我有一个表具有唯一标识符“名称”和两个都是布尔语句的字段。这两个领域被称为“sentbirth”和“senthire”。SQL更新使用IF语句
我想要做的是看看这个值是否已经为senthire或sentbirth。如果是这样,我想让它成为现实。但如果它是假的,那么我希望它用我的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
[使用SQL条件更新语句可能的复制](http://stackoverflow.com/questions/6097815/using-a-conditional-update-statement-in-sql) –