stored procedure in mysql in ubuntu - mysql

I have created stored procedure in MySQL in Window-7. it run successfully on windows. But when I switch to Ubuntu it gives error in the stored procedure. On windows I am using SQLyog for creating stored procedure. On Ubuntu, I run the SQL script and call that stored procedure but it gives error. Below is my stored procedure.
DELIMITER $$
USE `adserver`$$
DROP PROCEDURE IF EXISTS `getDaypartTimeDetail`$$
CREATE DEFINER=`root`#`localhost` PROCEDURE `getDaypartTimeDetail`
(currentDate DATE,noOfdays INT,cityId BIGINT)
BEGIN
DECLARE i INT;
DECLARE dateCnt INT;
SET dateCnt = 0;
DROP TEMPORARY TABLE IF EXISTS OnlyDate;
DROP TEMPORARY TABLE IF EXISTS AdvScheduleData;
CREATE TEMPORARY TABLE OnlyDate(dday DATE);
CREATE TEMPORARY TABLE AdvScheduleData(dday BIGINT,daypartId INT,totalFile BIGINT,totalDur BIGINT);
/* Generate Dates */
WHILE(dateCnt < noOfdays) DO
SET i = 1;
INSERT INTO OnlyDate(dday) VALUES (DATE_ADD(currentDate, INTERVAL dateCnt DAY));
SET dateCnt = dateCnt + 1;
END WHILE;
/* Insert all dayparts for all dates */
INSERT INTO AdvScheduleData (dday, daypartID) SELECT (UNIX_TIMESTAMP(dday)*1000), id FROM OnlyDate, daypart;
/* Update total files and duration */
UPDATE AdvScheduleData SET
TotalFile = (SELECT COUNT(advt_id)
FROM adv_schedule AdvSch
INNER JOIN advertisement Adv ON Adv.id = AdvSch.advt_id
WHERE AdvScheduleData.dday BETWEEN AdvSch.start_date AND AdvSch.end_date
AND AdvSch.status = 2
AND AdvSch.active = 1
AND AdvSch.id IN (SELECT schedule_id FROM schedule_daypart
WHERE daypart_id = AdvScheduleData.daypartId )
AND AdvSch.id IN (SELECT schedule_id FROM schedule_cities WHERE city_id = cityId)
AND Adv.is_active = 1
AND Adv.is_deleted = 0
AND Adv.status = 2
AND Adv.expiry_date >= AdvScheduleData.dday),
totalDur = (SELECT SUM(Adv.duration)
FROM adv_schedule AdvSch
INNER JOIN advertisement Adv ON Adv.id = ADVSCH.advt_id
WHERE AdvScheduleData.dday BETWEEN AdvSch.start_date AND AdvSch.end_date
AND AdvSch.status = 2
AND AdvSch.active = 1
AND AdvSch.id IN (SELECT schedule_id FROM schedule_daypart
WHERE daypart_id = AdvScheduleData.daypartId )
AND AdvSch.id IN (SELECT schedule_id FROM schedule_cities WHERE city_id = cityId)
AND Adv.is_active = 1
AND Adv.is_deleted = 0
AND Adv.status = 2
AND Adv.expiry_date >= AdvScheduleData.dday);
SELECT * FROM AdvScheduleData;
END$$
DELIMITER ;
The output I get in Ubuntu is
mysql> call getDaypartTimeDetail('2012-08-13',5,30534); ERROR 1054
(42S22): Unknown column 'ADVSCH.advt_id' in 'on clause'

Table name and aliases are case sensitive in Ubuntu.
Hence, this reference is giving an error:
totalDur = (SELECT SUM(Adv.duration)
FROM adv_schedule AdvSch
INNER JOIN advertisement Adv ON Adv.id = ADVSCH.advt_id
Change it to AdvSch.advt_id

Related

Mysql after insert trigger is giving error

I have written below after insert trigger and it didnt give me any error. But whenever I am trying to insert data into sept18.test I am getting below error
Error Code: 1442. Can't update table 'test' in stored function/trigger
because it is already used by statement which invoked this stored
function/trigger. 0.000 sec
Can someone please help me with this error. Thank you in adavance.
-- SELECT * FROM INFORMATION_SCHEMA.TRIGGERS WHERE TRIGGER_NAME = 'TR_ORDERS_INS'
DROP TRIGGER IF EXISTS TR_ORDERS_INS;
DELIMITER $$
CREATE TRIGGER TR_ORDERS_INS
AFTER INSERT ON sept18.test for each row
BEGIN
DECLARE MAX_DATE1 DATETIME;
IF EXISTS
(
select 1 from ept18.test O
where O.STOREID = NEW.STOREID
AND O.ITEMID = NEW.ITEMID
AND O.ORDERDATE = NEW.ORDERDATE
)
THEN
SET MAX_DATE1 = (SELECT max(DateTimeStamp)
from sept18.test
where itemid = NEW.itemid
and storeid = NEW.storeid
and OrderDate = NEW.orderdate);
INSERT INTO sep18kentest.orders_history
(ORDERID,STOREID,ITEMID,ORDERDATE,QUANTITY,BONUSBUCK,FLATBONUSBUCK,PRICE,STOREPRICE,PRICEOVERRIDE,
PRICEOVERRIDEFLAG,DIRECTSHIPFLAG,FREEITEMFLAG,SRP,DATETIMESTAMP,RECORDNUMBER)
SELECT ORDERID,STOREID,ITEMID,ORDERDATE,QUANTITY,BONUSBUCK,FLATBONUSBUCK,PRICE,STOREPRICE,PRICEOVERRIDE,
PRICEOVERRIDEFLAG,DIRECTSHIPFLAG,FREEITEMFLAG,SRP,DATETIMESTAMP,RECORDNUMBER
FROM sept18.test OD
WHERE OD.storeid = NEW.storeid
and OD.itemid = NEW.itemid
and OD.orderdate = NEW.orderdate
and OD.DateTimeStamp < MAX_DATE1;
DELETE FROM sept18.test
WHERE storeid = NEW.storeid
and itemid = NEW.itemid
and orderdate = NEW.orderdate
and DateTimeStamp < MAX_DATE1;
END IF;
END$$

MySQL migrate data from one table to another

I'm attempting to move data from one table to another, as part of a restructure to the database architecture. I'm using PHPMyAdmin and MySQL to do so.
The SQL is meant to, for each emergency_contacts.id, move e_c.id and e_c.activity_id to activities_emergency_contacts, where the pair will form a composite key to link a contact with an activity.
The following SQL returns an error:
CREATE PROCEDURE dowhile()
BEGIN
SET #cid = (SELECT MIN(`id`) FROM `emergency_contacts`);
SET #aid = (SELECT `activity_id` FROM `emergency_contacts` WHERE `id` = #cid);
WHILE #cid IS NOT NULL DO
INSERT INTO activities_emergency_contacts (activity_id, contact_id)
VALUES (#aid, #cid);
SET #cid = (SELECT MIN(id) FROM emergency_contacts WHERE #cid < id);
SET #aid = (SELECT activity_id FROM emergency_contacts WHERE id = #cid);
END WHILE;
END;
CALL dowhile();
SQL query:
CREATE PROCEDURE dowhile() BEGIN SET #cid = (SELECT MIN(id) FROM
emergency_contacts)
MySQL said:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3
I have searched the MySQL specific documentation to try and find any issues with my SET, WHILE, BEGIN/END, INSERT, CREATE - just about every line. I'm unsure how to proceed. Any advice would be greatly appreciated.
EDIT: I missed a closing bracket inside the WHILE on SELECT MIN (id), however I've fixed this and am still getting the exact same issue.
EDIT: The issue was that I was not using DELIMITER. Correct SQL:
DELIMITER $$
CREATE PROCEDURE dowhile()
BEGIN
SET #cid = (SELECT MIN(`id`) FROM `emergency_contacts`);
SET #aid = (SELECT `activity_id` FROM `emergency_contacts` WHERE `id` = #cid);
WHILE #cid IS NOT NULL DO
INSERT INTO activities_emergency_contacts (activity_id, contact_id) VALUES (#aid, #cid);
SET #cid = (SELECT MIN(id) FROM emergency_contacts WHERE #cid < id);
SET #aid = (SELECT activity_id FROM emergency_contacts WHERE id = #cid);
END WHILE;
END$$
DELIMITER ;
CALL dowhile();

declaring variable inside mysql stored procedure

we are trying to declare a variable inside mysql stored procedure that has transaction implemented in it. but it seems to be giving a syntax error :
following is the syntax of the stored procedure:
CREATE PROCEDURE `sp_MarkAppointmentRefferal`(
p_AppId bigint,
p_NewLocation bigint,
p_userId bigint,
p_ReferralReason varchar(500),
p_NewLocationName varchar(100)
)
begin
declare v_OldLocation int default 0;
set v_OldLocation = (select LocationId FROM appointments where iAppID = p_AppId limit 1 );
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
select -1;
END;
START TRANSACTION;
update table
set is_referred = 1,
referred_timestamp = now(),
referral_reason = p_ReferralReason
where iAppID = p_AppId
limit 1;
-- create a new appointment for the new referred location..
insert into appointments
(vAppName, vAppType, dAppDate, vCell, iPatID, iAppStatus, iuserid, iActive,
dInsertDate, iHSID, daily_ticket_no, LocationId, visit_id, encounter_id, ReferredFrom,ReferredOPDName, opd_name )
select vAppName, vAppType, now(), vCell, iPatID, iAppStatus, p_userId,
1, now(), iHSID, fn_GenerateNextAppointmentTicket(now(),p_NewLocation) , p_NewLocation, visit_id, encounter_id+1,
(select LocationId FROM appointments where iAppID = p_AppId limit 1),
(select OPD_Name FROM appointments where iAppID = p_AppId limit 1), p_NewLocationName
FROM appointments
where iAppID = p_AppId limit 1;
select LAST_INSERT_ID();
COMMIT;
end;
the syntax checker is saying that declare command is not valid here.
have also tried to place this inside the transaction clause and similar error shows up ..
any help is appreciated..
All declare statements should be at the top of the stored procedure body. Moving DECLARE EXIT HANDLER before the SET statement should fix the problem.

How to Create Trigger After Insert with select data from Multiple table with Join in MYSql

I am trying to Create Trigger in MySQL with Select Column data from Join multiple table. But Trigger is not allow me to DECLARE temp variable.
I would like to join 4 table on the bases of newly inserted record in one table and select the data from different table and insert r update in another table (DashboardStatus)
I am getting error [ SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET _BedId = (SELECT bd.BedId
FROM LifetouchHeartRate lthr
JOIN Device' at line 4 */ ]
CREATE TABLE `dashboardstatus` (
`LTHR` INT(11) NULL DEFAULT NULL,
`BedId` INT(11) NULL DEFAULT NULL
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
CREATE TRIGGER triggerDashboard AFTER INSERT ON LifetouchHeartRate for each row
BEGIN
DECLARE _BedId INT
SET _BedId = (SELECT bd.BedId As _BedId
FROM LifetouchHeartRate lthr
JOIN DeviceSession ds ON ds.DeviceSessionID = lthr.ByDevSessionId
JOIN PatientSession ps ON ps.PatientSessionId = ds.ByPatientSessionId
JOIN PatientDetails pd ON pd.PatientDetailsId = ps.ByPatientId
JOIN BedDetails bd ON bd.BedDetailsId = pd.ByBedId
WHERE lthr.LifeTouchHeartRateID = new.LifeTouchHeartRateID Limit 1 );
IF _BedId > 0
BEGIN
INSERT OR REPLACE INTO DashboardStatus (LTHR, BedId) VALUES ( new.LifeTouchHeartRateID, _BedId)
END
END
Remember ;
...
CREATE TRIGGER triggerDashboard AFTER INSERT ON LifetouchHeartRate for each row
BEGIN
-- DECLARE _BedId INT
DECLARE _BedId INT;
...
UPDATE
DELIMITER //
CREATE TRIGGER triggerDashboard AFTER INSERT ON LifetouchHeartRate
FOR EACH ROW
BEGIN
-- DECLARE _BedId INT
DECLARE _BedId INT;
SET _BedId = (SELECT bd.BedId As _BedId
FROM LifetouchHeartRate lthr
JOIN DeviceSession ds ON ds.DeviceSessionID = lthr.ByDevSessionId
JOIN PatientSession ps ON ps.PatientSessionId = ds.ByPatientSessionId
JOIN PatientDetails pd ON pd.PatientDetailsId = ps.ByPatientId
JOIN BedDetails bd ON bd.BedDetailsId = pd.ByBedId
WHERE lthr.LifeTouchHeartRateID = new.LifeTouchHeartRateID Limit 1 );
/*IF _BedId > 0
BEGIN
INSERT OR REPLACE INTO DashboardStatus (LTHR, BedId) VALUES ( new.LifeTouchHeartRateID, _BedId)
END
END*/
IF _BedId > 0 THEN
-- BEGIN
INSERT INTO DashboardStatus (LTHR, BedId) VALUES ( new.LifeTouchHeartRateID, _BedId);
-- END
END IF;
END//
DELIMITER ;
SQL Fiddle demo

MySql Error 1054 when inserting into table that has trigger

I have created a trigger on a table, and when I try to insert data into it I get MySql error "Error Code: 1054 'unknown column license_key in field list'"
The INSERT I try to do is this:
INSERT INTO LOAD_MASTER(license_key, state, total_pageviews, total_visitors, max_visitors, max_pageviews, ip, secret, read_time, url)
VALUES ("order55555hytgtrfderfredfredfredftyu8ikloi98nhygt6", "preparing", 400, 1000, 200, 400, "202,2,35,36", "Hemmeligheden", 120, "http://google.dk");
The Trigger I have created is supposed to check the TABLE LOAD_STATS for the presence of the IP entered in the LOAD_MASTER table, and then based on the results change a value in another table called LICENSE
My trigger is here:
DELIMITER //
CREATE TRIGGER ip_check AFTER INSERT ON LOAD_MASTER FOR EACH ROW
BEGIN
DECLARE MK varchar(50);
DECLARE MIP varchar(15);
DECLARE LID int(6);
SET MK = license_key;
SET MIP = ip;
SET LID = (
SELECT l.license_id
FROM license_keys k, license l
WHERE l.license_id = k.license_id
AND k.license_key = MK
);
IF (SELECT COUNT(DISTICT(master_ip)) FROM LOAD_STATS WHERE master_ip = MIP AND master_key = MK ) > 3 THEN
UPDATE LICENSE
SET STATE = 0
WHERE license_id = LID;
END IF;
END
//
DELIMITER ;
Any help on why I get this error would be much appriciated.
-Dan
In these lines
SET MK = license_key;
SET MIP = ip;
you probably meant to address NEW.license_key and NEW.ip respectively.
IMHO you can make more succinct. Try this
DELIMITER //
CREATE TRIGGER ip_check
AFTER INSERT ON load_master
FOR EACH ROW
BEGIN
IF (SELECT COUNT(DISTICT(master_ip))
FROM load_stats
WHERE master_ip = NEW.ip
AND master_key = NEW.license_key ) > 3 THEN
UPDATE license
SET state = 0
WHERE license_id =
(
SELECT l.license_id
FROM license_keys k JOIN license l
ON l.license_id = k.license_id
AND k.license_key = NEW.license_key
); -- make sure that this subquery returns only ONE record
END IF;
END //
DELIMITER ;
There is some room for improvement rewriting an UPDATE with JOIN instead of using a subquery