Can I use Functions / expressions to name a column via the "As" statement in T-SQL?
I'm hoping to dynamically name columns in a query based on a users choice of a parameter.
My idea was that based on the users choice the column would be named via the "As" that comes after the column/field specification.
Here is my example:
Select Distinct
Case @DateParam
When 'Created' Then Convert(Varchar, h.wmhd_cre_date, 101)
When 'Action' Then Convert(Varchar, d.wmdt_date, 101)
End As CONCATENATE(@DateParm + 'Date'),
So if the user selected the parameter for the "Created" date, then the column header would show "CreatedDate". But if they selected the parameter for "Action" date, then the column would be named "ActionDate".
I've tried to do similar things befor开发者_如何学Pythone and I'm starting the get the idea that you can't put expressions after an "As" statement. Is this true, or does anyone have any ideas?
That is correct. An aliased identifier may not be generated via an expression.
You could do something like this, however:
SELECT DISTINCT
CASE WHEN @DateParam = 'Created' THEN CONVERT(varchar, h.wmhd_cre_date, 101) END AS CreatedDate,
CASE WHEN @DateParam = 'Action' THEN CONVERT(varchar, h.wmdt_date, 101) END AS ActionDate
If you absolutely have to return the columns in the original way you described, you will need to use dynamic sql (e.g., EXEC
or EXEC sp_executesql
)
use EXEC
passing in the query as string.Example:
declare @fnameParam varchar(50)
set @fnameParam = 'FirstName'
EXEC 'SELECT FName AS ' + @fnameParam + ' FROM Table1'
精彩评论