简体   繁体   中英

SQL UPDATE using an IF statement

I have a table that has a unique identifier of "name" and two fields that are both Boolean statements. The two fields are titled "sentbirth" and "senthire".

What I am trying to do is to see if the value is already true for senthire or sentbirth. If so I want to leave it as true. But if it is false then I want it to update with the @SentBirth or @SentHire value that is being produced from my web application.

What I have so far is:

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

With this code as is I am receiving the error message that 'sentbirth' and 'senthire' are invalid column names.

How do I write this code properly in Microsoft SQL Server Management Studio?

Answer to this question is:

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

check and keep old or update with new, same for other fields:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM