views:

42

answers:

3

What is the best way to write a dynamic parametrized query for sql server 2005 where passed parameter value may be null?

+1  A: 

Make use of : SP_EXECUTESQL

Pranay Rana
mine is not stored procedure it's a parametrized query
NoviceToDotNet
GO TO LINK AND SEE THE DOUCMENT ITS ALL TALK ABOUT EXCUETING DYNAMIC PARAMETERIZE QUERY
Pranay Rana
@June: You're right but please be polite ;)
abatishchev
@abatishchev - ok actually my caps is on that time
Pranay Rana
A: 

How about something like

DECLARE @Table TABLE(
        val1 VARCHAR(20),
        val2 VARCHAR(20)
)

DECLARE @Param VARCHAR(20)

INSERT INTO @Table SELECT '1','2'
SELECT  *
FROM    @Table
WHERE   (@Param IS NULL OR val1 = @Param)

However, this will slow down performance. I would recomend that when you build your dynamic query, dont add parameters to the where clause, if it is not requied.

astander
+1  A: 

Only if possible:
Write the query with all the parameters included, but instead of writing a regular

WHERE
    field1=@param1
    and field2=@param2
    .....

write

WHERE
    (@param1 is null or field1=@param1)
    and (@param2 is null or field2=@param2)
    ...

or

WHERE
    field1=isnull(@param1,field1)
    and field2=isnull(@param2,field2)
    ...

but if serious performance issues occur, consider writing the query for each single case.
ONLY if this query executes many many times per second on small tables, there is a reason to write it entirely, use sp_prepare/sp_execute for it, so it will run fastest in this case.

Alexander
first let me know how do you format the code written in comment so that i can send you my code in formatted form
NoviceToDotNet
there is a JS running on this site, that formats it automatically. Just prepend each row with at least 4 spaces when writing the QUESTION or ANSWER (Doesn't work for comments). Or you could use the tool panel of the WYSIWYG editor on this site. The spaces/tabs I've added manually, because the site doesn't manage those.
Alexander
what else can i do to retain performancei want to know some code as you did above please let me know?
NoviceToDotNet
It all depends on the situation. This is a too broad question. You could try to search here for answers, or ask yourself a question about performance. But to know it better, the only way is to study, search the internet, or hire a consultant or teacher.
Alexander