I want to create a stored procedure in which first select statement and depending on the selected parameter if valid, insert record in the another table else do nothing. How to write the stored procedure for this?
I have tried with stored procedure and it is executed with no errors, but when I tried to EXEC stored procedure, it doesn't do the task as written in procedure.
CREATE PROCEDURE sp_CreateExpiryDocumentFollowup
(@param INT = NULL,
@param2 INT = NULL,
@param3 INT = 1,
@param4 BIT = 0,
@followupid INT = NULL)
AS
BEGIN
SELECT
@param1 = [TABLE_A].[VEHICLE_ID],
@param2 = [TABLE_A].[VEHICLE_DOCUMENT_ID],
@followupid = [TABLE_B].[FOLLOWUP_ID]
FROM
[TABLE_A]
LEFT JOIN
[TABLE_B] ON [TABLE_B].[VEHICLE_DOCUMENT_ID] != [TABLE_A].[VEHICLE_DOCUMENT_ID]
WHERE
[TABLE_A].[STATUS] = 1;
IF @followupid = NULL
BEGIN
INSERT INTO [TABLE_B] (VALUE_1, VALUE_2, VALUE_3, VALUE_4)
VALUES (@param1, @param2, @param3, @param4)
END
END
GO
I expect the record to insert in the TABLE_B if @followupid is null. The @followupid is null as I executed the select statement only. But while executing whole stored procedure it will return the result 0 row which in my case should be 1. And I checked the table as well, no any record is inserted but stored procedure runs successfully.
@followupid = nullis wrong it should be@followupid IS NULL. Also that won't work as expected if you have more than 1 row with[TABLE_A].[STATUS] = 1@followupid = nullis working as you expect, this means you haveANSI_NULLSset to off. This is deprecated and will stop working in a future version of SQL Server. YOu should stop usingSET ANSI_NULLS OFFas soon as you can and change to properNULLlogic.