假设我有一个名为 的表,Customer
其中包含主键和数据列,例如Name
和DateOfBirth
。我想编写一个名为 SP UpdCustomerByKey
,它接受参数CustomerKey
,Name
和DateOfBirth
。
该CustomerKey
参数是必需的,但数据参数是可选的。如果未提供,则该列应保持不变。
通常,这是通过类似的事情完成的
CREATE PROCEDURE [UpdCustomer]
(
@CustomerKey BIGINT,
@Name NVARCHAR(100) = NULL,
@DateOfBirth DATETIME = NULL
) AS
BEGIN
UPDATE Customer SET
Name = ISNULL(@Name, Name),
DateOfBirth = ISNULL(@DateOfBirth, DateOfBirth)
WHERE CustomerKey = @CustomerKey
END
这边走
UpdCustomer @CustomerKey=123, @DateOfBirth='2000-05-12'
将更新DateOfBirth
,同时保持Name
不变。
这种设计的问题在于它不允许调用者将数据列设置为NULL
。如果我尝试设置DateOfBirth
为NULL
这样:
UpdCustomer @CustomerKey=123, @DateOfBirth=NULL
DateOfBirth
它不会设置为,而是NULL
使该列保持不变。
如何保留这个基本设计但允许将列设置为NULL
?