|
Here is a section of a dynamically built stored procedure in a shortened format. This is part of a large stored procedure that de-normalises a bunch of tables and returns all the data in an XML document. The dynamic part of this involves passing in switches as BIT that can be used to exclude tables from the returned document. In this section we may or may not require table A and this is successfully done using @A_Switch. What happens when this table is returned is that we may or may not require the associated field 'Text' from table B. We have a switch passed in called @B_switch My question is how do I exclude B.Text from the select? I have been informed that I could use CASE but cannot see how to do this. Any advice would be much appreciated.
(comments are locked)
|
|
Dynamic SQL may be your only answer if it's complicated then. You could do something like:
Edited to use sp_executesql to ensure query plan reuse and ability to use parameterised query
(comments are locked)
|
|
Found it. Thanks anyway Melvyn as I've garnered some food for thought with your answers. The solution is (as simple as) : SELECT A.Id, Code, Description, CASE WHEN @B_switch THEN B.Text END AS "B/Text" FROM dbo.vw_A A JOIN dbo.vw_B B ON A.Id = B.Id WHERE @A_switch = 1 FOR XML PATH('A'), TYPE Suggest you mark this as the answer - I think it's better than the dynamic SQL.
Oct 22 '09 at 01:11 PM
Melvyn Harbour 1 ♦♦
(comments are locked)
|
|
You should just be able to use standard conditional logic, surely: I see what you are saying and yes, this would be a useful solution under normal circumstances. However, we have nested SELECTs and one of the possible excluded fields is on the outer table. Given the size of the SP, doubling the size of it is not really an option. It would work in some of the nested SELECT though.
Oct 22 '09 at 09:00 AM
Mark Veitch
Are you trying to remove the whole column from the select, or can you cope with it just being null if the switch is not set?
Oct 22 '09 at 09:20 AM
Melvyn Harbour 1 ♦♦
Need to remove the whole column I'm afraid otherwise I would have used a CASE statement to set the field to NULL. I could build some of the nested SELECTS dynamically (conditionally) in a similar way to the method you mentioned but I'd still have the same issue with the outermost table.
Oct 22 '09 at 10:45 AM
Mark Veitch
(comments are locked)
|
|
Using Melvyns way ,but instead of EXEC use sp_executesql. This allows you to also use parameterized statements and will reuse an execution plan. Yup. Valid comment. I'll amend my answer.
Oct 22 '09 at 01:10 PM
Melvyn Harbour 1 ♦♦
(comments are locked)
|

