如何使用Dynamic Sql

时间:2016-08-26 21:31:53

标签: sql sql-server loops dynamic-sql

我有一个表数据库,我希望在3个不同的模式中迭代每个表,一次一个模式。

我认为我需要的是:

DECLARE @tableName varchar(50)

DECLARE @schemaName varchar(50)

现在我们可以调用模式" A" " B"和" C"。

我可以使用以下方法获取每个模式的表列表:

SELECT t.name 
  FROM sys.tables AS t
  INNER JOIN sys.schemas AS s
  ON t.[schema_id] = s.[schema_id]
  WHERE s.name = N'schema_name';

但我不知道如何遍历该列表(id喜欢逐个将值插入到每个表中,并且它们依赖于表的列的数据类型,所以我不能只对所有表进行全面插入声明)。

1 个答案:

答案 0 :(得分:3)

DECLARE @SchemaName SYSNAME = 'dbo'

DECLARE @TableName SYSNAME
--note sysname is the same thing as NVARCHAR()

DECLARE CursorName CURSOR FOR
SELECT t.name 
  FROM sys.tables AS t
  INNER JOIN sys.schemas AS s
  ON t.[schema_id] = s.[schema_id]
  WHERE s.name = @SchemaName;

OPEN CursorName

FETCH NEXT FROM CursorName
INTO @TableName

    WHILE @@FETCH_STATUS = 0
    BEGIN

       DECLARE @Columns NVARCHAR(MAX)
       SET @Columns = 
       STUFF(
          (SELECT
             ',' + QUOTENAME(name)
          FROM
             sys.columns
          WHERE
             object_id = OBJECT_ID(QUOTENAME(@SchemaName) + '.' + QUOTENAME(@TableName))
          FOR XML PATH(''))
          ,1,1,'')

        DECLARE @SQL AS NVARCHAR(MAX)
        SET @SQL = 'INSERT INTO ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@TableName) + 
                    ' (' + @Columns + ') VALUES (' + 
                    'YOU MAKE REST DEPENDING ON YOUR NEEDS'

        --use print to view and copy your dynamic sql string to see if you have formed it correctly
        PRINT @SQL
        --EXECUTE (@SQL)

        FETCH NEXT FROM CursorName
        INTO @TableName
    END

CLOSE CursorName
DEALLOCATE CursorName