编写一个存储过程,其中有两个 varchar 参数用于列名和表名。我想在游标中使用这些参数。
以下编译(代码片段):
...
ALTER PROC [sp_test](
@TabName VARCHAR(MAX),
@ColName VARCHAR(MAX))
AS
DECLARE @SQL VARCHAR(MAX);
SET @SQL = 'SELECT ' + @ColName + 'FROM ' + @TabName + 'ORDER BY ' + @ColName
EXEC ('DECLARE curs CURSOR FOR ' + @SQL)
...
但是,当我尝试使用参数执行查询时,我收到错误:
> Msg 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword
'BY'.
> Msg 16916, Level 16, State 1, Procedure sp_testCrypt, Line 89 A
cursor with the name 'curs' does not exist.
> Msg 16916, Level 16, State
1, Procedure sp_testCrypt, Line 96 A cursor with the name 'curs' does
not exist.
有什么想法吗?
最佳答案
在“ORDER”前加一个空格 例如:“排序依据”
关于sql - T-SQL:带有表和列参数的游标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19160056/