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.
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
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
answered Oct 22 '09 at 12:20 PM
You should just be able to use standard conditional logic, surely:
answered Oct 22 '09 at 08:53 AM
Melvyn Harbour 1 ♦♦
Using Melvyns way ,but instead of EXEC use sp_executesql. This allows you to also use parameterized statements and will reuse an execution plan.
answered Oct 22 '09 at 12:36 PM