Store procedure and foreign key checks - mysql

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

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.

MySQL Stored Procedure works as plain SQL

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

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

Mysql- Not allowing duplicate entries to be inserted

I have the following Stored procedure with me which allows to insert into the Database.I want to change the the stored procedure such that duplicate entries should not be entered.The columns that I want to use for checking the duplicate are Material_Name and Material_Data.how should i change the SP? Someone help me.
CREATE PROCEDURE `sp_upload_file`(IN Training_Id INT,IN filename VARCHAR(200), IN path VARCHAR(200),IN materialdata MEDIUMBLOB)
BEGIN
INSERT INTO `training_material`
(`Training_Id`,
`Material_Name`,
`Material_Path`,
`Material_Data`,
`Created_Date`,
`Modified_Date`)
VALUES
(Training_Id,
filename,
path,
materialdata,
NOW()
,NOW());
END$$
DELIMITER ;
alter the table by creating UNIQUE constraint,
ALTER TABLE training_material
ADD CONSTRAINT trainmat_UQ UNIQUE(Material_Name, Material_Data)

Referential Insert - Stored Procedure - SQL Server 2008

I working in .Net Application. Here in my aspx page, i am having 3 Tabs (i.e) Tab 1, Tab 2,Tab 3. The first Tab contains some Textbox controls, the Second tab contains some combo box controls and same as Third tab contains some controls. I want to save all these three tab controls to THREE different tables in SQL Database. Only one Stored Procedure should be used for this. The PRIMARY KEY of the FIRST table should be saved in the SECOND and THIRD table. ( LIKE, REFERENTIAL INSERT ). Here is my SP...
ALTER PROCEDURE [dbo].[Insert]
(#Name NVARCHAR(50))
AS
BEGIN
SET NOCOUNT ON
DECLARE #TableOnePrimaryKey INT
BEGIN
INSERT INTO TABLEONE(Name)
VALUES (#Name)
SELECT #TableOnePrimaryKey=##IDENTITY
SELECT CAST(##IDENTITY AS INT)
INSERT INTO TABLETWO(TableTwoIDColumn)
VALUES (#TableOnePrimaryKey)
SELECT #TableOnePrimaryKey=##IDENTITY
SELECT CAST(##IDENTITY AS INT)
INSERT INTO TABLETHREE(TableThreeIDColumn)
VALUES (#TableOnePrimaryKey)
SELECT #TableOnePrimaryKey=##IDENTITY
SELECT CAST(##IDENTITY AS INT)
INSERT INTO TABLEFOUR(TableFourIDColumn)
VALUES (#TableOnePrimaryKey)
END
But, its the TABLE ONE Primary key is not got saved in other tables. How to Fix this..
Use scope_identity() instead of ##identity. And you should not assign the value to #TableOnePrimaryKey more than once. If you have an identity column in the other tables you loose the identity you got from the first insert.
ALTER PROCEDURE [dbo].[Insert]
(#Name NVARCHAR(50))
AS
BEGIN
SET NOCOUNT ON
DECLARE #TableOnePrimaryKey INT
INSERT INTO TABLEONE(Name)
VALUES (#Name)
SET #TableOnePrimaryKey=SCOPE_IDENTITY()
INSERT INTO TABLETWO(TableTwoIDColumn)
VALUES (#TableOnePrimaryKey)
INSERT INTO TABLETHREE(TableThreeIDColumn)
VALUES (#TableOnePrimaryKey)
INSERT INTO TABLEFOUR(TableFourIDColumn)
VALUES (#TableOnePrimaryKey)
END
I'd be using scope_identity over identity.
From http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/
"To avoid the potential problems associated with adding a trigger
later on, always use SCOPE_IDENTITY() to return the identity of the
recently added row in your T SQL Statement or Stored Procedure."
Try that and see if it fixes your issue.
Edit: I meant to mention that I think you need to set the variable differently. Try the following;
SET #TableOnePrimaryKey = (SELECT SCOPE_IDENTITY())
SELECT CAST(#TableOnePrimaryKey AS INT)
etc etc