views:

49

answers:

2

I'm using If Condition Srore procedure...

But .. I need if stored procedure with where in if else condition and concatenate with to and condition in Query..

Examble

create procedure [dbo].[Sp_Name]
    @code int,
    @dCode int  
As
select <.........> from  <tablename>
Where empcode=@code 
if (@dCode != 0)
Begin
    And dptcode=@ dCode 
End

Please help me find a solution...

+1  A: 

Would this work for you:

create procedure [dbo].[Sp_Name]
    @code int,
    @dCode int          
As
    select <.........> from  <tablename>
    Where empcode=@code AND (@dCode = 0 OR dptcode=@dCode)

Your question is pretty hard to understand - this is what I guess from what I actually did understand.

Thorsten Dittmar
That's how I would do it. One caveat though, sql doesn't short-circuit boolean expressions, so both sides of the 'or' will always be evaluated. It doesn't change the logic in this case, but something for people to be aware of...
HS
If that's what he's asking, then it will work; but the query won't be able to leverage indexes effectively. So unfortunately, it may be better to just use 2 queries.
Craig Young
A: 
create procedure [dbo].[Sp_Name]
    @code int,
    @dCode int          
As
select <.........> from  <tablename>
Where empcode=@code 
if (@dCode != 0)
Begin
    Select dptcode=@dCode 
End

Not sure if that's what the poster was after, can some one please edit the text and correct it.

Darknight