I created a stored procedure to update only the rows of a table that have changed
I used the SQLSERVER coalesce function.
CREATE PROCEDURE update_only_changed
@FName varchar(50) = NULL,
@LName varchar(50) = NULL,
@CUST_DB VARCHAR(20)
AS
BEGIN
DECLARE @QUERY VARCHAR(255)
SET @QUERY = 'UPDATE ' + @CUST_DB + '..people SET LastName = COALESCE(@LName, LastName) WHERE id = 1'
EXEC (@QUERY)
END
GO
Some considerations
-
Is a dynamic sql
-
The name of the database is passed as a parameter in the procedure
So, When I run the sql I have two situations:
-
EXEC(@ QUERY):I get the error saying: Must declare the scalar variable "@ LName". it does not interpret the variable that the command coalesce -
EXEC @QUERY (without parentheses)I get the error saying: The database 'UPDATE CUSTOMER' does not exist. Make sure the name is spelled correctly.
how can i put that to work ?
Remember, if a run the procedure with the update statement static, without EXEC, it works
UPDATE CUSTOMER..people SET LastName = COALESCE(@LName, LastName) WHERE id = 1
The first one doesn’t work because there is no variable @Lname in the context of the exec – it only exists in your procedure’s scope. You need to pass it into the scope of the query by using
sp_executesqlinstead of execBUT
I wouldn’t recommend doing anything at all like this.