Gautam
Gautam

Reputation: 1740

using if statement in stored procedure in sql

I have a stored procedure that is returning me some records. Now I want to change the condition on which the records are being shown on the basis of a condition

select * from table
WHERE cond1 = c1
AND cond2 = c2

basically I want a structure like this

if(Val1= Val2) then  
select * from table
WHERE cond1 = c1
AND cond2 = c2
AND cond3 = c3
else
select * from table
WHERE cond1 = c1
AND cond2 = c2

Since the stored proc is huge and I can't change too much in that so I can only change the where condition using if statement.

Upvotes: 0

Views: 4041

Answers (2)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239636

Just include the condition in your where clause:

select * from table
WHERE cond1 = c1
AND cond2 = c2
AND (Val1 <> Val2 OR cond3 = c3)

If this structure keeps expanding - maybe you're doing some form of search with different possible parameters - it's worth reading Erland Sommarskog's Dynamic Search conditions in T-SQL

Upvotes: 3

Kapil Khandelwal
Kapil Khandelwal

Reputation: 16134

Try this:

IF Val1 = Val2 
BEGIN

END
ELSE
BEGIN

END

Upvotes: 0

Related Questions