select inside insert statmen and procedure - mysql

can i want to create store procedure that get arguments and run an select statment inside the insert statment?
i got 2 question:
1)how to get arguments on store procedure?
2)can i run select statment in insert statment like this?
DELIMITER $$
CREATE PROCEDURE `insertGuide` #m_name varchar(45) ,#m_last varchar(45) ,#addres varchar(45) ,#mphone int
BEGIN
INSERT INTO `guides` (`id`, `name`, `lastName`, `address`, `phone`)
VALUES (select max(id)+1 from seq,#m_name,#m_last,#addres,#mphone);
END

I don't understand the first question, but regarding the INSERT statement, this should work
INSERT INTO `guides` (`id`, `name`, `lastName`, `address`, `phone`)
select max(id)+1, #m_name, #m_last, #addres, #mphone
from seq;

try like this:
DELIMITER $$
DROP PROCEDURE IF EXISTS insertGuide;
CREATE PROCEDURE insertGuide (id int, name varchar(45) ,last varchar(45) ,addres varchar(45) ,phone int(12))
BEGIN
INSERT INTO `guides` (`id`, `name`, `lastName`, `address`, `phone`)
VALUES (id, name, last, addres, phone);
END
you can run select query in insert like:
INSERT INTO `guides` (`id`, `name`, `lastName`, `address`, `phone`)
SELECT MAX(id)+1, #m_name, #m_last, #addres, #mphone
FROM seq;

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 can I write this complex query SQL?

If I know how to filter by all signs of the zodiac, then by the sign of the zodiac 'Capricorn' (from December 22 to January 20) I do not know how to select.
Here is the structure of the tables, do I need to select all users with the sign of the zodiac 'Capricorn'?
The structure of the tables can be changed (or even add new tables if required):
CREATE TABLE IF NOT EXISTS `horoscope` (
`id` INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(255) NOT NULL UNIQUE,
`date_start` VARCHAR(5),
`date_end` VARCHAR(5)
);
CREATE INDEX `horoscope_idx_1` ON `horoscope`(`date_start`, `date_end`);
CREATE TABLE IF NOT EXISTS `user` (
`id` INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(255) NOT NULL,
`birthday` DATE NOT NULL
);
Insert test data
# Insert horoscope in table
INSERT INTO `horoscope` (`name`, `date_start`, `date_end`) VALUES ('Aries', '03-21', '04-20');
INSERT INTO `horoscope` (`name`, `date_start`, `date_end`) VALUES ('Taurus', '04-21', '05-20');
INSERT INTO `horoscope` (`name`, `date_start`, `date_end`) VALUES ('Gemini', '05-22', '06-21');
INSERT INTO `horoscope` (`name`, `date_start`, `date_end`) VALUES ('Cancer', '06-22', '07-22');
INSERT INTO `horoscope` (`name`, `date_start`, `date_end`) VALUES ('Leo', '07-23', '08-23');
INSERT INTO `horoscope` (`name`, `date_start`, `date_end`) VALUES ('Virgin', '08-24', '09-22');
INSERT INTO `horoscope` (`name`, `date_start`, `date_end`) VALUES ('Libra', '08-23', '10-22');
INSERT INTO `horoscope` (`name`, `date_start`, `date_end`) VALUES ('Scorpio', '10-23', '11-21');
INSERT INTO `horoscope` (`name`, `date_start`, `date_end`) VALUES ('Sagittarius', '11-22', '12-21');
INSERT INTO `horoscope` (`name`, `date_start`, `date_end`) VALUES ('Capricorn', '12-22', '01-20');
INSERT INTO `horoscope` (`name`, `date_start`, `date_end`) VALUES ('Aquarius', '01-21', '02-19');
INSERT INTO `horoscope` (`name`, `date_start`, `date_end`) VALUES ('Pisces', '02-20', '03-20');
# Insert random user in table
DROP PROCEDURE IF EXISTS `add_user`;
CREATE PROCEDURE `add_user`(IN `count_user` INT)
LANGUAGE SQL
DETERMINISTIC
SQL SECURITY DEFINER
COMMENT 'A procedure for inserting random user'
BEGIN
DECLARE i INT DEFAULT (
SELECT `id`
FROM `user`
ORDER BY `id` DESC
LIMIT 1
);
IF i IS NULL
THEN SET i = 1;
END IF;
SET `count_user` = `count_user` + i;
WHILE i <= `count_user` DO
SET #`name` = CONCAT('user_', i);
SET #`user_birth` = '1980-01-01' + INTERVAL (RAND() * 365 * 20) DAY;
INSERT INTO `user` (`name`, `birthday`) VALUES (#`name`, #`user_birth`);
SET i = i + 1;
END WHILE;
END;
CALL `add_user`(1000);
DROP PROCEDURE IF EXISTS `add_user`;
I decided =)
SELECT *
FROM user as u
WHERE (
DATE_FORMAT(u.birthday, '%m%d') >= (
SELECT
CONCAT(LEFT(`h`.`date_start`, 2), RIGHT(`h`.`date_start`, 2))
FROM horoscope h
WHERE h.name = 'Capricorn'
) AND DATE_FORMAT(u.birthday, '%m%d') <= 1231
) OR (
DATE_FORMAT(u.birthday, '%m%d') >= 101 AND DATE_FORMAT(u.birthday, '%m%d') <= (
SELECT
CONCAT(LEFT(`h`.`date_end`, 2), RIGHT(`h`.`date_end`, 2))
FROM horoscope h
WHERE h.name = 'Capricorn'
)
);
If the boundaries of each zodiac sign are fixed dates, then it would make sense to add birth-sign as an attribute to each user instead of filtering by dates each and every time you need that information.
However I would suggest the following if you do need to filter:
select *
from user u
inner join horoscope h
where (h.date_start > h.date_end
and u.birthday between str_to_date(concat(year(u.birthday)-1, h.date_start),'%Y%m-%d')
and str_to_date(concat(year(u.birthday), h.date_end),'%Y%m-%d')
)
or (h.date_start < h.date_end
and u.birthday between str_to_date(concat(year(u.birthday), h.date_start),'%Y%m-%d')
and str_to_date(concat(year(u.birthday), h.date_end),'%Y%m-%d')
)
Note however that the indexing of the 2 varchar(5) columns in horoscope probably isn't going to be helpful to your queries.
see: https://rextester.com/OAOTEH65480

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 SHA256 with Insert Statement

I want to create a script to fill a database for testing. How would I set a string to be hashed and the inserted into the database?
I have:
INSERT INTO `loop`.`User`
(`userID`,
`firstName`,
`lastName`,
`email`,
`password`,
`userName`,
`bio`,
`spamCount`)
VALUES
('gZvTtlPtjGRqeMBaLji3HxoKB5EZCsNL',
'Joe',
'Smith',
'test0#email.com',
SHA2('testgZvTtlPtjGRqeMBaLji3HxoKB5EZCsNL', 256),
'test0#email.com',
"TEST BIO",
0);
How do I hash the string and INSERT in same statement?
You can insert a SELECT instead of VALUES to run a function on one of the inputs:
INSERT INTO `loop`.`User`
(`userID`,
`firstName`,
`lastName`,
`email`,
`password`,
`userName`,
`bio`,
`spamCount`)
SELECT
'gZvTtlPtjGRqeMBaLji3HxoKB5EZCsNL',
'Joe',
'Smith',
'test0#email.com',
SHA2('testgZvTtlPtjGRqeMBaLji3HxoKB5EZCsNL', 256),
'test0#email.com',
"TEST BIO",
0;
If you already have the table filled by some content, you can alter it with the following :
ALTER TABLE `page` ADD COLUMN `hash` char(64) AS (SHA2(`content`, 256)) AFTER `content`
This solution will add hash column right after the content one, generates hash for existing and new records too without need to change your INSERT statement.

Trigger MySQL not working

CREATE DEFINER=`root`#`%` TRIGGER `trg_add_role_type_to_auth_item` AFTER INSERT ON role_type
FOR EACH ROW
BEGIN
INSERT INTO `auth_item` (`name`, `type`, `description`, `bizrule`, `data`)
SELECT role_type.name, "2", role_type.name, "NULL", "NULL" FROM role_type WHERE role_type.role_type_id =
(SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='role_type');
END;
what is wrong in this trigger query....
my row got inserted in role_type but do not create in sert in auth_item table.. is it proper way .... I want to insert value from the last row to the auth_item table on insert in role_type table
In trigger you can directly access the fields of main table using new or old objects.
Try this:
CREATE DEFINER=`root`#`%` TRIGGER `trg_add_role_type_to_auth_item` AFTER INSERT ON role_type
FOR EACH ROW
BEGIN
INSERT INTO `auth_item` (`name`, `type`, `description`, `bizrule`, `data`)
VALUES (new.name, "2", new.name, NULL, NULL);
END;