游标中的SQL动态架构名称

时间:2018-02-01 12:25:14

标签: sql sql-server

我想将Cursor与动态SchemaName一起使用。

在我的下面代码SELECT id FROM @schema_names.company行是我的问题。 @schema_names是动态架构名称。

如何在Cursor中使用动态架构/表名?

-- in-memory schema table to hold distinct schema_names
DECLARE @i int
DECLARE @numrows int
DECLARE @schema_names nvarchar(max)
DECLARE @schema_table TABLE (
    idx smallint Primary Key IDENTITY(1,1)
    , schema_names nvarchar(max)
)
DECLARE @company_id NVARCHAR(max) 

-- populate schema table
INSERT @schema_table
SELECT name FROM sys.schemas Where name <> 'dbo' AND name <> 'guest' AND name <> 'INFORMATION_SCHEMA' AND name <> 'db_accessadmin' AND name <> 'db_backupoperator' AND name <> 'db_datareader' AND name <> 'db_datawriter' AND name <> 'db_ddladmin' AND name <> 'db_denydatareader' AND name <> 'db_denydatawriter' AND name <> 'db_owner' AND name <> 'db_securityadmin' AND name <> 'sys'

select * from @schema_table
-- enumerate the table

SET @i = 1
SET @numrows = (SELECT COUNT(*) FROM @schema_table)
IF @numrows > 0
    WHILE (@i <= (SELECT MAX(idx) FROM @schema_table))
    BEGIN

        -- get the next record primary key
        SET @schema_names = (SELECT schema_names FROM @schema_table WHERE idx = @i)

        DECLARE my_cursor CURSOR local static read_only forward_only FOR 
          SELECT id FROM @schema_names.company 

        OPEN my_cursor 

        FETCH next FROM my_cursor INTO @company_id 

        WHILE @@FETCH_STATUS = 0 
          BEGIN 
              --Do something with Id here 
              PRINT @company_id + 'a' 
              FETCH next FROM my_cursor INTO @company_id 
          END 

        CLOSE my_cursor 
        DEALLOCATE my_cursor 

        BEGIN TRY
            DECLARE @sSQL nvarchar(500);            
            SELECT @sSQL = N'INSERT ['+@schema_names+'].[Menu] VALUES (9, N''Dashboard'', N''Charts'', N''/Dash/Chart'', 1)'
            EXEC sp_executesql @sSQL
        END TRY
        BEGIN CATCH
            SELECT ERROR_MESSAGE()+' '+@schema_names AS ErrorMessage;
        END CATCH

        -- increment counter for next record
        SET @i = @i + 1
    END

1 个答案:

答案 0 :(得分:2)

尝试这种方法

1 - 创建临时表

2 - 使用动态SQL

将表中的Id插入Temp表

3 - 从临时表中获取光标

CREATE TABLE #Temp
(
    Id INT
)

SET @schema_names =
(
    SELECT 
       schema_names
    FROM @schema_table
    WHERE idx = @i
)

TRUNCATE TABLE #temp

INSERT INTO #temp(Id)
EXEC('SELECT id FROM '+@schema_names+'.company;')

DECLARE my_cursor CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR 
SELECT ID FROM #TEMP

OPEN my_cursor;
FETCH NEXT FROM my_cursor INTO @company_id;