如何在SQL Server中的游标中使用游标?

时间:2017-01-18 07:32:24

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

我有以下查询,我想在查询中使用嵌套游标。怎么做,因为它没有运行,我是SQL Server的新手。请帮帮我

CHECK TABLE SUGGEST LAT 31.8181 LONG 71.4146
  

Msg 16915,Level 16,State 1,Procedure Sp_CheckCarStatusMeter,Line   266个
  名称为“ShapeCursor”的游标已存在。开放   游标

     

Msg 16905,Level 16,State 1,Procedure Sp_CheckCarStatusMeter,   296行   光标已经打开。

代码:

DECLARE SuggestCursor CURSOR FOR  
    SELECT TOP 100 
        rtha.car_id, rtha.latitude, rtha.longitude 
    FROM   
        Carhistory rtha 
    WHERE 
        rtha.car_id = 6142 ;

OPEN SuggestCursor;  

FETCH NEXT FROM SuggestCursor INTO @CarSuggested, @carlatprevious, @carlongprevious;  

WHILE (@@FETCH_STATUS = 0)  
BEGIN  
    PRINT 'CHECK TABLE SUGGEST LAT '+@carlatprevious +' LONG '+ @carlongprevious;

    DECLARE ShapeCursor CURSOR FOR  
         SELECT 
             g.ID, @carID, g.ShapeType  
         FROM   
             tblgeo AS g  
         WHERE  
             car_id @ID;   

    IF (SELECT CURSOR_STATUS('local','ShapeCursor')) >= -1
    BEGIN
        Print 'DEALLOCATE CURSOR'
       --DEALLOCATE ShapeCursor
    END   
    ELSE    
        Print 'ELSE OPEN CURSOR'

    OPEN ShapeCursor;

    FETCH NEXT FROM ShapeCursor INTO @ID, @CarIdx, @ShapeType;  

    WHILE (@@FETCH_STATUS = 0) 
    BEGIN 

1 个答案:

答案 0 :(得分:0)

嵌套游标的示例:

DECLARE
        @crTables CURSOR,
        @crColumns CURSOR,
        @table_id INT,
        @table_name VARCHAR(100),
        @column_id INT,
        @column_name VARCHAR(100)

SET @crTables = CURSOR FAST_FORWARD FOR 
SELECT TOP 10 [object_id], NAME
FROM sys.tables t
ORDER BY t.[object_id] DESC

OPEN @crTables

FETCH NEXT FROM @crTables
INTO @table_id, @table_name

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @table_name + ': '

    SET @crColumns = CURSOR FAST_FORWARD FOR 
    SELECT TOP 10 c.column_id, c.name
    FROM sys.[columns] c
    WHERE c.[object_id] = @table_id
    ORDER BY c.column_id

    OPEN @crColumns

    FETCH NEXT FROM @crColumns
    INTO @column_id, @column_name

    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT @column_name

        FETCH NEXT FROM @crColumns
        INTO @column_id, @column_name
    END

    CLOSE @crColumns
    DEALLOCATE @crColumns

    PRINT ''

    FETCH NEXT FROM @crTables
    INTO @table_id, @table_name
END

CLOSE @crTables
DEALLOCATE @crTables

GO

其结果如下:

GO

DECLARE @txt VARCHAR(MAX)

SET @txt = 
STUFF(
    (
    SELECT TOP 10
        CHAR(13) + CHAR(10) + NAME
        + (
                SELECT TOP 10 CHAR(13) + CHAR(10) + c.name
                FROM sys.[columns] c
                WHERE c.[object_id] = t.[object_id]
                ORDER BY c.column_id
                FOR XML PATH(''), TYPE
            ).value('.', 'VARCHAR(MAX)')
        + CHAR(13) + CHAR(10)
    FROM sys.tables t
    ORDER BY t.[object_id] DESC
    FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)'), 1, 2, '')

PRINT @txt

尽量避免使用游标。