adilahmed
adilahmed

Reputation: 1572

IF condition in SQL query

Here is my SQL query

Declare @Type varchar

select  
  if
    (tn.notification_type=1)
  begin
    set @Type= 'WORK FLOW'
    print  'status  '+ CAST(@type AS nvarchar(58))  
  end
from tbl_Notification tn

here I am getting problem to include a condition based on a table column value

E.g. I have values 1 and 2 and 3

when I execute I am getting the error.

Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'if'.
Msg 156, Level 15, State 1, Line 9
Incorrect syntax near the keyword 'from'.

Upvotes: 0

Views: 8007

Answers (3)

tonyellard
tonyellard

Reputation: 156

To elaborate on Namphibian's answer, which is accurate:

SELECT
      @Type = (CASE tn.Notification_Type 
                   WHEN 1 THEN 'WORK FLOW' 
                   ELSE 'SOMETHING ELSE' 
                END)
FROM tbl_Notification tn

You also won't be able to do the print in the SQL query like that, you'd have to do it afterwards or in some sort of looping situation.

Upvotes: 2

juergen d
juergen d

Reputation: 204746

Declare @Type varchar 

if((select tn.notification_type from tbl_Notification tn) = 1) 
begin
   set @Type= 'WORK FLOW' 
   print 'status '+ CAST(@type AS nvarchar(58))
end 

Upvotes: 0

Namphibian
Namphibian

Reputation: 12211

Replace the if statement with a case statement. You cant use the if in a query like that.

Upvotes: 3

Related Questions