Question

I am trying to find out how to use a calculated value as part of an alias name .

For example:

Select employeeName as ''name of guy' but where 'name of guy' could be getdate() + 'name o guy' Addin qualifiers just prevents the code inside from calculating.

Is this possible in any way? I'm going to use a partition to group results by year and I need the column aliases to be based on the year thy are in

Was it helpful?

Solution

I don't know if it's what you are looking for but it could be a good starting :

DECLARE @var table(rownum int, rowkey varchar(60), ALIAS varchar(80))
INSERT INTO @var SELECT row_number() over (ORDER BY employeeName), employeeName, cast(getdate() AS varchar(12))+employeeName FROM Table1
DECLARE @query varchar(500)
DECLARE @rowkey varchar(60), @i int, @max int
SET @i = 1
SET @max = (SELECT count(*) FROM @var)
SET @query = ''
WHILE @i <= @max
BEGIN
    SET @rowkey = (SELECT rowkey FROM @var WHERE rownum = @i)
    SET @query = 'select employeeName as "'+(SELECT ALIAS FROM @var WHERE rowkey = @rowkey)+'" from Table1 where employeeName = '''+@rowkey+''';'
    exec(@query)
    SET @i = @i + 1
END;

OTHER TIPS

If you're only expecting a single value, you could use a table variable. However, if multiple rows are created it effectively becomes a temporary table. If you think that's likely, declare as a temporary table.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top