Reputation: 1530
I have been reading quite a few SO threads & others on how to achieve this, but nothing is really helping me.
IE:
How do I name a column as a date value
todays date as a column name to a simple select statement.
I could go on showing you threads that I have read, but none seem to answer what I want.
Essentially, what I am trying to do in SQL is this:
SELECT
Blahblah AS DATENAME(MONTH, GETDATE()) --AS "September"
OR
DECLARE
@CM VARCHAR(50)
SET
@CM = DATENAME(MONTH,GETDATE())
SELECT
Blahblah AS @CM --AS "September"
I'm aware that none of those work, but that is to show you what I am trying to do. Has anyone been able to achieve this?
Could you point me to a Thread you may have read that helped you do this?
Many thanks,
Mike
Upvotes: 1
Views: 2870
Reputation: 15464
TRy this
DECLARE
@CM VARCHAR(50),
@sql varchar(max)
SET @CM = DATENAME(MONTH,GETDATE())
SET @sql ='SELECT
''Blahblah'' as '+ @CM
exec(@sql)
Upvotes: 0
Reputation: 44921
You could maybe use dynamic sql like this:
create table t (val int)
insert t values (100)
declare @month varchar(20) = datename(month, getdate())
declare @sql varchar(max)
set @sql = 'select val as ' + @month + ' from t'
exec (@sql)
Result:
September
-----------
100
Upvotes: 2