2

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

有任何想法吗?

4

1 回答 1

2

在 "ORDER" 之前放一个空格 例如:' ORDER BY '

于 2013-10-03T13:21:15.833 回答