0

I am trying to create an If Else Update Script. This is what I have put together so far:

IF (SELECT [FileType1] 
    FROM Document 
    WHERE ([FileType1] LIKE 'E-mail' OR [FileType1] LIKE 'outlook'))

    UPDATE Document
    SET [FilePath] = [Full Path]

ELSE ((SELECT [FileType1] 
       FROM Document 
       WHERE ([FileType1] NOT LIKE 'E-mail' OR [FileType1] NOT LIKE 'outlook'))

    UPDATE Document
    SET [Path] = [Full Path]

What I am I doing wrong? Basically, if E-mail or outlook is found in one statement, I want the filepath column to equal the full path column.

If non-E-mails are found, I want the path column equal to the full path column.

2
  • Possible duplicate of using a conditional update statement in sql Commented Jun 13, 2016 at 20:10
  • not sure why you need IF ELSE here; what is preventing you to write conditions on UPDATE Commented Jun 13, 2016 at 20:11

2 Answers 2

2

You can do this with a CASE statement while defaulting the ELSE condition to itself:

Update  Document
Set     FilePath =  Case When FileType1 In ('E-mail', 'Outlook')
                        Then [Full Path]
                        Else FilePath
                    End,
        [Path]   =  Case When FileType1 Not In ('E-mail', 'Outlook') 
                        Then [Full Path]
                        Else [Path]
                    End

I've also removed the LIKE statements (since you're only using them for equality), and removed the OR statements in preference of an IN and NOT IN.

Sign up to request clarification or add additional context in comments.

Comments

2

Alternatively, you can simplify and shorten Siyual's suggestion to just using [iif], which is relatively new, i.e. introduced with SQL Server 2012.

update d
set FilePath = iif(FileType1 in ('E-Mail', 'Outlook'), FullPath, FilePath),
    Path = iif(FileType1 not in ('E-Mail', 'Outlook'), FullPath, Path)
from Document d;

Hopes this help.

1 Comment

IIF in SQL? I was a bit surprised, but then I read in here: msdn.microsoft.com/en-AU/library/…

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.