使用IF语句的SQL UPDATE

时间:2016-02-29 18:11:23

标签: sql sql-server if-statement select sql-update

我有一个表,其唯一标识符为“name”,两个字段都是布尔语句。这两个领域名为“sentbirth”和“senthire”。

我要做的是查看已发送的郡或分娩的价值是否为真。如果是这样,我想把它保留为真。但如果它是假的,那么我希望它用我的Web应用程序生成的@SentBirth或@SentHire值进行更新。

到目前为止我所拥有的是:

SELECT [name],[sentbirth],[senthire]
FROM [CCRAuction].[dbo].[cardsUser]
WHERE name = @Name

IF [sentbirth] = '1'
    BEGIN
    UPDATE [CCRAuction].[dbo].[cardsUser]
        SET [sentbirth] = '1'
    END 
 ELSE
    BEGIN
     UPDATE [CCRAuction].[dbo].[cardsUser]
        SET [sentbirth] = @SentBirth
    END

IF [senthire] = '1'
    BEGIN
    UPDATE [CCRAuction].[dbo].[cardsUser]
        SET [senthire] = '1'
    END
 ELSE
    BEGIN
     UPDATE [CCRAuction].[dbo].[cardsUser]
        SET [senthire] = @SentHire
    END

使用此代码,我收到错误消息“sentbirth”和“senthire”是无效的列名。

如何在Microsoft SQL Server Management Studio中正确编写此代码?

回答这个问题是:

UPDATE cu SET
  [sentbirth] = CASE WHEN cu.[sentbirth] = '1' THEN cu.[sentbirth] ELSE @SentBirth END,
  [senthire] = CASE WHEN cu.[senthire] = '1' THEN cu.[senthire] ELSE @SentHire END
FROM [CCRAuction].[dbo].[cardsUser] cu
WHERE cu.name = @name

1 个答案:

答案 0 :(得分:2)

检查并保持旧状态或使用new进行更新,对其他字段进行更新:

UPDATE cu SET
  [sentbirth] = CASE WHEN cu.[sentbirth] = '1' THEN cu.[sentbirth] ELSE @sentbirth END,
  ...
FROM [CCRAuction].[dbo].[cardsUser] cu
WHERE cu.name = @name