short circuiting dynamic sql queries


I'm in a bit of a jiffy here...

I'm trying to short-cicuit a sql query here, where if the value in the where clause is null then it'll query all records else, query only the values in the where clause.

here's my code...

declare @filter as varchar(50)
declare @SQLCmd as varchar(4000)

set @filter = 'xxxx' -
set @SQLCmd =  'select * from table
      where  NOT ('+@filter+' IS NOT NULL and table.field <> '+@filter+' )'
exec (@SQLCmd)      

this code works when @filter contains values on every executing. my problem is when i try to execute the code where @filter = null, @SQLCmd is null all in all..
ideally, the query should look like this:

select * from table
      where  NOT (null IS NOT NULL and table.field <> null )
can someone provide me with some tips?
subsequently, how do i make this work using a where... in clause?

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Aneesh RetnakaranDatabase AdministratorCommented:
You dont really need dynamic sql here

declare @filter as varchar(50)
set @filter = 'xxxx' -
select * from table
where (@Filter IS NULL or  field like '%'+@Filter+'%' )

praetoreanAuthor Commented:
i got it already... what i did was validate the value of the parameter... if = null then, i bypass and not add an additional where clause. if <> null, then i add an additional where clause...

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Aneesh RetnakaranDatabase AdministratorCommented:
if there is only one filter then this will be better

IF @Filter is Null
     select * from table
     select * from table where ield like '%'+@Filter+'%'
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.