How to create MySQL script using MySQL workbench? - mysql

I followed this tutorial but it seems like the queries he used in the video cannot be used in MySQL.
CREATE PROCEDURE spInsertIntoStudentCourses
#StudentName varchar(50),
#CourseName varchar(50)
AS
BEGIN
DECLARE #StudentId int;
DECLARE #CourseId int;
SELECT #StudentId = id from Students where StudentName = #StudentName;
if(#StudentId is null);
Begin;
INSERT INTO Student VALUES (#StudentName);
SELECT #StudentId = SCOPE_IDENTITY();
END;
SELECT #CourseId = id from Courses where CourseName = #CourseName;
if(#CourseName is null)
BEGIN;
INSERT INTO Courses VALUES (#CourseName);
SELECT #CourseId = SCOPE_IDENTITY();
END;
INSERT INTO StudentCourses VALUES (#StudentID, #CourseID);
END
What should be the right syntax for this?

After a year of studying some basics in creating a stored procedure in MySQL, I created my own MySQL version of the above question in like this.
CREATE PROCEDURE `InsertStudentCourse`(
_studentName VARCHAR(50),
_courseName VARCHAR(50)
)
BEGIN
DECLARE _studentId INT;
DECLARE _courseId INT;
SELECT _studentId = studentId FROM students WHERE studentName = _studentName;
IF (_studentId IS NULL) THEN
BEGIN
INSERT INTO students VALUES (NULL, _studentName);
SELECT _studentId = LAST_INSERT_ID();
END;
END IF;
SELECT _courseId = courseId FROM courses WHERE CourseName = _courseName;
IF (_courseId IS NULL) THEN
BEGIN
INSERT INTO courses VALUES (NULL, _courseName);
SELECT _courseId = LAST_INSERT_ID();
END;
END IF;
INSERT INTO student_courses VALUES (NULL, _studentName, _courseName);
END

Related

I am trying to write stored procedure to insets values and if record exist then select that row but it is giving me invalid use of group statement

I am trying to write stored procedure to insets values and if record exist then select that row but it is giving me invalid use of group statement
I have written below: -
TRY 1:- error :- invalid use of group statement
CREATE DEFINER=`root`#`localhost` PROCEDURE `insusers`(IN enterprise_id varchar(40),IN enterprise_name varchar(40),IN email_id varchar(40))
BEGIN
SELECT COUNT(*) FROM user WHERE email_id = email_id;
IF COUNT(*) < 1 THEN
INSERT INTO user(enterprise_id,user_name,email_id)
VALUES (enterprise_id,enterprise_name,email_id);
SELECT * FROM user WHERE user_id = last_insert_id();
ELSE
SELECT * FROM user WHERE email_id = email_id;
END IF;
END
TRY 2 :- error :- Not able to insert new values
CREATE DEFINER=`root`#`localhost` PROCEDURE `insusers`(IN enterprise_id varchar(40),IN enterprise_name varchar(40),IN email_id varchar(40))
BEGIN
DECLARE count INT DEFAULT 0;
SELECT COUNT(*) INTO count FROM user WHERE email_id = email_id;
IF count < 1 THEN
INSERT INTO user(enterprise_id,user_name,email_id)
VALUES (enterprise_id,enterprise_name,email_id);
SELECT * FROM user WHERE user_id = last_insert_id();
ELSE
SELECT * FROM user WHERE email_id = email_id;
END IF;
END
Please help me with solution.
Thanks in advance.
It is recommended to use BEGIN and END to separate IF clauses, also use # to distinguish between variables and columns. Hope this helps:
CREATE DEFINER=`root`#`localhost` PROCEDURE `insusers`(IN #enterprise_id varchar(40),IN #enterprise_name varchar(40),IN #email_id varchar(40))
BEGIN
IF ((SELECT COUNT(*) FROM user WHERE email_id = #email_id)<1) BEGIN
INSERT INTO user(enterprise_id,user_name,email_id)
VALUES (#enterprise_id,#enterprise_name,#email_id);
SELECT * FROM user WHERE user_id = last_insert_id();
END ELSE BEGIN
SELECT * FROM user WHERE email_id = #email_id;
END
END

Store procedure select returns null after insert

I have 3 tables called tipo_produto & tipo_veiculo and tipo_produto_veiculo
Basicaly, a procedure called addTipo_produto that inserts values into tipo_produto and then selects tipo_produto to get the last ID where the values match but it returns null and it's impossible because I just added the value before
DELIMITER //
Create procedure addTipo_produto(
IN p_tipo_produto varchar(50),
IN p_tipo_veiculo varchar(50)
)
begin
DECLARE id_tipo_veiculo INT;
DECLARE id_tipo_produto INT;
INSERT INTO `tipo_produto`(`tipo_produto`) VALUES(p_tipo_produto);
SELECT `id_tipo_veiculo` INTO id_tipo_veiculo FROM `tipo_veiculo` WHERE `tipo_veiculo` LIKE p_tipo_veiculo;
SELECT `id_tipo_produto` INTO id_tipo_produto FROM `tipo_produto` WHERE `tipo_produto` LIKE p_tipo_produto;
INSERT INTO `tipo_produto_veiculo`(`id_tipo_produto`, `id_tipo_veiculo`) VALUES((SELECT(id_tipo_produto)), (SELECT(id_tipo_veiculo)));
end//
DELIMITER ;
Entire code:
https://pastebin.com/0qWgtusK
Fixed code:
DELIMITER //
Create procedure addTipo_produto(
IN p_tipo_produto varchar(50),
IN p_tipo_veiculo varchar(50)
)
begin
DECLARE _id_tipo_veiculo INT;
DECLARE _id_tipo_produto INT;
INSERT INTO `tipo_produto`(`tipo_produto`) VALUES(p_tipo_produto);
SET _id_tipo_veiculo = (SELECT `id_tipo_veiculo` FROM `tipo_veiculo` WHERE `tipo_veiculo` LIKE p_tipo_veiculo);
SELECT `id_tipo_produto` INTO _id_tipo_produto FROM `tipo_produto` WHERE `tipo_produto` LIKE p_tipo_produto;
INSERT INTO `tipo_produto_veiculo`(`id_tipo_produto`, `id_tipo_veiculo`) VALUES(_id_tipo_produto, _id_tipo_veiculo);
end//
DELIMITER ;
Thanks everyone
I have altered one line because only insert statement was for tipo_produto table.
Hope rest can be done by you.
DELIMITER //
Create procedure addTipo_produto(
IN p_tipo_produto varchar(50),
IN p_tipo_veiculo varchar(50)
)
begin
DECLARE id_tipo_veiculo INT;
DECLARE id_tipo_produto INT;
INSERT INTO `tipo_produto`(`tipo_produto`) VALUES(p_tipo_produto);
SELECT LAST_INSERT_ID() INTO id_tipo_veiculo;
SELECT `id_tipo_produto` INTO id_tipo_produto FROM `tipo_produto` WHERE `tipo_produto` LIKE p_tipo_produto;
INSERT INTO `tipo_produto_veiculo`(`id_tipo_produto`, `id_tipo_veiculo`) VALUES(id_tipo_produto, id_tipo_veiculo);
end//
DELIMITER ;

Assign a list of items to a variable and iterate in cursor SQL

I have a predefined list of items which I want to use in select query.
DECLARE #cur_emp CURSOR;
DECLARE #TEST_ID int
DECLARE #TEST_NAME varchar(100)
DECLARE #names table(name varchar(100))
--SET #TEST_NAME = 'Order not timely approved'
insert into #names(name) values ('a')
insert into #names(name) values ('b')
--SET #TEST_NAME = CURSOR FOR (select name from #names)
WHILE EXISTS (select * from #names)
BEGIN
SET #cur_emp= CURSOR FOR (select TEST_ID from CS_TEST_V2 where test_name = #name)
Error says: #name is an invalid column name
Can somebody please help.
You have syntax errors in your cursor part. Please try this.
DECLARE #TEST_ID INT
DECLARE #TEST_NAME VARCHAR(100)
DECLARE #names TABLE (NAME VARCHAR(100))
--SET #TEST_NAME = 'Order not timely approved'
INSERT INTO #names (NAME)
VALUES ('a')
INSERT INTO #names (NAME)
VALUES ('b')
DECLARE cur_emp CURSOR
FOR
SELECT NAME
FROM #names;
OPEN cur_emp
FETCH NEXT FROM cur_emp
INTO #TEST_NAME
WHILE ##FETCH_STATUS = 0
BEGIN
SET #TEST_ID = (
SELECT TEST_ID
FROM CS_TEST_V2
WHERE test_name = #TEST_NAME
)
FETCH NEXT FROM cur_emp
INTO #TEST_NAME
END
CLOSE cur_emp
DEALLOCATE cur_emp

mySQL stored procedure to insert row into table always inserts 0 values for all columns

I'm attempting to do an insert store procedure on mySQL as a little test.
The end result inserts all zeros into a row rather than the values passed into the definer.
My Code:
CREATE PROCEDURE `Test` (
IN IDvar int,
IN FirstNamevar nvarchar(50),
IN LastNamevar nvarchar(50),
IN Nationalityvar nvarchar(50),
In Agevar nvarchar(50),
)
BEGIN
INSERT INTO testtable (
ID,
FirstName,
LastName,
Nationality,
Age)
VALUES(
IDvar,
FirstNamevar,
LastNamevar,
Nationalityvar,
Agevar);
END
I click apply and get the following code to construct the store procedure
USE `testdb`;
DROP procedure IF EXISTS `Test`;
DELIMITER $$
USE `testdb` $$
CREATE PROCEDURE `Test` (
IN IDvar int,
IN FirstNamevar nvarchar(50),
IN LastNamevar nvarchar(50),
IN Nationalityvar nvarchar(50),
In Agevar nvarchar(50),
)
BEGIN
INSERT INTO testtable (
ID,
FirstName,
LastName,
Nationality,
Age)
VALUES(
IDvar,
FirstNamevar,
LastNamevar,
Nationalityvar,
Agevar);
END$$
DELIMITER;
If I look at the constructed store procedure code I get the following
CREATE DEFINER=`root`#localhost` PROCEDURE `Test`(
IN IDvar int,
IN FirstNamevar nvarchar(50),
IN LastNamevar nvarchar(50),
IN Nationalityvar nvarchar(50),
In Agevar nvarchar(50),
)
BEGIN
INSERT INTO testtable (
ID,
FirstName,
LastName,
Nationality,
Age)
VALUES(
IDvar,
FirstNamevar,
LastNamevar,
Nationalityvar,
Agevar);
END
When I then execute this store procedure with values:
IDvar = 3
FirstNamevar = TestFirstName
LastNamevar = TestLastName
Nationalityvar = GER
Age = 20
I get this out
set #IDvar = 0;
set #FirstNamevar = '0';
set #LastNamevar = '0';
set #Nationalityvar = '0';
set #Agevar = '0';
call testdb.Test(#IDvar, #FirstNamevar, #LastNamevar, #Nationalityvar, #Agevar);
select #IDvar, #FirstNamevar, #LastNamevar, #Nationalityvar, #Agevar;
Obviously this end with a row with all zero values. Anyone know why this is happening?
Cheers
1) You are passing all zeros into the stored procedure. So that is what is then inserted into the table.
2) Your SELECT at the end does not read from the table you insert into in the stored procedure but rather just returns the values of the variables - all of which are 0.
So everything is working as your code is telling it to.

Stored Procedure issue

I am new to sql and most of my training is in MSSQL, however I am taking a class in MYSQL. I have a stored procedure that is giving me an issue. I have the delimiter set to //.
CREATE PROCEDURE AddComment
(
name varchar(50),
emailAddress varchar(50),
Comments text
)
BEGIN
DECLARE ComName varchar(50);
DECLARE ComID int;
SELECT name into ComName;
SELECT ID into ComID from Commenters WHERE names = ComName;
if ComID = NULL
BEGIN
INSERT INTO COMMENTERS ('names', 'emailAddresses') values (name, emailAddress);
SELECT ID into ComID from Commenters WHERE names = ComName;
END
INSERT INTO COMMENTS ('commentersID', 'Comments') values (ComID, Comments);
END;
//
EDIT
This is what I have now:
CREATE PROCEDURE AddComment
(
Username varchar(50),
UseremailAddress varchar(50),
UserComment text
)
BEGIN
DECLARE ComName varchar(50);
DECLARE ComID int;
SELECT Username into ComName;
SELECT ID into ComID from Commenters WHERE names = ComName;
if ComID = NULL
BEGIN
INSERT INTO COMMENTERS(names,emailAddresses) values (Username, UseremailAddress);
SELECT ID into ComID from Commenters WHERE names = ComName;
END
INSERT INTO COMMENTS(commentersID, Comments) values (ComID, UserComment);
END;
//
And the error I am getting is:
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 'BEGIN INSERT INT
O COMMENTERS(names, emailAddresses) values (Username, Useremail' at line 1
Any Ideas?
You are coding column names and values reversed in you insert statements.
It should be
INSERT INTO COMMENTERS (name, emailAddress) values ('names', 'emailAddresses') ;