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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A Seach Proc with optional parameters

Status
Not open for further replies.

joebickley

Programmer
Aug 28, 2001
139
0
0
GB
Hi
Im trying to make a proc return a list of data depending on what parameters are sent too it. There are 8 parameters all of which are optional. If non are sent it returns all the records if 2 are sent it uses them etc etc

How can i build a wher clause to reflect this as it can be different each time.

Thanks

Joe

 
where fld1 = coalesce(@prm1,fld1)
and fld2 = coalesce(@prm2,fld2)
and ...

or you can build up the statement in dynamic sql.
declare @sql varchar(8000)

if @prm1 is not null
select @sql = colesce(@sql + ' and','where') + 'fld1 = ''' + @prm1 + ''''
if @prm2 is not null
select @sql = colesce(@sql + ' and','where') + 'fld2 = ''' + @prm2 + ''''
if ...


select @sql = coalesce(@sql,'')
exec (@select + @sql)


======================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top