Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

where clause depend on variable

Status
Not open for further replies.

Guest_imported

New member
Joined
Jan 1, 1970
Messages
0
hi guys
i have to created one conditional

i have to create where claused depend on variable
please help to do this.

if substring(jcode)='JOB'
set VAR1='JOB_CODE'
else
set VAR1='JOB_SALORDNO'
if exist(select * from jobmast where @var1='000152JOBA')
what wrong in it does not work

m.a.khaleel

 

MS SQL does not allow variables to used for database, table or column names. You can do the following.

Declare @rc int
Set @rc=0

if substring(jcode)='JOB'
if exist(select * from jobmast
where JOB_CODE='000152JOBA')
Set @rc=1
else
if exist(select * from jobmast
where JOB_SALORDNO='000152JOBA')
Set @rc=1

If @rc=1
Begin
<your code here>
End

You could also create and execute dynamic SQL statements.

declare @sql nvarchar(200), @rc int, @var1 nvarchar(12)
set @rc=0

if substring(jcode)='JOB'
set @var1='JOB_CODE'
else
set @var1='JOB_SALORDNO'

Set @sql=
'if exists (select * from jobmast where ' +
@var1 + '=''000152JOBA'') Set @rc=1'

exec sp_executesql @sql,N'@rc int Output',@rc=@rc output

If @rc=1
Begin
<your code here>
End

---------------------------------

I've seen a number of your posts as Visitor. I recommend that you join Tek-Tips. Terry L. Broadbent
FAQ183-874 contains tips for posting questions in these forums.
NOTE: Reference to the FAQ is not directed at any individual.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top