使用变量名称在多个表上运行查询

时间:2012-03-13 05:32:32

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

我要做的是在多个表上多次运行查询,所以我这里有一个表名表,循环通过将@tablename设置为每次迭代时表的名称我想在。上运行查询。

如下所示,@tablename是我要运行查询的表的名称,但如何使用@tablename作为表名运行这些查询?

CREATE TABLE [BusinessListings].[dbo].[temptablenames]
(id int,
name nvarchar(50),
)

INSERT INTO [BusinessListings].[dbo].[temptablenames] (id, name)
VALUES 
(1,'MongoOrganisationsACT1'),
(2,'MongoOrganisationsNSW1'),
(3,'MongoOrganisationsNT1'),
(4,'MongoOrganisationsQLD1'),
(5,'MongoOrganisationsSA1'),
(6,'MongoOrganisationsTAS1'),
(7,'MongoOrganisationsVIC1'),
(8,'MongoOrganisationsWA1');

DECLARE @tablename sysname,
@id int
SET @id = 1
WHILE (@id < 9)
BEGIN
select @tablename = name from temptablenames where id = @id

select @tablename


        select _key_out, sum(quality_score) as sumscore, count(*) as reccount, (sum(quality_score) / count(*)) as ave
        into tempga0
        from @tablename
        group by _key_out

        select _key_out, count(*) as reccount
        into tempga3
        from @tablename
        where dedupe_result is null
        group by _key_out
        having count(*)>1

        select a._key_out, max(quality_score) as maxdedupetotalscore
        into tempga4
        from
        @tablename a
        join
        tempga3 b
        on a._key_out = B._key_out
        --where isdeleted is null
        group by a._key_out

        --- keep records
        update @tablename
        set dedupe_result = 'Keep'
        from 
        @tablename a
        join
        tempga4 b
        on a._key_out = B._key_out  
        where a.quality_score = b.maxdedupetotalscore
        --and isdeleted is null
        and dedupe_result is null

SET @id = @id + 1 
END
GO

DROP TABLE [BusinessListings].[dbo].[temptablenames]

注意:这只是我想要运行的查询的一部分,我只是想弄清楚如何将查询中的变量替换为表名。我也知道这不是好形式,但我有理由这样做。

在此处更新了工作代码:

DECLARE @tablename nvarchar(30),
@id int,
@SQLStr nvarchar(1000)
SET @id = 1
WHILE (@id < 9)
BEGIN
select @tablename = name from temptablenames where id = @id

IF OBJECT_ID('tempga0') IS NOT NULL
DROP TABLE tempga0

    set @SQLStr = 'select _key_out, sum(quality_score) as sumscore, count(*) as reccount, (sum(quality_score) / count(*)) as ave
into tempga0
from ' + @tablename + ' group by _key_out'

    exec(@SQLStr)


 SET @id = @id + 1 
END
GO

1 个答案:

答案 0 :(得分:1)

使用Exec命令。将您的查询写在变量中并执行它

Declare @SQLStr = 'Select * into X from ' + @tablename
exec(@SQLStr)

你必须要小心。我看到你正在使用语句。您将不得不检查该表是否已存在,因为您将获得异常。您将需要删除表,或者在开始循环之前更好的方法是执行此操作:

CREATE TABLE tempga0 (
_key_out int,
sumscore numeric(18,9),
reccount int,
ave numeric(18,9))

--rest of the tables to be created here...

创建所有表格,当您启动While循环时添加

WHILE (@id < 9)         
BEGIN    
    TRUNCATE TABLE tempga0
    --truncate the rest of the tables

    --Do the rest of your stuff here
END

希望有所帮助