我创建了一个存储过程来仅更新表中已更改的行
我使用了SQLSERVER coalesce
函数。
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
一些注意事项
是动态sql
数据库的名称在过程中作为参数传递
所以,当我运行 sql 时,我有两种情况:
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.
我怎样才能让它发挥作用?
请记住,如果使用更新语句静态运行过程,而不使用 EXEC,它可以工作
UPDATE CUSTOMER..people SET LastName = COALESCE(@LName, LastName) WHERE id = 1