MySQL Stored Procedure works as plain SQL - mysql

I'm trying to write a stored procedure that inserts into one table (A), then queries another table (B), then finally inserts into table (C) the last insert id, along with the result from table B. I have written a stored procedure named VetIdFromCode to do the selecting from table B, which works fine in isolation. When I run the query in isolation, subbing in value for the IN parameters then it runs fine, but when I try and save it as a stored procedure it tells me invalid SQL near 'SET #LIID...'
Many thanks for any help.
CREATE PROCEDURE `NewClientUser`(
IN `uemail` VARCHAR(60),
IN `uphash` CHAR(40),
IN `uvcode` VARCHAR(11))
DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY INVOKER
INSERT INTO users (user_id,user_email,user_hash,user_role)
VALUES (NULL,uemail,uphash,'1');
SET #LIID = LAST_INSERT_ID();
CALL `VetIdFromCode`(uvcode, #VID);
INSERT INTO user_vet_lookup(user_id,vet_id)
VALUES (#LIID,#VID);

You need to start the "code" of the procedure with the key word "BEGIN" and put an "END" at the end. Like:
CREATE PROCEDURE `NewClientUser`(
IN `uemail` VARCHAR(60),
IN `uphash` CHAR(40),
IN `uvcode` VARCHAR(11))
BEGIN
DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY INVOKER
INSERT INTO users (user_id,user_email,user_hash,user_role)
VALUES (NULL,uemail,uphash,'1');
SET #LIID = LAST_INSERT_ID();
CALL `VetIdFromCode`(uvcode, #VID);
INSERT INTO user_vet_lookup(user_id,vet_id)
VALUES (#LIID,#VID);
END
Check out the documentation: http://dev.mysql.com/doc/refman/5.7/en/create-procedure.html

Related

Azure Data Factory - Get SCOPE_IDENTITY value from MYSQL Stored Procedure

I'm using Lookup activity to invoke a MYSQL Stored Procedure. The requirement is to insert a record into a table, get the latest primary key and use that in another activity.
Below is the Stored Procedure
CREATE Procedure usp_LogAudit (
p_pipeline_id int,
p_status varchar(20)
)
begin
Insert into PipelineExecutionLog
(
pipeline_id,
execution_start,
execution_end,
status
)
values
(
p_pipeline_id ,
utc_timestamp(),
null,
p_status
);
SELECT LAST_INSERT_ID() AS SCOPE_IDENTITY;
end;
As, I'm using MYSQL, I don't have the facility to directly import the Stored Procedure along with it' parameters. (Note: For MS-SQL, it's straight forward)
As shown below, I'm using the Query option and invoking the MYSQL Stored Procedure using the 'call'.
Below is the Dynamic Expression
#concat('call usp_LogAudit(',variables('PipelineId'),',','''',variables('PipelineStatus'),'''',')')
The Lookup activity is calling the Stored Procedure successfully at database side. However, in ADF, it's throwing an error.
Not sure how to fix this. Any advice is appreciated.

Stored Procedure Data Not being Populated in Table

CREATE TABLE TempTable (
[Fiscal Quarter] varchar(50),
[Unique ID] int,
[Forecasted Amount (converted)] Numeric (25,2),
[Lead Source] varchar(50),
[AD] varchar(50),
[Stage] varchar(50),
[Opportunity Name] varchar(50))
INSERT INTO TempTable Exec [MOPs].[MSP_INQTRWon_Final_Proc_VG]
**
Question: When I insert data from stored procedure into a table; it shows 0 rows affected. However when I execute the stored procedure it says 455 rows affected.
**
However when I execute the stored procedure it says 455 rows affected.
When you execute the stored procedure it should return rows like select statement in order to insert those rows into a table. Instead if it's just doing some operation on those rows there is nothing to insert.
Please confirm whether your stored procedure returns rows when you execute.
In MySQL stored procedure is executed via call procedurename();
https://dev.mysql.com/doc/refman/8.0/en/call.html
SQLServer use exec. Is your database MySQL? Then which version?

Store procedure and foreign key checks

I am trying to create a store procedure to insert data into my joining table which contains two foreign keys (one for members and one for centres)
With straight SQL (via phpmyadmin) i can change values in the table, however with a store procedure I just get error: 1452.
How can I write to the table without causing the error and without disabling the foreign key constraints completely. I understand there's nothing to prevent people from entering the wrong values, the idea is that the user interface will prevent that ultimately. However, if there's a better way within the database I’d love to hear it.
The sql that works is:
INSERT INTO `tblmembers_has_tblcentres` (`tblMembers_MemberID`,
`tblCentres_CentreID`, `DateMemberJoinedCentre`) VALUES ('92', '2',
CURRENT_TIMESTAMP);
And my store procedure looks like this:
CREATE DEFINER=`root`#`localhost` PROCEDURE `Add_Memb_to_Centre`(IN `iMember`
INT, IN `iCentre` INT)
SQL SECURITY INVOKER
INSERT INTO `tblmembers_has_tblcentres` (`tblMembers_MemberID`,
`tblCentres_CentreID`, `DateMemberJoinedCentre`) VALUES ('iMember', 'iCentre',
CURRENT_TIMESTAMP)
You are trying to insert the string values "iMember" and "iCentre" rather than their variable contents. Keep using the backticks:
CREATE DEFINER=`root`#`localhost` PROCEDURE `Add_Memb_to_Centre`(IN `iMember`
INT, IN `iCentre` INT)
SQL SECURITY INVOKER
INSERT INTO
`tblmembers_has_tblcentres`
(
`tblMembers_MemberID`,
`tblCentres_CentreID`,
`DateMemberJoinedCentre`
)
VALUES ('iMember', 'iCentre', CURRENT_TIMESTAMP) -- WRONG
VALUES (`iMember`, `iCentre`, CURRENT_TIMESTAMP) -- CORRECT

MySQL Stored Procedure and Identifiers

I am learning to write MySQL stored procedures and I have encountered some difficulties. Here I have two stored procedures:
First stored procedure:
CREATE PROCEDURE sp1 (IN `username` TEXT, OUT `user_id` INT)
BEGIN
DECLARE rowcount INT;
SELECT count(`User ID`) INTO rowcount FROM user WHERE `Username`=username;
SET user_id = rowcount;
END|
Second stored procedure:
CREATE PROCEDURE sp2 (IN `doc_id` INT, IN `content` LONGTEXT)
BEGIN
UPDATE doc SET `Content`=content WHERE `Doc ID`=doc_id;
END|
(Delimiter is |.)
Question:
I observe that the result of the first stored procedure is the same as calling SELECT count(`User ID`) FROM user;. However, the second stored procedure does its job and gets the content updated with the new content.
So why does the first stored procedure treat `Username` and username as equal identifiers but the second stored procedure treats `Content` and content as different identifiers? The two identifiers in both cases are the same except the capitalization of the first letter.
I figure it out after reading the official MySQL documentation about the scope of local variables.
It states that:
A local variable should not have the same name as a table column. If an SQL statement, such as a SELECT ... INTO statement, contains a reference to a column and a declared local variable with the same name, MySQL currently interprets the reference as the name of a variable.

Attempting to insert into a table then update a field within the same stored procedure

I'm attempting to create a procedure that is a basic insert into a table, and then performs a quick update on another table afterwards in MySQL. Please find the code below:
DROP PROCEDURE IF EXISTS `sp_insertUserSocial`
GO
CREATE PROCEDURE sp_insertUserSocial
(
IN p_userSocialID INT(11),
IN p_socialID INT(11),
IN p_userID INT(11),
IN p_referralID INT(11)
)
BEGIN
INSERT INTO UserSocial
(
userSocialID,
socialID,
userID,
referralID
)
VALUES
(
IN p_userSocialID,
IN p_socialID,
IN p_userID,
IN p_referralID
) ;
UPDATE Users
SET connCount = connCount + 1
WHERE UserID = p_referralID;
END
GO
In PHPAdmin it's giving me a syntax error, but I'm not sure where exactly it is? It says line 23, which makes me think it's the semi-colon but I thought that these were needed after an insert statement?
Any help is appreciated, thanks!
I see a couple of problems:
GO, must specify the DELIMITER. 19.1. Defining Stored Programs.
In the INSERT (13.2.5. INSERT Syntax), the IN is optional to pass parameters to the stored procedure (13.1.15. CREATE PROCEDURE and CREATE FUNCTION Syntax), but not part of the syntax of the INSERT.
SQL Fiddle demo