T-SQL:仅在提供值的情况下更新列

时间:2018-12-14 01:16:29

标签: sql-server tsql

当前,我有以下UPDATE语句:

UPDATE Customer 
SET Name = @Name,
    Age = @Age,
    Email = @Email
    ...

现在,仅在提供值的情况下,才需要在UPDATE语句中包括列。否则,请勿在{{1​​}}语句中包括该列。

所以从概念上讲可能是这样的:

UPDATE

有什么办法可以做到这一点?我正在考虑动态查询,但是更新列的列表非常长,因此需要大量工作来更改为动态查询,如下所示:

UPDATE Customer 
SET
    IF LEN(@Name) > 0 THEN Name = @Name,
    IF LEN(@Age) > 0 THEN Age = @Age,
    IF LEN(@Email ) > 0 THEN Email = @Email
    ...

4 个答案:

答案 0 :(得分:3)

那这样的事情呢...

UPDATE Customer SET
    [Name] = CASE WHEN ISNULL(@Name, '') = '' THEN [Name] ELSE @Name END
    ,Age = CASE WHEN ISNULL(@Age, '') = '' THEN Age ELSE @Age END
    ,Email = CASE WHEN ISNULL(@Email, '') = '' THEN Email ELSE @Email END
    ...

答案 1 :(得分:3)

我认为您应该尝试一下 (在声明并设置变量@ Name,@ Age和@Email之后)

    UPDATE Customer SET
    Name = case when @Name  is null then Name  else @Name  end,
    Age  = case when @Age   is null then Age   else @Age   end,
    Email= case when @Email is null then Email else @Email end,
    ...

如果任何变量的值为空,则不会更新该字段。

答案 2 :(得分:1)

如果您缺少的值为空:

UPDATE [Customer] SET
    [Name] = COALESCE(@Name, [Name]),
    [Age] = COALESCE(@Age, [Age]),
    [Email] = COALESCE(@Email, [Email]),
    ...

如果它们为空,则可以使用NULLIF强制转换为null,这具有将空字符串与null相同的潜在好处:

UPDATE [Customer] SET
    [Name] = COALESCE(NULLIF(@Name, ''), [Name]),
    [Age] = COALESCE(NULLIF(@Age, ''), [Age]),
    [Email] = COALESCE(NULLIF(@Email, ''), [Email]),
    ...

答案 3 :(得分:1)

您也可以尝试

UPDATE Customer SET
    [Name] = ISNULL(@Name, [Name])
    ,Age = ISNULL(@Age, Age)
    ,Email = ISNULL(@Email, Email)
...

这是在更新中检查NULL值的简便查询。