My sql error in creating temporaty table stored procedure - mysql

I have a stored procedure query and inserting value in temp table.. but shows error
delimiter //
create procedure AccountLedgerViewUnderSundryDebtorCreditorCash()
begin
create temporary table temp_kk(accountGroupID varchar(50),HierarchyLevel varchar(50));
insert into temp_kk(accountGroupID,HierarchyLevel)
select accountGroupId, 1 as HierarchyLevel from tbl_AccountGroup
where accountGroupId='27'or accountGroupId = '28'or
accountGroupId = '11';
create temporary table temp_kk2(accountGroupID varchar(50),HierarchyLevel varchar(50));
insert into temp_kk2(accountGroupID,HierarchyLevel)
select e.accountGroupId, G.HierarchyLevel + 1 AS HierarchyLevel
from tbl_AccountGroup as e, temp_kk G
where e.groupUnder=G.accountGroupId ;
create temporary table temp_kk3(accountGroupID varchar(50),HierarchyLevel varchar(50));
insert into temp_kk3(accountGroupID,HierarchyLevel)
select * from temp_kk union all temp_kk2 ;
SELECT
ledgerId AS 'Account Ledger Id',
accountLedgerName AS 'Account Ledger Name',
accountGroupId AS 'Account Group Id',
openingBalance AS 'Opening Balance',
debitOrCredit AS 'Credit Or Debit',
defaultOrNot AS 'Editable Or Not',
description AS 'Description'
FROM tbl_AccountLedger
where accountGroupId IN (select accountGroupId from temp_kk3);
end //
delimiter ;
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 'temp_kk2 ; SELECT ledgerId AS [Account Ledger Id], acccountLedgerName' at line 20

This line:
select * from temp_kk union all temp_kk2 ;
Needs to be:
select * from temp_kk union all select * from temp_kk2 ;
At least, that what sticks out most obviously.
Though, I tend to avoid using select *. If you change the temp table, it will break. It also ends up making the code harder to read if you don't know for sure what all columns are in the table you're selecting from. Yes, it saves you some typing right now, but you'll lose that time-savings later on when you have to keep looking back at the table definition to figure out what exactly you're selecting.
Though, with these simple temp tables, it isn't as big of a deal.

Related

Django migration sql for conditional triggers

I want to create a trigger that only inserts into table when the condition is met.
I've tried using various combinations of IF/BEGIN/END and WHERE, but Django returns me an SQL syntax error each time.
Here, type_user_id refers to the person who triggers the like, and user_id refers to the person who receives the notification. It should only trigger when they are not the same person.
operations = [
migrations.RunSQL(
"DROP TRIGGER like_notification",
"""
CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article
FOR EACH ROW
IF (select user_id from channel WHERE channel_id IN
(SELECT channel_id FROM article WHERE article_id = NEW.article_id)) <> NEW.user_id
BEGIN
INSERT INTO notification (type, type_id, article_id, is_read, type_user_id, user_id)
VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id,
(SELECT user_id from channel WHERE channel_id IN
(SELECT channel_id FROM article WHERE article_id = NEW.article_id)
)
)
END;
"""
)
]
>>>django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for the right syntax
to use near 'BEGIN\n INSERT INTO notification (type, type_id, article_id, is_re' at line 5")
and
CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article
FOR EACH ROW
BEGIN
DECLARE #user_same Boolean;
SELECT 1 into #user_same
FROM channel
WHERE channel_id IN (select channel_id FROM article where article_id = NEW.article_id)
AND user_id = NEW.user_id;
IF #user_same <> 1
THEN
INSERT INTO notification (type, type_id, article_id, is_read, type_user_id, user_id,)
VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id, (
SELECT user_id from channel WHERE channel_id IN (
SELECT channel_id FROM article WHERE article_id = NEW.article_id)
)
END IF;
END;
>>>You have an error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near '#user_same Boolean;\n SELECT 1 into #user_same\n FRO' at line 4"
and
CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article
FOR EACH ROW
INSERT INTO notification (type, type_id, article_id, is_read, type_user_iduser_id)
VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id,
(
SELECT user_id from channel WHERE channel_id IN
(SELECT channel_id FROM article WHERE article_id = NEW.article_id)
)
WHERE NOT user_id = NEW.user_id;
>>>You have an error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near 'WHERE NOT user
I don't really understand why none of them work. Any help would be much appreciated!
#variables are not DECLARED.
Either:
DECLARE user_same BOOLEAN;
SELECT 1 INTO user_same WHERE ...
or
SELECT #user_same := 1 WHERE ...
Better yet, this avoids the need for the variable.
IF (EXISTS SELECT * FROM ...)
Also, don't use the construct IN ( SELECT ... ); it is usually better to use WHERE EXISTS ( SELECT * FROM ... ) or JOIN ... ON ....
(There may be more problems after fixing those.)
Another easy way to do this.
You should add any symbols between ; delimiters for the appropriate converting MySQL syntax to the raw SQL.
CREATE TRIGGER trigger_name BEFORE INSERT ON table
FOR EACH ROW
BEGIN
IF NEW.number <> 'anynumber' AND NEW.number <> 'anynumber'
THEN
SET NEW.number = 'anynumber'; --
END IF; --
END
This example works due to the dash symbols.

MySQL Error Code: 1265. Data truncated for column 'prod_code' at row 7

I'm using MySQL Workbench 5.7
I have the following table created and stored procedure:
DROP TABLE MV_SALESBYMONTH;
CREATE TABLE MV_SALESBYMONTH
(
`time_year` int, `time_month` int, `prod_code` int,`sale_units` int, `sale_price` int);
DELIMITER $$
CREATE procedure `REFRESH_MV_SALESBYMONTH` () BEGIN
TRUNCATE TABLE `MV_SALESBYMONTH`;
INSERT INTO MV_SALESBYMONTH
(SELECT TIME_YEAR AS 'YEAR', TIME_MONTH AS 'MONTH', PROD_CODE AS 'PRODUCT',
SUM(SALE_UNITS) AS 'UNITS SOLD', SUM(SALE_UNITS*SALE_PRICE) AS 'SALES TOTAL'
FROM TIME T, SALES S
WHERE S.TIME_ID = T.TIME_ID
GROUP BY TIME_YEAR, TIME_MONTH, PROD_CODE);
END $$
DELIMITER ;
STEP 5: Using the Materialized View
CALL REFRESH_MV_SALESBYMONTH();
SELECT * FROM MV_SALESBYMONTH;
When I try to run the statement:
CALL REFRESH_MV_SALESBYMONTH();
I get the error 1265: Data Truncated for column 'prod_code' at row 7
Define prod_code as varchar(100) in the create table statement. That way it can hold the maximum number of characters possible in the source data.

MySQL: Insert with conditional

I must perform the following situation down, but when you run got the 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 'INTO produto_seriais(serial_id) VALUES( SELECT id
FROM seriais WHERE serial =' at line 5
SELECT CASE WHEN (
SELECT COUNT(id) FROM seriais WHERE serial = '2020'
) > 1
THEN
(INSERT INTO produto_seriais(serial_id) VALUES(
SELECT id FROM seriais WHERE serial = '2020'
))
ELSE (
INSERT INTO seriais (serial) VALUE('2020');
SET #last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO produto_seriais (serial_id) VALUES (#last_id_in_table1);
)
END;
The case is as follows:
I'll get in "serial" table by serial "X". If it already exists, unless your ID in the "produto_seriais" table. If there is (serial), I will save the same, recover your ID and save to "produto_seriais". Any suggestions for how to do this?
Important Note: This routine will run will be thousands of times each execution (10,000 or more, depending on the quantity of serial).
P.s.: Sorry for my bad english.
Try a stored procedure
DELIMITER //
CREATE PROCEDURE sp_produto_seriais(IN `p_serial_id`)
IF EXISTS (SELECT * FROM seriais WHERE serial = p_serial_id )
BEGIN
INSERT INTO produto_seriais (serial_id)
SELECT id
FROM seriais
WHERE serial = p_serial_id
END
ELSE
BEGIN
INSERT INTO seriais (serial) VALUE(p_serial_id);
INSERT INTO produto_seriais (serial_id) VALUES (LAST_INSERT_ID());
END //
DELIMITER ;
usage:
CALL sp_produto_seriais('2020')
You could use the if exists..else statement.
If exists (select * from ....)
Begin
Insert into ... Select id from table
End
Else
Begin
Insert..
End
Please fill .... with your statements. You could use the link here to convert it for MySQL.
Convert if exists for MySQL

Trying hard to solve error 1064

I have tried hard but not getting the solutin regading sp below.. plz help !!
CREATE PROCEDURE AccountLedgerViewUnderBank()
begin
WITH GroupInMainGroup (accountGroupId,HierarchyLevel) AS
(
select accountGroupId,
1 as HierarchyLevel
from tbl_AccountGroup where accountGroupId='9'
UNION ALL
select e.accountGroupId,
G.HierarchyLevel + 1 AS HierarchyLevel
from tbl_AccountGroup as e,GroupInMainGroup G
where e.groupUnder=G.accountGroupId
)
SELECT
ledgerId AS 'Account Ledger Id',
acccountLedgerName AS 'Account Ledger Name'
FROM tbl_AccountLedger
where accountGroupId IN (select accountGroupId from GroupInMainGroup
)
end ; //
The error showing
ERROR 1064 (42000): 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 'Group
InMainGroup (accountGroupId,HierarchyLevel) AS
(
select accountGroupId,
1 a' at line 6
It looks like you're trying to use a CTE, which is not supported with MySQL (at time of writing).
Subqueries are supported with most versions of MySQL, so you may be able to rewrite it as something like:
CREATE PROCEDURE AccountLedgerViewUnderBank()
begin
SELECT ledgerId AS 'Account Ledger Id',
acccountLedgerName AS 'Account Ledger Name'
FROM tbl_AccountLedger
where accountGroupId
IN (select accountGroupId
from tbl_AccountGroup where accountGroupId='9'
UNION ALL
select e.accountGroupId
from tbl_AccountGroup as e,GroupInMainGroup G
where e.groupUnder=G.accountGroupId)
end ; //

Mysql sql error #1064

check the manual that corresponds to your MySQL server version for the right syntax to use near: 'SELECT count(*) FROM capacity
WHERE
server=NEW.server
AND
feed' at line 2
my code:
DROP TRIGGER IF EXISTS newsmonitoringrawdata.TNTInsertionTrigger;
CREATE TRIGGER TgtInsertionTrigger BEFORE INSERT ON tnews
FOR EACH ROW BEGIN
SET #isRecordCreated =
SELECT count(*) FROM capacity
WHERE
server=NEW.server
AND
feed=NEW.Feed
AND
date_Format(streamdt,'%Y-%m-%d %H:%i')=date_Format(NEW.StreamDT,'%Y-%m-%d %H:%i');
IF #isRecordCreated>0 THEN
UPDATE capacity
SET MsgNumber=MsgNumber+1,
size=size+NEW.MSize
WHERE
server=NEW.server
AND
feed=NEW.feed
and
date_Format(streamdt,'%Y-%m-%d %H:%i')=date_Format(NEW.StreamDT,'%Y-%m-%d %H:%i');
ELSE
INSERT INTO capacity(server, feed, streamdt, msgNumber, size)
VALUES
(
NEW.server,
NEW.feed,
date_Format(NEW.StreamDT,'%Y-%m-%d %H:%i:00'),
1,
NEW.size
);
END IF;
END
SET #isRecordCreated = (
SELECT count(*) FROM capacity
WHERE
server=NEW.server
AND
feed=NEW.Feed
AND
date_Format(streamdt,'%Y-%m-%d %H:%i')=date_Format(NEW.StreamDT,'%Y-%m-%d %H:%i')
);
You have to add parantheses () around the query.