使用数组中的值填充动态数组

时间:2014-06-12 12:16:39

标签: sql sql-server sql-server-2008

我必须在许多表上执行类似的查询。我想使用动态查询,而不是编写 n 数量几乎相似的类似查询。伪:

array = (
    'table_a' => 'value_a',
    'table_b' => 'value_b',
    'table_c' => 'value_c'
);

foreach (array as table => value)
    exec(
        'select ' + @value + ' into #' + @table + ' from ' + @table
    );
end

在SQL Server 2008 RE中是否可以这样?任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

您可以使用类似以下脚本的内容在SQL Server中执行此操作:

CREATE TABLE #temp (id INT IDENTITY(1,1), tablename VARCHAR(50))
INSERT INTO #temp
        ( tablename )
VALUES  ( 'table_a' ),('table_b'),('table_c')

DECLARE @sql NVARCHAR(MAX)
DECLARE @tblcount INT, @i INT = 1
SELECT @tblcount = MAX(id) FROM #temp

WHILE @i <= @tblcount
    BEGIN
        SELECT @sql = 'SELECT t.somefield, t.otherfield as ' + tablename + ' INTO #some_temptable_' + tablename + ' FROM #mytable t where SomeField like ''1''' FROM #temp WHERE id = @i
        EXEC sp_executesql @sql
        --SELECT @sql
        SELECT @i = @i + 1
    END

DROP TABLE #temp