How to automatic truncate table in MySQL every 3 months? - mysql

I have a PHP/MySQL project having 15 tables. One of table name tbl_user_log, where all user log will saved. I want to empty or truncate this table in every 3 month.How could I do this using trigger or any solution is applicable.

You can set a cronjob to a certain route of your project to perform following sql:
DELETE FROM tbl_user_log
See this website: http://setcronjob.com
Or you can simply use mysql EVENTs.

It may helps you
declare #tbl nvarchar(max)='table_name'
if (
(select create_date FROM
sys.tables where name=#tbl)
<= (SELECT DATEADD(month,-3, GETDATE()))
begin
truncate table #tbl
end
else
select 'table creation date is not more than 3 months'
better you can put this in a procedure and u can directly pass table name as input and can wrk efficently

Related

how to set limit on table containing record

I am using mySQL
Is there any way to set limit of table record/row? I have table X and want to set limit of total records/rows on table, for example 2rows. So no one can insert third record in table. This table should not allow to insert third record.
I do not want to use Triggers.
You can do it this the user grants, so the user cant write into this table and you can create a separate User for administration this table.
seee Manual : https://mariadb.com/kb/en/mariadb/grant/
If you dont want to use triggers, you 'll have to check the number of rows inside your application (if any).
Create an AFTER INSERT trigger on the table. - it's the only way to do it.
create trigger TableLimit
on TableName
after insert
as
declare #countTableRows int
select #countTableRows = Count(*)
from TableName
if #countTableRows > 2
begin
rollback
end
go

sql refer row on masive insert using a stored procedures - mysql

I have a table task, this table contains information of recurring tasks, fox example daily tasks, so I repeat each task because I want to know the result of each task over time
1/1/2014 Get Pizza OK
1/2/2014 Get Pizza OK
1/3/2014 Get Pizza Error
1/4/2014 Get Pizza OK
For this I made a stored procedure
DELIMITER $$
CREATE DEFINER=`db`#`%` PROCEDURE `SP_repeat_task`()
BEGIN
INSERT INTO Task
(
date_of_assignment,
Some fields
)
SELECT
DATE_ADD(tas.date_of_assignment, INTERVAL 1 DAY),
another fields
FROM Task tas
WHERE tas.date_of_assignment=CURRENT_DATE and many conditions
)
;
END
This procedure is invoked every day 5 minutes before midnight. And produces something like this
The problem is that I have to insert the id of the records added in another table
For example
When I add 4 tasks in insert-select statement i need add these to another table
In my case, there can be multiple records for each task.
I can easily obtain id_person in my select, but not how to use it in the next insert.
I cant change the structure of the tables, I have only my stored procedure to work
I read about mysqli_insert_id, but not how to use it in my case
EDIT
based in b.b3rn4rd answer
When i add the other field in cursor select
DECLARE records_to_clone_cursor CURSOR FOR
SELECT `field1`, `field2`, `field3` FROM `Task` WHERE ... ;
In FETCH return more rows because as there is a one to many relationship in my tables
so the query returns with old fields
DECLARE records_to_clone_cursor CURSOR FOR
SELECT `field1`, `field2` FROM `Task` WHERE ... ;
And i tried change the prepared statement for a classic Insert-Select
SET #NEW_ID = LAST_INSERT_ID();
INSERT INTO Another_table
(
id_task,
id_person
)
SELECT tas.id_task,
pe.id_person
FROM Task tas
INNER JOIN Person pe
ON pe.id_person = tas.id_assigned
WHERE tas.id_task= #NEW_ID;
-- EXECUTE insert_responables USING #NEW_ID, #Var_3;
But does nothing, first prepared works well, and Select-Inser work in nornal query.
that I can do?
EDIT 2
if I need to insert the values​​, but because they are different cause the cursor query returns more records and these are duplicated by the number of records in the field is_person

How to generate Sequential User Code using MySQL Trigger?

I have created a MySQL Trigger BEFORE INSERT on table name agent_mst as below
BEGIN
DECLARE max_id INT;
SET max_id=(SELECT MAX(agent_id_pk)+1 FROM `agent_mst`);
IF (max_id IS NULL) THEN
SET max_id=1;
END IF;
SET NEW.date_added=NOW(),
NEW.date_updated=NOW(),
NEW.agent_code = CONCAT('SDA', LPAD(max_id, 4,'0'));
END
So what it does is, every time we inset a record, it generates agent_code field value to something like SDA0001, SDA0002, SDA0003, ...
Now suppose I delete a record with code SDA0003 and insert new record, it will definitely generate the agent code as SDA0004. As it is taking the max_id and increasing it with 1. But here I want to get SDA0003 again. So that all agent_codes can stay in sequence. How to do that?
Thanks in advance.
you need to identify the first (smallest) missing id.
check out in this link, a nice way to do it in a select query:
Find mininum not used value in mysql table
To know next auto increment id try to run below query and check column "Auto_increment":
SHOW TABLE STATUS FROM DBName where name = 'tableName'

Save/Update List of Dates in Database

I'm using SQL Server 2008. I'm looking for a creative way to save and update a list of dates in our database.
I'm going to collect a list of dates from the application and I will need to check if each value already exists, if not add, and then delete any dates not in the list that are already stored in the database.
The easiest thing I can think of is to delete all dates associated to this particular request and then iterate over each item in my list and insert into database.
Does anyone have a more elegant idea?
You can use merge. You can also load the dates into a temporary table and do an insert such as:
with toinsert as (
select thedate
from #newdates nd left outer join
alldates ad
on nd.thedate = ad.thedate
where ad.thedate is null
)
insert into alldates(thedate)
select thedate
from toinsert
The toinsert alias uses a left outer join to do a "not in". I often find that this works better. Regardless of how you set up the queries (like this or with a merge), you should put in an index on the dates. It should make things go faster.
I would use a combination of table valued parameters and the NOT EXISTS function. So pass your dates from your application to a stored procedure as a paramater, the stored procedure will then return a list of all the dates inserted back to your application.#
The first step is to create the type so you can pass a list of dates to your procedure:
CREATE TYPE dbo.DateListType AS TABLE (Date DATETIME)
Next create your procedure. I have assumed you date table is called dbo.Dates, you'll obviously need to substitute your table in for this.
CREATE PROCEDURE dbo.InsertDates (#Dates dbo.DateListType READONLY)
AS
BEGIN
DECLARE #Inserted TABLE (Date DATETIME)
INSERT INTO dbo.Dates
OUTPUT inserted.Date INTO #Inserted
SELECT Date
FROM #Dates d
WHERE NOT EXISTS
( SELECT 1
FROM dbo.Dates
WHERE Dates.Date = d.Date
)
SELECT Date
FROM #Inserted
END
Not sure what your application is coded in so unfortunately can't suggest any code to call the procedure

How to call a stored procedure and alter the database table in 1 go

I'm really struggeling with this for some time now.
I have a MySQL database and a lot of data. It is a formula1 website i have to create for college.
Right now the j_tracks_rounds_results table is filled with data but one column is not filled out. It's the rank column.
I created a stored procedure as the following:
DROP PROCEDURE `sp_rank`//
delimiter ##
PROCEDURE `sp_rank`(sid INT)
begin
set #i = 0;
SELECT `performance`, subround_id, #i:=#i+1 as rank
FROM `j_tracks_rounds_results`
where subround_id = sid
order by `subround_id`,`performance`;
end
delimiter ;
The output is like the following:
rec.ID PERFORMANCE SUBROUND_ID RANK
87766 100,349114516829 1 1
93040 101,075635087628 1 2
88851 101,664302543497 1 3
It gets the results and ads a rank to it, sorted on performance so the lowest performance gets rank1 etc...
What i am trying to achieve is to put the rank back into the table. Like an ALTER command for the column "rank".
How would i be able to accomplish this?
Basically don't...
Create table to hold the key (rec.id ?) and the rank. Truncate it to get rid of the previous results then use insert into ... with your query and then join to it.
You really don't want to be altering tables in your normal running, guaranteed some one will use the column when it isn't there, and then when you look at the fault it will be...
People just don't look for table structures changing through the application lifetime, it's a screw up waiting to happen.
You are misapplying your SQL statements. You want the UPDATE command, not ALTER.
eg.
UPDATE table SET rank=#i WHERE subround_id=#id