I have a stored procedure used for updating records in a SQL Server database.
I want to use the existing value within the database if a match is found and a null is provided as the variable.
Often only partial data is available so the procedure is executed at several stages to complete the record. I do not always have all variables at each execution.
Why is the below CASE not working? If a null value is provided, it replaces existing data within the field.
ALTER PROCEDURE [dbo].[sp_UPSERT_Test]
@ID int,
@Account_ID varchar(15)
@Name varchar(15)
AS
BEGIN
MERGE INTO dbo.Database_Log AS target
USING (
SELECT @ID, @Account_ID ,@Account_ID)
AS source (ID, Account_ID, Name)
ON target.ID = source.ID
WHEN MATCHED
THEN UPDATE
SET
Account_ID = CASE
WHEN source.Account_ID = NULL
THEN target.Account_ID
ELSE source.Account_ID
END
,Name = CASE
WHEN source.Name = NULL
THEN target.Name
ELSE source.Name
END)
WHEN NOT MATCHED
THEN INSERT (Account_ID, Name)
VALUES (Account_ID, Name);
RETURN
END
Maybe because you're not properly checking for NULL
? NULL
is not a value you can compare with the equality operator - you must use IS NULL
Try this:
SET
Account_ID = CASE
WHEN source.Account_ID IS NULL
THEN target.Account_ID
ELSE source.Account_ID
END
Use IS NULL
instead of = NULL