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 |
Ramm10
Starting Member
2 Posts |
Posted - 2014-08-11 : 00:31:19
|
I am working on Stored Procedure in SQL 2008. I have to return the rows of a table based on different input combinations (around 17 combinations). 5 parameters are passed as i/p to this sp.I started writing the SP checking in this wayDECLARE @varDynamicQuery VARCHAR(255)SET @varDynamicQuery = 'SELECT Name, Address, PhoneDetails FROM SuperUserDetails WITH(NOLOCK) WHERE ' /* Combi 1 Input - Parameter - Output - Condition ----------------------------------------------------- UID @in_varUID TableRows None */ IF(@in_varUID IS NOT NULL AND @in_varUID <> '') BEGIN SET @varDynamicQuery = @varDynamicQuery + 'UID = '''+@in_varUID+'''' EXEC (@varDynamicQuery) END /* Combi 2 Input - Parameter - Output - Condition ----------------------------------------------- Address @in_varAddr TableRows None */ IF(@in_varAddr IS NOT NULL AND @in_varAddr <> '') BEGIN SET @varDynamicQuery = @varDynamicQuery + 'UID = '''+@in_varAddr+'''' EXEC (@varDynamicQuery) END /* Combi 3 Input - Parameter - Output - Condition ----------------------------------------------------- UID @in_varUID TableRows None Address @in_varAddr */ IF( (@in_varUID IS NOT NULL AND @in_varUID <> '') AND(@in_varAddr IS NOT NULL AND @in_varAddr <> '') ) BEGIN SET @varDynamicQuery = @varDynamicQuery + 'UID = '''+@in_varUID+''' AND Address = ''''+@in_varAddr+''' EXEC (@varDynamicQuery) ENDBut, I am sure, a better way than this. As writing 17 combinations is not a good way.If it better to write this using CASE statements?The list of combinations are,(only 6 are shown) The input parameters to Sp are also listed.Input Params C1 C2 C3 C4 C5 C6UID Y N N N N NAddress N Y N N Y YPhoneDetails N N Y Y Y NCreatedOn Y Y N Y Y YLastDate Y Y N N N YPlease advice me on this.ThanksRamm |
|
gbritton
Master Smack Fu Yak Hacker
2780 Posts |
Posted - 2014-08-11 : 07:54:48
|
Check out this article:http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/ |
|
|
|
|
|