0

大家好,我的基本 sql 知识需要一些帮助

我希望能够用表中的值替换变量值并继续运行查询,直到达到表中的最终值

开始查询

DECLARE @prime_SCHEMA VARCHAR(20)
DECLARE @next_SCHEMA VARCHAR(20)
DECLARE @TABLE_name VARCHAR(100)
DECLARE @SQL VARCHAR(500)

SET @prime_SCHEMA = 'aaa'
SET @next_SCHEMA = 'bbb'
SET @TABLE = 'table1' 
SET @sql = 'select top 1 * into '+@next_SCHEMA +'.'+@TABLE_name +' from '+@prime_SCHEMA +'.'+@TABLE_name +' TRUNCATE TABLE '+@next_SCHEMA +'.'+@TABLE_name 
print @sql

我现在想将其包装在 Fetch 中并使用名为“table_val”的表来更新 TABLE_name 值并循环直到表中的所有行都已使用

如此有效,我最终可能会得到多个 @sql 语句

谢谢

4

1 回答 1

0

试试这个——

询问:

DECLARE 
      @prime_schema SYSNAME = 'aaa'
    , @next_schema SYSNAME = 'bbb'

DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = (
    SELECT CHAR(13) + '
        SELECT * 
        INTO [' + @next_schema + '].[' + o.name + ']
        FROM [' + s.name + '].[' + o.name + ']
        WHERE 1 != 1'
    FROM sys.objects o WITH (NOWAIT)
    JOIN sys.schemas s WITH (NOWAIT) ON o.[schema_id] = s.[schema_id]
    WHERE o.[type] = 'U'
        AND s.name = @prime_schema
        AND o.name IN ('table1', 'table2', 'table3')
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')

PRINT @SQL

输出:

SELECT * 
INTO [bbb].[table1]
FROM [aaa].[table1]
WHERE 1 != 1

SELECT * 
INTO [bbb].[table2]
FROM [aaa].[table2]
WHERE 1 != 1

SELECT * 
INTO [bbb].[table3]
FROM [aaa].[table3]
WHERE 1 != 1
于 2013-05-21T11:27:55.107 回答