Reputation: 1152
Writing a Stored Procedure which has two varchar parameters for column and table name. I want to use these parameters within a Cursor.
The following compiles (code snippet):
...
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)
...
However, when I attempt to execute the query with arguments I get the errors:
> 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.
Any ideas?
Upvotes: 2
Views: 434