Add a first day column to table with expression - mysql

I am using Below code to add a first day of the month column to the table with an expression to update automatically. But it's throwing a syntax error. someone pls do help.
ALTER TABLE `abc`.`t1`
ADD COLUMN `First_Day` DATE NULL DEFAULT select DATE_ADD(DATE_ADD(LAST_DAY(report_date),
INTERVAL 1 DAY),
INTERVAL - 1 MONTH) AFTER `Totals`;

mysql won't allow to use expressions for setting default values.
you can create trigger for this purpose.
delimiter $$
CREATE TRIGGER test_trigger BEFORE INSERT ON `product`
FOR EACH ROW SET
NEW.myCol= DATE_ADD(DATE_ADD(LAST_DAY(new.report_date),
INTERVAL 1 DAY),
INTERVAL - 1 MONTH);
END$$
delimiter;

I would question why you would wish to store this but if you must a generated column might do.
drop table if exists t;
create table t(id int, report_date date);
ALTER TABLE t
ADD COLUMN `First_Day` DATE as
(date_add(date_add(last_day(date(report_date)),interval 1 day),interval -1 month));
insert into t (id,report_date) values
(1,'2018-01-08'),(2,'2018-02-09');
select * from t;
+------+-------------+------------+
| id | report_date | First_Day |
+------+-------------+------------+
| 1 | 2018-01-08 | 2018-01-01 |
| 2 | 2018-02-09 | 2018-02-01 |
+------+-------------+------------+
2 rows in set (0.00 sec)
I you choose to go this way or via a trigger you will have to write a one off update to populate this column for existing data.

Related

Generating a date in a table SQL

I have a database in SQL which contains information about students and books they are borrowing.
I have a table of loans which includes the book_id, the student_id, the day the book was taken and the number of days the book can be kept.
I want to auto-generate the return_date by adding the days at the date in which the book was taken. How can I do this using MySQL Workbench?
You can use MySQL datetime function date_add() to compute the target return_date. Assuming that the date when the book was loaned is called loan_date and that the duration is stored in loan_duration, expressed in days:
select
book_id,
student_id,
loan_date,
date_add(loan_date, interval loan_duration day) return_date
from loan_table
In an update statement:
update loan_table
set return_date = date_add(loan_date, interval loan_duration day)
where return_date is null -- only compute the return_dates that were not yet computed
Edit
If you want that value to be auto-generated, an option is to use a generated stored (or virtual) column (available since MySQL 5.7). This works by defining a computation rule, that MySQL will automatically apply when a record is inserted or updated.
Demo on DB Fiddle:
-- set up
create table loan_table(
id int primary key auto_increment,
book_id int,
student_id int,
loan_date date,
loan_duration int,
-- here is the generated column
return_date date
as (date_add(loan_date, interval loan_duration day)) stored
);
-- perform an insert
insert into loan_table(book_id, student_id, loan_date, loan_duration)
values(1, 1, '2019-11-02', 3)
-- check the computed value
select * from loan_table;
id | book_id | student_id | loan_date | loan_duration | return_date
-: | ------: | ---------: | :--------- | ------------: | :----------
1 | 1 | 1 | 2019-11-02 | 3 | 2019-11-05
You can use a combination of interval and + :
select book_id
, student_id
, date_taken
, number_od_days
, (date_taken + interval number_od_days day) as return_date
from loans;
Here is the example in the DEMO
If you want this column to be auto incremented I suggest you create a trigger in your table:
CREATE TRIGGER rentcheck
BEFORE INSERT ON loans
FOR EACH ROW
begin
if new.number_od_days < 0 or new.number_od_days is null then
signal sqlstate '45000';
else
set new.return_date = (new.date_taken + interval new.number_od_days day);
end if;
end;
With it you can control if the column number_of_days will be negative or not entered because that would result with non logical data. Here is the demo for the trigger: DEMO
you can use variables in mysql:
set #days = 10;
set #mydate := DATE_ADD("2019-11-01", INTERVAL #days DAY);
select #mydate;
and then use your insert statement:
Insert into Loan(... ,[return_date])
values (...., #mydate)
Hope it helps

How to extract information from table to populate a CALENDAR table in a created data warehouse

I have a transaction table with an important column labeled TDate.
I need to use this column information to create a Calendar table.
TDate Example: 2013-1-1
In the Calendar Table, I must have Month, Day, Year in different columns.
What is a syntax to do so?
Try this, I think you are looking for it. Its just a simple use the YEAR, MONTH, DAY function to extract all these values and insert into different table as below.
create table test_2(TDate date);
insert into test_2 values(now());
select * from test_2;
create table calendar(year int, month int, day int);
insert into calendar select year(tdate) as year,month(tdate) as month, day(tdate) as day from test_2;
mysql> select * from calendar;
+------+-------+------+
| year | month | day |
+------+-------+------+
| 2018 | 5 | 5 |
+------+-------+------+
1 row in set (0.00 sec)

How to create a trigger updating 2 tables in MySql

I have 2 tables (in MySQL):
sales(sale_id, customer_id, sale_date, dicount, stock_item_id, seller_id, quantity)
record example:
a0018 | m9795 | 2017-10-2020 | 5 | MarFT | 0 | B-77028
stock(stock_item_id,supplier_name,supplier_email,supplier_phone,item_category item_name,wholesale_price,markup_price,items_in_stock)
record example:
B-77001 |BSN |direct#bsn.com | 1877333665 | Gainers | True Mass | 2.6kg | 33.75 |44.99 | 500
I need to create a trigger that will add a new record into sales table (recording a new sale, that will autoincrement). At the same time I want stock table to update 'items_in_stock' value (that should decrease by whatver quantity was just sold when there is match on stock_item_id)? I hope this makes sense. I'd appreciate any help. Thanks.
Use this:
DELIMITER $$
CREATE
TRIGGER `OnSalesInsert` BEFORE INSERT ON `Sales`
FOR EACH ROW BEGIN
UPDATE Stock
SET items_in_stock = items_in_stock - new.quantity
WHERE stock_item_id = new.stock_item_id;
END;
$$
DELIMITER ;

Trigger needs to fire only when column value is today's date

I want to apply the trigger in database when column_value match the particular scenario like
In goal table there are fields like goal, status, start_Date, end_Date
Now I want to change the status of goal. When user enter his/her goal, he/she filled end_Date. Now I want to change the status of goal when end_Date matched to current Date
Example:-
+------+--------+--------------+-------------+
| GOAL | STATUS | START_DATE | END_DATE |
+------+--------+--------------+-------------+
| 1 | Active | 2017-07-03 | 2017-07-09 |
+------+--------+------------+---------------+
When END_DATE equals to current Date, then I want to change status 'Active' to 'Finished'
I hope I am able to understand my question.
Thanks in advance!
Body of an oracle table level trigger would look like this...
BEGIN
IF INSERTING and (:new.end_date = sysdate) THEN
:NEW.goal_status := desired_value;
ELSIF UPDATING AND (:new.end_date = sysdate) then
:NEW.goal_status := desired_value;
END IF;
End;
The logic for this is
DROP TRIGGER IF EXISTS TB;
DELIMITER //
CREATE TRIGGER TB BEFORE INSERT ON T
FOR EACH ROW
BEGIN
IF NEW.START_DT = DATE(NOW()) THEN
SET NEW.STATUS = 'YES' ;
end if;
END //
DELIMITER ;
use sandbox;
DROP TABLE IF EXISTS T;
CREATE TABLE T(GOAL INT, STATUS VARCHAR(3), START_DT DATE,END_DATE DATE);
mysql> TRUNCATE TABLE T;INSERT INTO T VALUES(1,NULL,'2017-07-06','2017-07-06');SELECT * FROM T;
Query OK, 0 rows affected (0.73 sec)
Query OK, 1 row affected (0.06 sec)
+------+--------+------------+------------+
| GOAL | STATUS | START_DT | END_DATE |
+------+--------+------------+------------+
| 1 | YES | 2017-07-06 | 2017-07-06 |
+------+--------+------------+------------+
1 row in set (0.00 sec)

Move rows from TableA into Table-Archive

Is it possible to move rows that are 3 days old into an other table called "Table_Archive" automatically in mysql ones a week?
tableA ex:
ID | stringvalue | Timestamp
1 | abc | 2011-10-01
2 | abc2 | 2011-10-02
3 | abc3 | 2011-10-05
4 | abc4 | 2011-10-10
5 | abc5 | 2011-10-11
After the move
tableA:
ID | stringvalue | Timestamp
4 | abc4 | 2011-10-10
5 | abc5 | 2011-10-11
Table_Archive:
ID | stringvalue | Timestamp
1 | abc | 2011-10-01
2 | abc2 | 2011-10-02
3 | abc3 | 2011-10-05
And when new input comes into tableA it wont be any problems with ID (PK) in the next move?
What Ive got:
CREATE PROCEDURE clean_tables ()
BEGIN
BEGIN TRANSACTION;
DECLARE _now DATETIME;
SET _now := NOW();
INSERT
INTO Table_Archive
SELECT *
FROM TableA
WHERE timestamp < _now - 3;
FOR UPDATE;
DELETE
FROM TableA
WHERE timestamp < _now - 3;
COMMIT;
END
How do I change _now to be the date 3 days ago?
Personally, I would make use of the MySQL Event Scheduler. This is a built in event scheduler rather like CRON in Linux.
You can specify it to call a procedure, procedures or functions or run a bit of SQL at designated intervals.
Read the MySQL docs but an example would be:
CREATE EVENT mydatabase.myevent
ON SCHEDULE EVERY 1 WEEK STARTS CURRENT_TIMESTAMP + INTERVAL 10 MINUTE
DO
call clean_tables();
So this is saying "call clean_tables() once a week and make the first call in 10 minutes' time"
One gotcha is that the event scheduler is (I think) disabled by default. To turn it on run:
SET GLOBAL event_scheduler = ON;
You can then run:
SHOW PROCESSLIST;
To see whether the event scheduler thread is running.
As for preserving your Table A ID column (if you must). I would keep the ID on Table_Archive as unique to that table i.e make it the primary key & auto_increment and then have a 'Original_TableA_ID' column in which to store the TableA ID. You can put a unique index on this if you want.
So Table_Archive would be like:
create table `Table_Archive` (
ID int unsigned primary key auto_increment, -- < primary key auto increment
tableAId unsigned int not null, -- < id column from TableA
stringValue varchar(100),
timestamp datetime,
UNIQUE KEY `archiveUidx1` (`tableAId`) -- < maintain uniqueness of TableA.ID column in Archive table
);
Nobody seems to have answered your original question "How do I change _now to be the date 3 days ago?". You do that using INTERVAL:
DELIMITER $
CREATE PROCEDURE clean_tables ()
BEGIN
BEGIN TRANSACTION;
DECLARE _now DATETIME;
SET _now := NOW();
INSERT
INTO Table_Archive
SELECT *
FROM TableA
WHERE timestamp < _now - interval 3 day;
FOR UPDATE;
DELETE
FROM TableA
WHERE timestamp < _now - interval 3 day;
COMMIT;
END$
DELIMITER ;
One final point is that you should consider creating an index on the timestamp column on TableA to improve the performance of you clean_tables() procedure.
You may need to have a look into cron jobs if you want that script/query to be executed automatically.
If you are using cpanel have a look into http://www.siteground.com/tutorials/cpanel/cron_jobs.htm
Adding to the best answer (imo) by Tom Mac regarding the event scheduler - be aware that when backing up the schema, you have to specify that you want the events backed up with it via the --events=TRUE flag.
If you're exporting manually in the workbench, the latest version has a checkbox on the main 'Export To Disk' tab - older versions hide it away in the Advanced Export Options tab.
It is possible, MySQL will execute query automatically at specific time using MySQL Event Scheduler. Check this link for more details.
https://dev.mysql.com/doc/refman/5.7/en/event-scheduler.html