what I am trying to do is run a query multiple times over multiple tables, so what I have here is a table of the table names that cycles through setting @tablename to the name of the table on each iteration that I want to run the query on.
As you can see below @tablename is the name of the table I want to run the queries on but how do i run these queries using @tablename as the table name?
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]
note: this is only part of the queries that I want run, I just want to figure out how to subsitute the variable in the query as the table name. Also I know this isnt good form but there is a reason I need to do it this way.
updated working code here:
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
Use the Exec command. Write your query in a variable like and execute it
You just have to be carefull. I see that you are using into statements. You will have to check that the table does not already exist because you will get an exception. You will need to drop the tables, or a better way would be to do this before you start your loop:
Create all the tables, and when you start your While loop add a
Hope it helps