0

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.

2
  • OK. So what is your question? Commented Dec 18, 2012 at 7:15
  • Its simple I need to embed a condition in where clause if a particular value satisfy the condition.. kind of dynamically editing the where clause in stored procedure Commented Dec 18, 2012 at 7:19

2 Answers 2

3

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

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

2 Comments

+1 - I don't know who Erland is, but he has some pretty useful material.
@MrMoose - I've never seen Erland on here. He used to be quite active on the usenet groups (e.g. microsoft.public.sqlserver.programming), and his work is still superbly researched.
0

Try this:

IF Val1 = Val2 
BEGIN

END
ELSE
BEGIN

END

2 Comments

will it be working within where clause? I mean I just need to add an extra "AND" condition in the where clause3
If you are wanting to change just the WHERE clause based on the variable values, then you will need to use Dynamic SQL. I mean you cannot simply code - Select * from Table IF var1=var2 WHERE...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.