MySQL: What's wrong with this CREATE PROCEDURE statement? - mysql

DROP PROCEDURE IF EXISTS CreateTopic;
CREATE PROCEDURE CreateTopic
(
i_forum_id INT,
i_user_id INT,
i_title VARCHAR(255),
i_language VARCHAR(50),
i_content TEXT,
i_stickied TINYINT,
i_announce TINYINT,
i_closed TINYINT
)
BEGIN
INSERT INTO forum_topics (forum_id, user_id, title, language)
VALUES (i_forum_id, i_user_id, i_title, i_language);
SET #tid := LAST_INSERT_ID();
INSERT INTO forum_posts (topic_id, user_id, subject, content) VALUES (#tid, i_user_id, i_title, i_content);
INSERT INTO core_logs (obj_id, user_id, type, action) VALUES (#tid, i_user_id, 'Topics', 'Topic Created');
END;
I'm not sure what's wrong with it. MySQL tells me all sorts of things are incorrect, it just doesn't want to be created. Also, the parameters are identical types and lengths to their respective tables.

It is your first ";" that breaks procedure definition and mysql thinks you are done and treats whatever goes after ";" as another query.
You have to use delimiter for stored procedures.
DELIMITER $$
DROP PROCEDURE IF EXISTS CreateTopic$$
CREATE PROCEDURE CreateTopic
(
i_forum_id INT,
i_user_id INT,
i_title VARCHAR(255),
i_language VARCHAR(50),
i_content TEXT,
i_stickied TINYINT,
i_announce TINYINT,
i_closed TINYINT
)
BEGIN
INSERT INTO forum_topics (forum_id, user_id, title, language)
VALUES (i_forum_id, i_user_id, i_title, i_language);
SET #tid := LAST_INSERT_ID();
INSERT INTO forum_posts (topic_id, user_id, subject, content) VALUES (#tid, i_user_id, i_title, i_content);
INSERT INTO core_logs (obj_id, user_id, type, action) VALUES (#tid, i_user_id, 'Topics', 'Topic Created');
END
$$
DELIMITER ;

There are a few problems. I hope I got them all:
DROP PROCEDURE IF EXISTS CreateTopic;
CREATE PROCEDURE CreateTopic
(
i_forum_id INT,
i_user_id INT,
i_title VARCHAR(255),
i_language VARCHAR(50),
i_content TEXT,
i_stickied TINYINT,
i_announce TINYINT,
i_closed TINYINT
)
BEGIN
DECLARE tid INT;
INSERT INTO forum_topics (`forum_id`, `user_id`, `title`, `language`)
VALUES (i_forum_id, i_user_id, i_title, i_language);
SET tid = LAST_INSERT_ID();
INSERT INTO forum_posts (`topic_id`, `user_id`, `subject`, `content`) VALUES (tid, i_user_id, i_title, i_content);
INSERT INTO core_logs (`obj_id`, `user_id`, `type`, `action`) VALUES (tid, i_user_id, 'Topics', 'Topic Created');
END;

Related

how can I form a stored procedure in mysql, which can first check multiple values on multiple tables and then insert into db if true

The actual problem statement looks like :
• Product(prod_id, prod_name, qty_on_hand)
• Order(cust_id, prod_id, order_date, qty_ordered)
• Customer(cust_id, cust_name, phone, address)
"Write a stored procedure to take the cust_id, prod_id and qty_ordered as
input. Procedure should check if the order for a particular customer can be
fulfilled and if yes then insert the new order and update the product
quantity on hand. Display appropriate message if the order cannot be
fulfilled.
Output parameter must have updated value of the qty_on_hand"
I am new to plsql so ignore silly mistakes. I tried to code something like this :
delimiter $$
-- creating procedure
CREATE PROCEDURE order_request( cust_id int, prod_id int, qty_ordered int)
BEGIN
IF( customer.cust_id != cust_id AND product.prod_id != prod_id AND qty_ordered > product.qty_on_hand) THEN
SELECT 'invalid details' ;
ELSE INSERT INTO `orders` (`cust_id`, `prod_id`, `order_date`, `qty_ordered`) VALUES (cust_id, prod_id, current_date(), qty_ordered) ;
END IF ;
END $$
CALL order_request(3,3,2)$$
which showing me error : unknown table customer in field list
I have solved the question. Here is the solution:
CREATE DATABASE shopping;
USE shopping;
CREATE TABLE product( prod_id INT PRIMARY KEY, prod_name varchar(20), qty_on_hand INT CHECK(qty_on_hand >= 0));
CREATE TABLE customer( cust_id INT PRIMARY KEY, cust_name varchar(20), phone INT, address varchar(20) );
-- product table insertion
INSERT INTO `product` (`prod_id`, `prod_name`, `qty_on_hand`) VALUES ('1', 'mug', '2');
INSERT INTO `product` (`prod_id`, `prod_name`, `qty_on_hand`) VALUES ('2', 'bowl', '15');
INSERT INTO `product` (`prod_id`, `prod_name`, `qty_on_hand`) VALUES ('3', 'plate', '7');
INSERT INTO `product` (`prod_id`, `prod_name`, `qty_on_hand`) VALUES ('4', 'fork', '40');
INSERT INTO `product` (`prod_id`, `prod_name`, `qty_on_hand`) VALUES ('5', 'spoon', '30');
-- customer table insertion
INSERT INTO `customer` (`cust_id`, `cust_name`, `phone`, `address`) VALUES ('1', 'duke', '1212121212', 'pune');
INSERT INTO `customer` (`cust_id`, `cust_name`, `phone`, `address`) VALUES ('2', 'finn', '190120138', 'waterland');
INSERT INTO `customer` (`cust_id`, `cust_name`, `phone`, `address`) VALUES ('3', 'buck', '98989898', 'delhi');
INSERT INTO `customer` (`cust_id`, `cust_name`, `phone`, `address`) VALUES ('4', 'larry', '738197232', 'jaipur');
INSERT INTO `customer` (`cust_id`, `cust_name`, `phone`, `address`) VALUES ('5', 'edna', '184194791', 'mumbai');
CREATE TABLE orders( cust_id INT, prod_id INT, order_date DATE, qty_ordered INT CHECK(qty_ordered > 0) , FOREIGN KEY (cust_id) REFERENCES customer(cust_id), FOREIGN KEY (prod_id) REFERENCES product(prod_id));
-- orders table insertion
INSERT INTO `orders` (`cust_id`, `prod_id`, `order_date`, `qty_ordered`) VALUES ('1', '2', '2022-09-15', '2');
delimiter $$
-- creating procedure
CREATE PROCEDURE order_request( cust_id_param INT, prod_id_param INT, qty_ordered_param INT)
BEGIN
IF EXISTS (SELECT cust_id,prod_id,qty_on_hand FROM customer,product WHERE cust_id = cust_id_param AND prod_id = prod_id_param AND qty_on_hand >= qty_ordered_param)
THEN INSERT INTO `orders` (`cust_id`, `prod_id`, `order_date`, `qty_ordered`) VALUES (cust_id_param, prod_id_param, current_date(), qty_ordered_param);
UPDATE `product` SET product.qty_on_hand = qty_on_hand - qty_ordered_param WHERE prod_id = prod_id_param ;
ELSE SELECT 'invalid details' ;
END IF ;
END $$
CALL order_request(1,1,2)$$ -- valid
CALL order_request(3,2,14)$$ -- valid
CALL order_request(5,4,4)$$ -- valid
CALL order_request(10,10,2)$$ -- invalid
select * from orders$$
select * from product$$
-- creating the funtion
CREATE FUNCTION order_details (cust_id_param INT, prod_id_param INT ) RETURNS INT
BEGIN
DECLARE ans int;
SELECT SUM(qty_ordered) INTO ans FROM orders WHERE cust_id = cust_id_param AND prod_id = prod_id_param;
RETURN ans;
END$$
-- calling the funtion
SELECT order_details(5,4)$$

how to write multiple Insert queries in single procedure?

how to write multiple Insert queries in single procedure?
CREATE DEFINER=`root`#`localhost` PROCEDURE `Proc_Insert`(IN `newt` VARCHAR(500), IN `news` TEXT, IN `status` VARCHAR(500), IN `ntype` VARCHAR(500), IN `img_file` VARCHAR(1500), IN `vlink` VARCHAR(500))
INSERT INTO tbl_news(newt, news, status, ntype) VALUES (newt,news,status,ntype);
SET LID = LAST_INSERT_ID();
INSERT INTO tbl_img(pic, cid, imgfile, imgtype, imgstatus) VALUES (LID,LID,img_file,ntype,status);
INSERT INTO tbl_video(cid, vlink, vdis, vstatus) VALUES (LID,v_link,news,status);
This is the first time i am using this stored procedure.
You must enclose the statements with begin and end, and add all statements that you want:
DELIMITER $$
CREATE PROCEDURE `Proc_Insert`(IN `newt` VARCHAR(500), IN `news` TEXT, IN `status` VARCHAR(500), IN `ntype` VARCHAR(500), IN `img_file` VARCHAR(1500), IN `vlink` VARCHAR(500))
BEGIN
DECLARE LID INT;
INSERT INTO tbl_news(newt, news, status, ntype) VALUES (newt,news,status,ntype);
SET LID = LAST_INSERT_ID();
INSERT INTO tbl_img(pic, cid, imgfile, imgtype, imgstatus) VALUES (LID,LID,img_file,ntype,status);
INSERT INTO tbl_video(cid, vlink, vdis, vstatus) VALUES (LID,v_link,news,status);
END$$
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `paymentStoreProcedure`(IN `inEmail` VARCHAR(100))
BEGIN
DECLARE x, y, lastID INT DEFAULT 0;
INSERT INTO `payments`(`user_name`, `email`, `billing_address`, `ch_contact`, `city`, `ch_payment_method`, `ch_card_title`, `ch_card_number`, `ch_card_expiration`, `ch_card_cvv`, `created_at`) VALUES ('Nabeel',inEmail,'nazimabad','03211234127','Karachi','bank','Nabeel Ahmed','4242424242424242','02 / 24','123', now());
SELECT MAX(id) INTO lastID FROM `payments`;
SELECT id INTO x FROM `users` WHERE email = inEmail;
INSERT INTO `payment_products`(`payment_id`, `cart_id`, `product_name`, `price`, `quantity`, `product_id`, `created_at`) SELECT lastID, x, `product_name`, `price`, `quantity`, `product_id`, now() FROM `cart_infos` WHERE cart_id = x AND is_sold = 0;
UPDATE `cart_infos` SET is_sold =1 WHERE cart_id=x;
SELECT "Payment received";
END$$
DELIMITER ;
Note: I have used this code in my website so I copied it so you can figure it out and it's executable.

Mysql stored procedure insert into multiple tables

Am trying to insert data into 2 tables but only 1 table gets the data but the other one doesn't. I don't get any error messages but only the login table gets populated but the user doesn't.
Here is my code
CREATE DEFINER=`root`#`localhost` PROCEDURE `new_user`(
_email varchar(50),
_password varchar(255),
_name varchar(35),
_surname varchar(35)
)
BEGIN
start transaction;
insert into logins_copy (
email,
password,
created_at,
updated_at
)
values
(
_email,
_password,
current_timestamp(),
current_timestamp()
);
SELECT #user_id := id from logins_copy where email = _email;
insert into users (
user_id,
name,
surname,
updated_at
)
values
(
#user_id,
_name,
_surname,
current_timestamp()
);
commit;
END
and to test this I called the procedure:
call `new_user`("test#hotmail.com", "test123", "Adam", "James");

mysql Insert Statements in Stored Procedure not Inserting

I created a stored procedure which should perform the following:
Insert into Agencies Table, creating an id in the PK index row
Save the id in a variable
Insert the id and other data into Users table
The syntax below does not trigger any errors:
DELIMITER $$
CREATE PROCEDURE insertNewAgencyAndAdmin (IN aName varchar (100), IN numTrav int, IN polType int, IN uEmail varchar(255), IN uFName varchar(40), IN uLName varchar(40), IN uTitle varchar(100))
BEGIN
INSERT INTO btsAgency.Agencies (agencyName, numTrav, polType) VALUES (#aName, #numTrav, #polType);
SET #agencyID = (SELECT agencyID from btsAgency.Agencies where agencyID = LAST_INSERT_ID());
INSERT INTO btsUsers.Users (userAgencyID, userEmail, userFirstName, userLastName, userTitle ) VALUES
(#agencyID, #uEmail, #uFName, #uLName, #uTitle);
END
However, the Stored Proc doesn't insert my parameters into the tables when executed. So, after searching I try to create the SP like this (including $$ after "END" and resetting the delimiter to a semi-colon ):
DELIMITER $$
CREATE PROCEDURE insertNewAgencyAndAdmin (IN aName varchar (100), IN numTrav int, IN polType int, IN uEmail varchar(255), IN uFName varchar(40), IN uLName varchar(40), IN uTitle varchar(100))
BEGIN
INSERT INTO btsAgency.Agencies (agencyName, numTrav, polType) VALUES (#aName, #numTrav, #polType);
SET #agencyID = (SELECT agencyID from btsAgency.Agencies where agencyID = LAST_INSERT_ID());
INSERT INTO btsUsers.Users (userAgencyID, userEmail, userFirstName, userLastName, userTitle ) VALUES
(#agencyID, #uEmail, #uFName, #uLName, #uTitle);
END $$
DELIMITER ;
MySql creates the Stored Proc but gives me the following 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 'DELIMITER' at line 1
When I execute the created Stored Proc it still doesn't insert the data in my parameters.
Any help would be appreciated.
Some problems in your stored procedure:
It is important to indicate the difference between 9.4. User-Defined Variables and routine parameters 13.1.15. CREATE PROCEDURE and CREATE FUNCTION Syntax, are different variables (eg.: aName != #aName).
Avoid naming parameters or variables as columns of your tables.
DELIMITER $$
CREATE PROCEDURE `insertNewAgencyAndAdmin` (
/*
IN `aName` varchar (100),
IN `numTrav` int,
IN `polType` int,
IN `uEmail` varchar(255),
IN `uFName` varchar(40),
IN `uLName` varchar(40),
IN `uTitle` varchar(100)
*/
IN `_aName` varchar (100),
IN `_numTrav` int,
IN `_polType` int,
IN `_uEmail` varchar(255),
IN `_uFName` varchar(40),
IN `_uLName` varchar(40),
IN `_uTitle` varchar(100)
)
BEGIN
/*
INSERT INTO `btsAgency`.`Agencies` (
`agencyName`,
`numTrav`,
`polType`
) VALUES (
#`aName`,
#`numTrav`,
#`polType`
);
*/
INSERT INTO `btsAgency`.`Agencies` (
`agencyName`,
`numTrav`,
`polType`
) VALUES (
`_aName`,
`_numTrav`,
`_polType`
);
/*
SET #`agencyID` = (SELECT `agencyID` from `btsAgency`.`Agencies` where `agencyID` = LAST_INSERT_ID());
INSERT INTO `btsUsers`.`Users` (
`userAgencyID`,
`userEmail`,
`userFirstName`,
`userLastName`,
`userTitle`
) VALUES (
#`agencyID`,
#`uEmail`,
#`uFName`,
#`uLName`,
#`uTitle`
);
*/
INSERT INTO `btsUsers`.`Users` (
`userAgencyID`,
`userEmail`,
`userFirstName`,
`userLastName`,
`userTitle`
) VALUES (
LAST_INSERT_ID(),
`_uEmail`,
`_uFName`,
`_uLName`,
`_uTitle`);
END$$
DELIMITER ;
SELECT * FROM discounts $$
delimiter $$;
CREATE PROCEDURE insertData(IN id int,IN title varchar(255),IN amount decimal)
BEGIN
insert into discounts values (id,title,amount);
END; $$
call insertData(3,"sadasd",56);
/*DROP PROCEDURE insertData */

Merge statement error in SQL Server 2008 (Incorrect syntax near)

I'm trying to use "MERGE" in two temporary tables, I failed to get results.
Error: Incorrect syntax near the keyword 'AS'.
Create Table #tmp1
(
[Server] varchar(4),
[DateTime] datetime,
IdComponent int,
AvgTimeTaken int
)
Create Table #tmp2
(
[Server] varchar(4),
[DateTime] datetime,
IdComponent int,
AvgTimeTaken int
)
insert into #tmp1 values ('BE01','2012-08-01 00:00:00',1,100)
insert into #tmp1 values ('BE02','2012-08-01 00:00:00',2,100)
insert into #tmp1 values ('BE03','2012-08-01 00:00:00',3,100)
insert into #tmp1 values ('BE04','2012-08-01 00:00:00',4,100)
insert into #tmp1 values ('BE05','2012-08-01 00:00:00',5,100)
insert into #tmp2 values ('BE01','2012-08-01 00:00:00',1,100)
insert into #tmp2 values ('BE02','2012-08-01 00:00:00',2,200)
insert into #tmp2 values ('BE03','2012-08-01 00:00:00',3,300)
insert into #tmp2 values ('BE04','2012-08-01 01:00:00',4,400)
insert into #tmp2 values ('BE05','2012-08-01 02:00:00',5,500)
MERGE #tmp1 AS [Target]
USING #tmp2 AS [Source]
ON ([Target].[Server] = [Source].[Server]
AND [Target].[DateTime] = [Source].[DateTime]
AND [Target].[IdComponent] = [Source].[IdComponent])
WHEN MATCHED THEN
UPDATE
SET [Target].AvgTimeTaken = [Source].AvgTimeTaken
WHEN NOT MATCHED THEN
INSERT ([Target].[Server], [Target].[DateTime], [Target].IdComponent, [Target].AvgTimeTaken)
VALUES ([Source].[Server], [Source].[DateTime], [Source].IdComponent, [Source].AvgTimeTaken);
I'm not sure I can be wrong. At the end also has a semicolon.
Help please!
I've run into this error before and it was because SQL Server 2008 R2 does not support the merge syntax unless you set the compatibility mode by executing the following:
ALTER DATABASE mydatabase SET COMPATIBILITY_LEVEL = 100
Where mydatabase is the name of the database you want to apply this to.
Take out the Target aliases in the INSERT clause.
Create Table #tmp1 (
[Server] varchar(4),
[DateTime] datetime,
IdComponent int,
AvgTimeTaken int
);
Create Table #tmp2 (
[Server] varchar(4),
[DateTime] datetime,
IdComponent int,
AvgTimeTaken int
);
insert into #tmp1 values ('BE01','2012-08-01 00:00:00',1,100);
insert into #tmp1 values ('BE02','2012-08-01 00:00:00',2,100);
insert into #tmp1 values ('BE03','2012-08-01 00:00:00',3,100);
insert into #tmp1 values ('BE04','2012-08-01 00:00:00',4,100);
insert into #tmp1 values ('BE05','2012-08-01 00:00:00',5,100);
insert into #tmp2 values ('BE01','2012-08-01 00:00:00',1,100);
insert into #tmp2 values ('BE02','2012-08-01 00:00:00',2,200);
insert into #tmp2 values ('BE03','2012-08-01 00:00:00',3,300);
insert into #tmp2 values ('BE04','2012-08-01 01:00:00',4,400);
insert into #tmp2 values ('BE05','2012-08-01 02:00:00',5,500);
MERGE #tmp1 AS Target
USING #tmp2 AS Source
ON (Target.Server = Source.Server
AND Target.DateTime = Source.DateTime
AND Target.IdComponent = Source.IdComponent)
WHEN MATCHED THEN
UPDATE
SET Target.AvgTimeTaken = Source.AvgTimeTaken
WHEN NOT MATCHED THEN
INSERT (Server, DateTime, IdComponent, AvgTimeTaken)
VALUES (Source.Server, Source.DateTime, Source.IdComponent, Source.AvgTimeTaken);
The insert column list used in the MERGE statement cannot contain multi-part identifiers. Use single part identifiers instead.