Kelk Kelk - 6 months ago 17
SQL Question

Is it possible to add SQL alias from subquery?

I want to add aliases to sql query from select subquery.

something like

SELECT
ID AS(
SELECT
TOP1 NAME
FROM MYTABLE
)
,NAME
,SURNAME
FROM PEOPLE


Is it possible?

Error:


Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '('. Msg 102,
Level 15, State 1, Line 1 Incorrect syntax near ','. Msg 156, Level
15, State 1, Line 8 Incorrect syntax near the keyword 'and'

Answer

Only possible with this:

DECLARE @n VARCHAR(MAX), @sql VARCHAR(MAX)

SELECT TOP 1 @n = NAME FROM MYTABLE
SET @sql = 'SELECT ID AS ' + @n + ', NAME, SURNAME FROM PEOPLE'

EXEC(@sql)