Setting alias name from a subquery in SQL

Nithesh Narayanan picture Nithesh Narayanan · Dec 13, 2011 · Viewed 9.8k times · Source

In my Select query I just want to to set the alias name of a column based on a sub-query (that is, a value in another table). Is this possible in SQL Server 2008?

Like:

SELECT tax_Amt AS (SELECT tax FROM Purchase.tblTax WHERE tax_ID=@tax_ID) 
FROM Table

Any way to achieve the above query?

Answer

gbn picture gbn · Dec 13, 2011

No, you cannot dynamically set an alias or column name in standard SQL.

You'd have to use dynamic SQL if you want: but note the alias applies to the column therefore all rows have the same alias. You can't vary the alias row by row

Personally, I'd have an extra column called "TaxType" or such because it sounds like you want to vary the name per row. I'd do that anyway even if all rows have the same alias so my client code expects "TaxType"