简体   繁体   中英

Increment an alias in dynamic sql select statement

I am trying to create a dynamic SQL statement that includes an alias that has to increment. My query is like

DECLARE @q varchar(255)
SET @q = '0'
SELECT 'SELECT (SELECT DISTINCT NameColumn 
FROM NAMETABLE) @q' 
FROM NameTable

Where for each record in nametable @q changes. So it would go @q = 0 for record 1, @q = 1 for record 2, @q = 2 for record 3, etc. I found ROW_NUMBER but that appears to only do incrementing a column and as an Int whereas I need a varchar to increment. If someone had an idea as to how to do this or could point me in the right direction that would be wonderful

Is this what you want?

SELECT 'SELECT (SELECT DISTINCT NameColumn 
                FROM NAMETABLE
              ) ' + cast(row_number() over (order by (select NULL)) as varchar(255))
FROM NameTable;

I am, however, unclear on why you would want an alias to be a number.

EDIT:

To get what you want, just pre-pend the number with a letter.

SELECT 'SELECT (SELECT DISTINCT NameColumn 
                FROM NAMETABLE
              ) t' + cast(row_number() over (order by (select NULL)) as varchar(255))
FROM NameTable;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM