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 |
allan8964
Posting Yak Master
249 Posts |
Posted - 2012-11-15 : 13:44:37
|
Hi there,I have a problem with WHERE clause branch in a sp. Here is the sample:1.select Sum(ProdNum) ... from Table1where Code = @Code and Left(Model, 4) = 'ABCD' ...2.select Sum(ProdNum) ... from Table1where Code = @Code and Right(Model, 4) = 'ABCD' ...there are about 100 pieces of statements like those. When the @code values change the different statement is run, for example, if @code='M123' then it runs #1, @code='N321' then it runs #2, so forth. I am thinking is there any way like branch in c# or other better ways to simplify the codes, because the each WHERE clause is long, each select piece takes about 70 lines, or I can only write 100 stored procedures? Really appreciate your help! |
|
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts |
Posted - 2012-11-15 : 13:55:22
|
Couple of ways I can think of:1. Create a look up table - something like this:CREATE TABLE dbo.CodeLookup(code CHAR(4))INSERT INTO dbo.CodeLookup VALUES('M123'),('N321')SELECT SUM(ProductNum)FROM Table1 t1 INNER JOIN dbo.CodeLookup c ON t1.Model LIKE c.code + '%'; 2. Use dynamic SQL. Even though usually one would try to avoid dynamic sql if at all possible, this is one of those cases you might consider it.I prefer the lookup table, but you may need dynamic sql if your join condition changes for each lookup value (as in your example, it is RIGHT(Model,4) in one case and LEFT(Model,4) in another case. There is a discussion of the reasons for doing this and the safe way to do this at Gail Shaw's blog here: http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/ |
|
|
allan8964
Posting Yak Master
249 Posts |
Posted - 2012-11-15 : 17:19:07
|
I am not sure about #1 but dynamic sql is something I must try. Thanks for the idea! |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-11-15 : 22:20:15
|
quote: Originally posted by allan8964 I am not sure about #1 but dynamic sql is something I must try. Thanks for the idea!
For first method you just need to create the mapping table as Sunita suggested with values based on your @Code values------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
|
|
|
|
|
|
|