顺序列名

时间:2019-03-13 10:43:20

标签: sql-server tsql

具有简单的查询,例如:

select * from foo

输出中包含列

bar | abc | def
---------------
...............

是否可以将此查询封装到另一个查询中,并给诸如1|2|3...之类的列赋予顺序名称(保持所有行不变)?

我知道这听起来很奇怪,而且可能甚至不可能。

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

尝试一下:

DECLARE @TableName NVARCHAR(100) = 'YOUR TABLENAME HERE',
    @Query NVARCHAR(MAX) = 'SELECT '

SELECT @Query = CONCAT(@Query, '    ', COLUMN_NAME, ' AS ', QUOTENAME(ROW_NUMBER() OVER(ORDER BY ORDINAL_POSITION)), ', 
')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName

SET @Query = SUBSTRING(@Query, 0, LEN(@Query) - 3) + ' 
FROM ' + QUOTENAME(@TableName)

您使用INFORMATION_SCHEMA.COLUMNS来获取表的所有列, ROW_NUMBER()窗口函数可为列别名生成顺序号,而sp_ExecuteSQL可执行动态生成的查询。

答案 1 :(得分:1)

尝试

DECLARE @Sql NVARCHAR(max),
        @TableName VARCHAR(100) = '<YourTableName>'
;WITH CTE
AS
(
SELECT  DENSE_RANK()OVER (ORDER BY COLUMN_NAME) Rno,
        TABLE_NAME,
        COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE  TABLE_CATALOG='Database' 
AND TABLE_NAME =  @TableName
) 
SELECT 'SELECT '+ STUFF((SELECT ', '+ COLUMN_NAME +' AS '+ QUOTENAME(CAST(Rno AS VARCHAR))
FROM CTE
FOR XML PATH ('')),1,1,'') + ' FROM '+@TableName 
PRINT @Sql
EXEC (@Sql)