I'm working with some store procedures, one in particular, requires me to use a condition for a specific field of the select. My select is like this:
acc.AccountNum AS [Voucher_ID],
pol.Number AS [Policy_Number],
veh.Vehicle AS [VIN],
What I'm trying to do is change the column alias to the AS dynamically, which then amends based on a condition, I tried to insert an if like this:
acc.AccountNum AS If(@x = 1){[Voucher_ID]} else {[Voucher_ID2]},
But it does not work, I also tried a case but that didn't work either, is there a way to do this or do I have to create two distinct selects?
CodePudding user response:
As mentioned by @Larnu in comments, you cannot have dynamic column literals. You can have both aliases and pick up based on the nullability.
CASE @x = 1 then acc.AccountNum ELSE NULL END AS [Voucher_ID],
CASE @x <> 1 OR @x IS NULL then acc.AccountNum ELSE NULL END AS [Voucher_ID2],
pol.Number AS [Policy_Number],
veh.Vehicle AS [VIN],
CodePudding user response:
An alias must be a literal. this means that what was requested in my application is only feasible in one way: Create 2 distinct selects, and insert the required condition before the select, like this:
IF @x = 1
SELECT acc.AccountNum AS [Voucher_ID],
pol.Number AS [Policy_Number],
veh.Vehicle AS [VIN]
FROM program WHERE ...
IF @x = 2
SELECT acc.AccountNum AS [Voucher_ID2],
pol.Number AS [Policy_Number],
veh.Vehicle AS [VIN]
FROM program WHERE ...