2016-02-29 68 views
0

我有一个表具有唯一标识符“名称”和两个都是布尔语句的字段。这两个领域被称为“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 
+0

[使用SQL条件更新语句可能的复制](http://stackoverflow.com/questions/6097815/using-a-conditional-update-statement-in-sql) –

回答

2

检查,并保持新老或更新,同样对其他领域:

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

我试过你的代码为: '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' 但是我收到错误“关键字'FROM' – Dominick

+0

@Dominick附近的错误语法,删除FROM前的最后一个逗号 –

+0

完美!这正是我所期待的!非常感谢你的帮助。更新了代码以反映答案。 – Dominick