Sql - 获取下一个值以替换变量值

时间:2013-05-21 11:24:39

标签: sql sql-server sql-function

大家好,我的基本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语句

谢谢

1 个答案:

答案 0 :(得分: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