sql - T-SQL:带有表和列参数的游标

标签 sql t-sql sql-server-2005 stored-procedures cursor

编写一个存储过程,其中有两个 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/

相关文章:

php - 使用php函数从sql数据库中删除

mysql - 如何查找 mySQL DB 中没有重复的行?

sql - 我必须在不使用函数或存储过程的情况下用 '&' 分隔值分割字符串?

sql-server - SQL 错误 - 必须声明表变量 "@tablename"

sql-server-2005 - 将数字转换为字母

php - 如何将所有数组数据插入mysql?

sql - 编写具有多个聚合列和多个 where 子句的查询的最佳方式是什么

c# - 使用sqlserver 2005在特定位置插入值

sql - 将存储过程的返回值分配给 SQL 中的变量的最佳方法是什么?

sql - 如何更改 DataGrip 中的字符集?