-1

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
1

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

I tried your code as: 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 But I received the error "Incorrect syntax near the keyword 'FROM'
@Dominick, remove last comma before FROM

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.