question

kiankumarreddyk avatar image
kiankumarreddyk asked

How to assign dynamic column alias name in select query?

Hello, Is it possible to dynamically generate a column alias? Please see below eg: declare @strDate varchar(100) set @strDate = 'instr-' + convert(nvarchar(100), getdate()) select Name as @strDate from settings Expected column headers of the query results output should be: Name, Jan 2016 results, Feb 2016 results,.....Apr 2017 results. Please help me how can I achieve the above scenario
dynamic sqlpl-sql
10 |1200 characters needed characters left characters exceeded

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

· Write an Answer
AndrwWhlr avatar image
AndrwWhlr answered
you could do something like this. DECLARE @strDate VARCHAR(100) SET @strDate = 'instr-' + CONVERT(NVARCHAR(100), GETDATE()) DECLARE @sql NVARCHAR(MAX) SET @sql = 'select Name as ' + QUOTENAME(@strDate, '[') + ' from settings' PRINT @sql --EXEC(@sql)
10 |1200 characters needed characters left characters exceeded

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.