Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Various combinations of input into a query?
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Posting Yak Master

129 Posts

Posted - 02/11/2013 :  14:30:39  Show Profile  Reply with Quote
Trying to convert dynamic SQL code into a SPROC.
There are potential 5 inputs into the SPROC.
I am guessing I need to check to see which combination of parameters are NOT NULL (And also the ones which are NULL) in order to execute the right query.

however, there is also another problem... what if params1, 2, 4 are populated? or params1, 2, 3 populated? or 2, 3, 4 are populated? it means I have to do a query for each combination right?

is there a better way to do this or do I have to just do with what I am doing which is just to check each parameter/combination and execute that type of query?

James K
Flowing Fount of Yak Knowledge

3873 Posts

Posted - 02/11/2013 :  19:00:30  Show Profile  Reply with Quote
Since no one else has responded yet, I will give it a try

If you write one query each for each combination, it is going to be huge chunk of code that would be hard to debug and maintain.

Instead, what I would suggest is to use dynamic SQL. But not dynamic SQL in your client code (i.e. don't use adhoc dynamic SQL); Dynamic SQL in a stored procedure is what I am thinking of. This is one of those cases where dynamic SQL is indeed useful and is the best choice. Dynamic search conditions <-> Dynamic query.

When you write the code, it has to be done carefully to avoid SQL injection. There are two articles you should read:

The first article is exhaustive and very thorough. The second one is shorter and to the point. Once you get the gist of what they are saying, it is relatively simple to implement.

Give that a try and if you run into difficulties, post the code with some sample data etc.

Edited by - James K on 02/11/2013 19:03:41
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.02 seconds. Powered By: Snitz Forums 2000