views:

244

answers:

5

I want to display Alias name based on the value of some other column name in the query in SQL Server. For e.g.

SELECT P.Amount AS (CASE P.Type WHEN 'Individual' THEN 'Salary' ELSE 'Profit' END)
  FROM Person P

I know the above is not right, but something like this will help.

+1  A: 

Hi,

You'd need to return Amount as "Amount" and then return an extra column containing the "type" for that amount.

i.e.g

SELECT P.Amount, CASE P.Type WHEN 'Individual' THEN 'Salary' ELSE 'Profit' END AS AmountType
FROM Person P
AdaTheDev
+2  A: 

The "Alias" name is the name of the entire column of the data you are returning. It is not possible for this to change on a "by row" basis.

The only way you can change a column name (alias) dynamically is using dynamic SQL to build up your query. However, this does not appear to be what you are wanting to do.

Robin Day
And at that, even dynamic SQL will only be able choose ONE name for the alias for a whole given query.
mjv
+1  A: 

No can do...

SQL returns a recorset which can only have one name / alias per each column.
Which name would it choose it example given if some records returned by the query were 'Individual' and some were some other type?

Of course, as suggested in several responses, you can modify the number of columns returned by the query and name each column as desired but dealing with such a results set that may then require additional logic, which would defeat the purpose since if one wanted extra logic, he/she may just select both the Amount and the Type and work off these values for attribute naming and such at the level of the application...

mjv
+5  A: 

I'm not sure if you can add dynamic aliases, but you should be able to do something like this (if you have only a few possible aliases):

SELECT
    CASE P.Type WHEN 'Individual' THEN P.Amount ELSE NULL END AS Salary,
    CASE P.Type WHEN 'Individual' THEN NULL ELSE P.Amount END AS Profit
FROM
    Person p
Lukáš Lalinský
+1 Good spot, this may actually do what he is after. Didn't think of this.
Robin Day
Thanks, this is definitely the closest deal I could get
Jason M
A: 

A column can have one and only one name. If your rowset contained only one row, then you could look at the row's Type column first and then change the column name appropriately for the select. If it contains multiple rows, it's simply not possible.

IF 1 = (SELECT COUNT(*) FROM Person P WHERE <where-criteria>) THEN
    IF 'Individual' = (SELECT P.Type FROM Person P WHERE <where-criteria>) THEN
        SELECT P.Amount AS Salary
        FROM Person P
        WHERE <where-criteria>
    ELSE
        SELECT P.Amount AS Profit
        FROM Person P
        WHERE <where-criteria>
    END IF
ELSE
    SELECT P.Amount AS SalaryOrProfit
    FROM Person P
    WHERE <where-criteria>
END IF

I think you might need to re-examine your design.

Cade Roux