假设:
您可以通过指示列的索引对结果集进行排序。
SELECT * FROM CUSTOMERS ORDERY BY 1
我正在尝试在以下上下文中使用,但是,我收到错误消息:
Msg 5308,Level 16,State 1,Line 8 窗口函数不支持整数索引作为ORDER BY子句表达式。
EXEC ("
SELECT *,
ROW_NUMBER() OVER ( ORDER BY 1 ) AS 'Seq'
from dynamic_table");
你能想到一个解决方法吗?
答案 0 :(得分:1)
如果你知道列名这应该有效:
Exec ("
select *,
ROW_NUMBER() OVER ( ORDER BY " + columnName + " ) AS 'Seq'
from dynamic_table");
如果列名称未知:
DECLARE @table_name nvarchar(100) = 'test'
DECLARE @column_name nvarchar(100)
SELECT
@column_name = columns.name
FROM sys.columns
inner join sys.tables ON tables.object_id = columns.object_id
WHERE tables.name = @table_name and column_id = 1
EXEC ('
select *,
ROW_NUMBER() OVER ( ORDER BY ' + @column_name + ' ) AS ''Seq''
from ' + @table_name);