Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
tech_1
Posting Yak Master
129 Posts |
Posted - 2013-02-11 : 14:30:39
|
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
Master Smack Fu Yak Hacker
3873 Posts |
Posted - 2013-02-11 : 19:00:30
|
Since no one else has responded yet, I will give it a tryIf 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:http://www.sommarskog.se/dyn-search-2008.htmlhttp://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/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. |
|
|
|
|
|
|
|