What is the best way to write a dynamic parametrized query for sql server 2005 where passed parameter value may be null?
mine is not stored procedure it's a parametrized query
NoviceToDotNet
2010-08-19 09:59:43
GO TO LINK AND SEE THE DOUCMENT ITS ALL TALK ABOUT EXCUETING DYNAMIC PARAMETERIZE QUERY
Pranay Rana
2010-08-19 10:00:54
@June: You're right but please be polite ;)
abatishchev
2010-08-20 07:33:52
@abatishchev - ok actually my caps is on that time
Pranay Rana
2010-08-20 07:46:27
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
2010-08-19 10:00:28
+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
2010-08-19 10:01:57
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
2010-08-19 10:04:20
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
2010-08-19 10:07:15
what else can i do to retain performancei want to know some code as you did above please let me know?
NoviceToDotNet
2010-08-19 16:51:35
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
2010-08-19 21:46:21