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 |
hk13
Starting Member
12 Posts |
Posted - 2015-01-13 : 11:08:49
|
Hello,This is for Microsoft Server SQL 2012.I'm trying to create a WHERE clause that will have different results depending on a parameter that is entered. For example, if you put in a number, it will only calculate the rows where the column ID matches that number. However, if you put in 0, which doesn't exist in that column ID, it will instead calculate all the data in the table.So the below would be a very basic idea of what I'm trying to do, but I'm not sure how to do it with proper syntax.WHERE IF ID=0, THEN do thisELSE do this AND ID=#Thanks in advance. |
|
gbritton
Master Smack Fu Yak Hacker
2780 Posts |
Posted - 2015-01-13 : 11:25:21
|
You may be confusing two things.There is an IF statement: http://msdn.microsoft.com/en-CA/library/ms182717.aspxThat you can use in a script or stored procedure or multi-line function to control the logic flow.There is also a CASE expression:http://msdn.microsoft.com/en-CA/library/ms181765.aspxWhich can be used inside queries (and actually anywhere an expression is allowed).In your case, I think you will use CASE, e.g.select ...(other columns)... , CASE WHEN @ID = 0 OR ColumnID = @ID THEN SUM(column_to_be_summed) ELSE 0 END AS Column_Sum , ... other columns ... Replace "SUM" with whatever calculation you need. |
|
|
hk13
Starting Member
12 Posts |
Posted - 2015-01-13 : 11:44:07
|
Thanks for the response.I'm actually just reworking a bit of SQL that mostly goes over my head, so I don't have much room to recreate it like the example you gave.However, looking over your example, I added the "OR @ID = 0" to my WHERE clause and it appears to be working now. Sitting back and thinking about it, that extra bit makes a lot of sense on getting it to work.Thanks again for the help! |
|
|
|
|
|
|
|