仅当存在值时才使用TSQL Update变量

时间:2014-01-07 20:44:47

标签: sql-server tsql stored-procedures

我有一个update语句,如下所示:

UPDATE  sessions
SET currentStep      = @currentStep,
    chosenDepartment = @chosenDepartment,
    proposedTimes    = @proposedTimes
WHERE   sessionID = @sessionID
    AND empID = @empID;

我使用相同的存储过程进行多次更新,因为我的流程中的每一步都会获得额外的价值。

我的问题:有没有办法只做到这一点:

chosenDepartment = @chosenDepartment

如果@cosenDepartment实际上包含值?

如果我每次都这样做,如果我没有传递任何内容,它将用空白数据覆盖它。

2 个答案:

答案 0 :(得分:2)

试试这个:

UPDATE  sessions
SET currentStep      = @currentStep,
    chosenDepartment = CASE WHEN @chosenDepartment IS NOT NULL THEN @chosenDepartment ELSE chosenDepartment END,
    proposedTimes    = @proposedTimes
WHERE   sessionID = @sessionID
    AND empID = @empID;

或者

UPDATE  sessions
SET currentStep      = @currentStep,
    chosenDepartment = COALESCE(@chosenDepartment, chosenDepartment),
    proposedTimes    = @proposedTimes
WHERE   sessionID = @sessionID
    AND empID = @empID;

注意#1:SQL Server将翻译COALESCE(@chosenDepartment, chosenDepartment) 进入CASE WHEN @chosenDepartment IS NOT NULL THEN @chosenDepartment ELSE chosenDepartment END

注意#2:如果你想避免使用NULL @chosenDepartment,但如果你想避免使用空字符串或0进行更新,那么你可以使用NULLIF函数:{{ 1}}或COALESCE(NULLIF(@chosenDepartment,''), chosenDepartment)

答案 1 :(得分:0)

您可以在tsql之前放置if语句,这样如果@chosenDepartment为空,那么tsql就不会运行。