• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 210
  • Last Modified:

SQL IF ELSE statement

I am getting an error on the following statement and I cannot figure out why:

IF CONTAINS(SUBSTRING(Task, 4, LEN(Task)), '-')

BEGIN

UPDATE    table1
SET              Task = SUBSTRING(Task, 1, 3) + '0' + SUBSTRING(Task, 4, LEN(Task))
WHERE     (field1 = 'TEST') AND (field2 = 'BASELINE')

END

The SQL compiler says there is an error near the '(' character
0
zintech
Asked:
zintech
  • 3
  • 2
1 Solution
 
Rajkumar GsSoftware EngineerCommented:
You cannot use, IF condition like this. Try this way, by using CHARINDEX
UPDATE    table1
SET              Task = SUBSTRING(Task, 1, 3) + '0' + SUBSTRING(Task, 4, LEN(Task))
WHERE     (field1 = 'TEST') AND (field2 = 'BASELINE')
	and CHARINDEX('-', SUBSTRING(Task, 4, LEN(Task))) > 0

Open in new window

0
 
Rajkumar GsSoftware EngineerCommented:
instead of using 'IF' (which contains a table column) you can use it in WHERE condition.
0
 
zintechAuthor Commented:
My issue is that I have to use an IF statement with an ELSE.  Is there any way I can use an IF statement in this case
0
 
zintechAuthor Commented:
I suppose I could do a series of many WHERE statements as opposed to an IF statement
0
 
Rajkumar GsSoftware EngineerCommented:
You can use CASE statement in WHERE condition - that can do something whether one condition satisfies, else do something else.

...WHERE COLUMN = CASE WHEN 1 = 1 THEN 'Same' ELSE 'Different' END

Open in new window


Or if you want to stick on 'IF', you need to write full query in IF statement. Just mentioning column name alone not works

Raj
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now