动态查询游标

时间:2014-09-29 11:22:34

标签: sql-server sql-server-2008-r2 cursor

我需要为游标编写动态查询以获取表的索引名称。

尝试1:

DECLARE @Cur AS Cursor

EXECUTE SP_EXECUTESQL N'SET @Cur = CURSOR fast_forward for 
                        SELECT IndexColumn = i.name
                        FROM sys.indexes i
                        INNER JOIN sys.tables t ON t.object_id = i.object_id
                        WHERE
                        T.Name = ''' + @TableName + ''''

错误:'+'附近的语法不正确。

尝试2:

 DECLARE @sqlstatement nvarchar(max)

 SET @sqlstatement = 'DECLARE @Cur AS CURSOR fast_forward for 
                 SELECT IndexColumn = i.name
                 FROM sys.indexes i
                 INNER JOIN sys.tables t ON t.object_id = i.object_id
                 WHERE
                 T.Name = ''' + @TableName + ''''
 PRINT(@sqlstatement)
 EXEC sp_executesql @sqlstatement

错误:'fast_forward'附近的语法不正确。

2 个答案:

答案 0 :(得分:1)

游标声明不正确(丢失@ / AS

 SET @sqlstatement = 'DECLARE Cur CURSOR fast_forward for 
                 SELECT IndexColumn = i.name
                 FROM sys.indexes i
                 INNER JOIN sys.tables t ON t.object_id = i.object_id
                 WHERE
                 T.Name = ''' + @TableName + ''''

(尝试1不正确,因为光标不在字符串中构建的批处理范围内)

答案 1 :(得分:1)

因为游标不在范围内,所以不需要声明。你也可以这样做 -

SET @sqlstatement = 'DECLARE cur_mycursor CURSOR fast_forward for 
                 SELECT IndexColumn = i.name
                 FROM sys.indexes i
                 INNER JOIN sys.tables t ON t.object_id = i.object_id
                 WHERE
                 T.Name = ''' + @TableName + ''''
EXEC(@sqlstatement)

OPEN cur_mycursor

FETCH NEXT FROM cur_mycursor INTO .... blah..blah...