SQL Server : drop constraint if exists - sql

I have been struggling with this for about 2 hours now. I am trying to create a column to tables using a stored procedure. That said, I must check if that column exists, and if it does I must drop it.
The Issue is that I am not able to drop the constraint, I am getting an error:
invalid column name 'RowNumber'
Code:
DECLARE #tableName NVARCHAR(30)
DECLARE #newColumnName NVARCHAR(100)
DECLARE #newDefaultValue NVARCHAR(100)
DECLARE #newColumnType NVARCHAR(100)
DECLARE #constraintName NVARCHAR (30)
SET #tableName='TestTable'
SET #newDefaultValue = 'James'
SET #newColumnType ='NVARCHAR(100)'
SET #newColumnName = 'James'
CREATE TABLE #cons (constraintName NVARCHAR(100), RowNumber int)
INSERT INTO #cons(constraintName, RowNumber)
SELECT
t.*
FROM
(SELECT
name,
ROW_NUMBER() OVER(ORDER BY name) AS RowNumber
FROM
sys.objects
WHERE
type_desc LIKE '%CONSTRAINT'
AND name like '%JAMES%'
AND name like '%JAMES%') AS t
SELECT * FROM #cons
IF EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '[dbo].[TestTable]'
AND COLUMN_NAME = 'James')
BEGIN
DECLARE #i int
DECLARE #numberOfRows int
SET #i = 1
SET #numberOfRows = (SELECT COUNT(*) FROM #cons)
WHILE(#i <= #numberOfRows)
BEGIN
SET #constraintName = (SELECT constraintName
FROM #cons
WHERE RowNumber = #i)
DECLARE #dropStatement NVARCHAR(500)
SET #dropStatement = 'ALTER TABLE [dbo].[TestTable] DROP CONSTRAINT ' + #constraintName
EXEC(#dropStatement)
SET #i = #i + 1
END
ALTER TABLE [dbo].[TestTable]
DROP COLUMN [James]
END
--ALTER TABLE [dbo].[TestTable] ADD James NVARCHAR(50)
DROP TABLE #cons
How can I get this to drop the column?

ALTER TABLE
DROP CONSTRAINT #constraintname
Before the drop colum

Related

Declare a variable based on name in sys.tables then delete the table based on that variable in dynamic SQL

So what I expect is for the first piece of code to find the table name then if that table name exists and is more than 3 days old drop that table.
My issue with this code is that the code is not replacing #temp_name with the actual table DrinkSales. So the variable is not being correctly set in the select statement.
Current Code:
declare #table varchar(100) = 'DrinkSales'
DECLARE #temp_name VARCHAR(100)
declare #drop varchar(max) = '
DECLARE #temp_name VARCHAR(100)
select #temp_name= name
FROM sys.objects
WHERE DATEDIFF(day, create_date, getdate()) > 3
and name = '''+#table+'''
select #temp_name
--if object_id(''dbo.'+#table+''', ''U'') is not null -- needs to be changed to detect if variable is null rather than table.
--drop table dbo.'+#table+'
'
print(#drop)
exec(#drop)
So the result should be:
DECLARE #temp_name VARCHAR(100)
select #temp_name= name
FROM sys.objects
WHERE DATEDIFF(day, create_date, getdate()) > 3
and name = 'DrinkSales'
select #temp_name
--if object_id('dbo.DrinkSales', 'U') is not null -- this should be changed to
--drop table dbo.DrinkSales
*if #temp_name is not null *
*drop dbo.drinksales*
(1 row affected)
I think you were over-quoting - a common problem in dynamic SQL.
You can (and should) minimise the dynamic SQL required as follows:
declare #schema varchar(100) = 'dbo', #table varchar(100) = 'Proposal', #temp_name varchar(100);
if exists (
select 1
from sys.objects
where datediff(day, create_date, getdate()) > 3
and [name] = #table
and [schema_id] = schema_id(#schema)
)
begin
declare #drop varchar(max) = 'drop table ' + quotename(#schema) + '.' + quotename(#table) + ';';
print(#drop)
--exec(#drop)
end;
Its important to use quotename to protect against SQL injection.
Note also the addition of the schema as suggested by #David Browne.

Equivalent set base query for the cursor

I have a stored procedure which uses cursor. I want to know any equivalent set base query for the cursor.
USE [T04_676]
GO
/****** Object: StoredProcedure [dbo].[proc_InsertAssessmentCast] Script Date: 3/16/2016 7:43:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Capgemini>
-- Create date: <12-Mar-2016>
-- Description: <This Stored procedure is used to create table 'assessment_cast' and fill data into it>
-- exec proc_InsertAssessmentCast
-- =============================================
CREATE PROCEDURE [dbo].[proc_InsertAssessmentCast]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #tmpTableNames TABLE
(
TableName varchar(250),
PatientID_ITM_ID INT,
date_ITM_ID INT,
KVSTableType INT,
Association_ITM_ID INT
)
DECLARE #tmpAssociatedColumn_ITM_ID TABLE
(
InitialTableMasterID INT
)
DECLARE #AssociatedColumn_ITM_ID INT
DECLARE #AssociatedColumn_ITM_ID_List VARCHAR(400)
DECLARE #TableName varchar(250)
DECLARE #PatientID_ITM_ID INT
DECLARE #date_ITM_ID INT
DECLARE #KVSTableType INT
DECLARE #Association_ITM_ID INT
DECLARE #SameRowID INT
DECLARE #T04PKID INT
DECLARE #T04CMID INT
DECLARE #T04Value VARCHAR(250)
DECLARE #sqlT04Value nvarchar(MAX)
DECLARE #tmpValue TABLE
(
Value varchar(250)
)
CREATE TABLE #tmpAssessmentRows
(
PrimaryKeyTableID INT,
ColumnID INT,
Value varchar(250)
)
DECLARE #sqlSameRowID NVARCHAR(250),#sqlT04_Value_Query NVARCHAR(MAX)
DECLARE #ColWithAliasTbl TABLE (colID int,colName varchar(50) )
DECLARE #PivotTBL VARCHAR(MAX)=''
DECLARE #ColID VARCHAR(MAX)
DECLARE #ChkPtntID VARCHAR(MAX)
DECLARE #ColName VARCHAR(MAX)
DECLARE #AllColID VARCHAR(MAX) = ''
DECLARE #AllColName VARCHAR(MAX) = ''
BEGIN TRY
IF EXISTS (SELECT name FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tmpAssesessment_Cast]') AND type in (N'U'))
BEGIN
DROP TABLE tmpAssesessment_Cast
END
IF EXISTS (SELECT name FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[assessment_cast]') AND type in (N'U'))
BEGIN
DROP TABLE assessment_cast
END
IF NOT EXISTS (SELECT name FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[InitialOriginalDataKVS]') AND name = N'ix_InitialOriginalDataKVS_SameRowID')
CREATE NONCLUSTERED INDEX [ix_InitialOriginalDataKVS_SameRowID] ON [dbo].[InitialOriginalDataKVS]
(
[InitialTableMasterID] ASC
)
INCLUDE ( [SameRowID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
--Insert Table names of tables having both columns: patientID and date
INSERT INTO #tmpTableNames
SELECT ITM1.TableName,ITM1.InitialTableMasterID,ITM2.InitialTableMasterID,ITM1.KVSTableType,0 AS Association_ITM_ID
FROM InitialTableMaster ITM1
INNER JOIN InitialTableMaster ITM2 ON ITM1.TableName=ITM2.TableName
WHERE ITM1.ColumnName ='patientID' AND ITM2.ColumnName ='date'
--Set Association for the column in table
UPDATE #tmpTableNames
SET Association_ITM_ID=Association
FROM InitialTableMaster ITM
INNER JOIN #tmpTableNames tmpTableNames ON tmpTableNames.TableName=ITM.TableName
WHERE Association <> 0 AND tmpTableNames.KVSTableType=1
--Do not consider tables with KVSTableType=1 having no Association
DELETE FROM #tmpTableNames
WHERE KVSTableType=1 AND Association_ITM_ID=0
SELECT TOP 1
#PatientID_ITM_ID=PatientID_ITM_ID,
#date_ITM_ID=date_ITM_ID,
#Association_ITM_ID=Association_ITM_ID
FROM #tmpTableNames
----Logic to get the associated columns ID values in list
INSERT INTO #tmpAssociatedColumn_ITM_ID
SELECT InitialTableMasterID
FROM InitialTableMaster
WHERE Association=#Association_ITM_ID and InitialTableMasterID <>#Association_ITM_ID
WHILE ((SELECT COUNT(1) FROM #tmpAssociatedColumn_ITM_ID)>0)
BEGIN
SELECT TOP 1 #AssociatedColumn_ITM_ID=InitialTableMasterID
FROM #tmpAssociatedColumn_ITM_ID
SET #AssociatedColumn_ITM_ID_List= ISNULL(#AssociatedColumn_ITM_ID_List,'') + '['+ CONVERT(NVARCHAR,#AssociatedColumn_ITM_ID) + '],'
DELETE FROM #tmpAssociatedColumn_ITM_ID
WHERE InitialTableMasterID=#AssociatedColumn_ITM_ID
END
SET #AssociatedColumn_ITM_ID_List=SUBSTRING(#AssociatedColumn_ITM_ID_List,0,LEN(#AssociatedColumn_ITM_ID_List))
print '1'
print #AssociatedColumn_ITM_ID_List
SET #sqlT04Value='
SELECT COALESCE('+ #AssociatedColumn_ITM_ID_List + ') as ''Value''
FROM [InitialOriginalDataKVS]
PIVOT(max(Value)
FOR InitialTableMasterID IN ('+ #AssociatedColumn_ITM_ID_List +')) AS PVTTable
WHERE SameRowID = '
--DECLARE GetSameRowIDs CURSOR STATIC LOCAL FOR
DECLARE GetSameRowIDs CURSOR FORWARD_ONLY READ_ONLY FAST_FORWARD FOR
SELECT sameRowID FROM InitialOriginalDataKVS
WHERE InitialTableMasterID=#PatientID_ITM_ID AND NewFlag=1
GROUP BY sameRowID
OPEN GetSameRowIDs
FETCH NEXT FROM GetSameRowIDs
INTO #SameRowID
WHILE (##FETCH_STATUS = 0) -- Inner cursor loop
BEGIN
SET #T04PKID=0
SELECT #T04PKID=PrimaryKeyTableID
FROM dbo.PrimaryKeyForPredicting
WHERE PatientID IN (SELECT value FROM dbo.InitialOriginalDataKVS
WHERE SameRowID=#SameRowID AND InitialTableMasterID=#PatientID_ITM_ID)
AND [date] IN (SELECT value FROM dbo.InitialOriginalDataKVS
WHERE SameRowID=#SameRowID AND InitialTableMasterID=#date_ITM_ID)
--Process only if the combination of patientID and date exists in 'PrimaryKeyForPredicting'
IF(ISNULL(#T04PKID,0)<> 0)
BEGIN
DELETE FROM #tmpValue
SET #T04Value=NULL
SET #sqlSameRowID=CONVERT(VARCHAR(50),#SameRowID)
SET #sqlT04_Value_Query=#sqlT04Value+#sqlSameRowID
INSERT INTO #tmpValue
EXEC sp_executesql #sqlT04_Value_Query
IF((SELECT COUNT(1) FROM #tmpValue)>0)
BEGIN
SELECT #T04Value=Value FROM #tmpValue
END
SELECT #T04CMID = ColumnID
FROM [dbo].[PrimaryKeyForModeling]
WHERE ColumnName IN (SELECT value FROM [InitialOriginalDataKVS]
WHERE SameRowID=#SameRowID AND InitialTableMasterID=#Association_ITM_ID)
IF(ISNULL(#T04CMID,0)<> 0)
BEGIN
INSERT INTO #tmpAssessmentRows
(PrimaryKeyTableID,ColumnID,Value)
VALUES(#T04PKID,#T04CMID,#T04Value)
END
END
FETCH NEXT FROM GetSameRowIDs
INTO #SameRowID
END
CLOSE GetSameRowIDs
DEALLOCATE GetSameRowIDs
SELECT PKP.PatientID,PKP.[Date],ColumnID,Value into tmpAssesessment_Cast
FROM #tmpAssessmentRows AR
INNER JOIN dbo.PrimaryKeyForPredicting PKP ON AR.PrimaryKeyTableID=PKP.PrimaryKeyTableID
order by PKP.PrimaryKeyTableID
-----------------------------
--Logic for assesment_cast table creation from the data in rows
------------------------------
INSERT INTO #ColWithAliasTbl
SELECT ColumnID,[ColumnName]
FROM [dbo].[PrimaryKeyForModeling]
WHERE ColumnID IN (SELECT Distinct ColumnID FROM tmpAssesessment_Cast)
While EXISTS (SELECT colID,colName FROM #ColWithAliasTbl)
Begin
SELECT #ColID='['+CONVERT(VARCHAR,min(colID))+'],' FROM #ColWithAliasTbl
SELECT #ColName='['+CONVERT(VARCHAR,colID)+'] AS '''+ colName+''',' FROM #ColWithAliasTbl WHERE colID = (SELECT min(colID) FROM #ColWithAliasTbl)
SET #AllColID = #AllColID+#ColID
SET #AllColName = #AllColName+#ColName
DELETE from #ColWithAliasTbl Where colID = (SELECT min(colID) FROM #ColWithAliasTbl)
End
print #AllColID
print LEN(#AllColID)
SET #AllColID = SUBSTRING(#AllColID, 1, LEN(#AllColID)-1)
print '2'
SET #AllColName = SUBSTRING(#AllColName, 1, LEN(#AllColName)-1)
print '3'
SET #PivotTBL = 'SELECT patientID, [date], '+#AllColName +
' into assessment_cast FROM (SELECT * FROM [dbo].[tmpAssesessment_Cast]) KVS
PIVOT (Max(Value) FOR [ColumnID] IN ('+#AllColID+') ) pvt order by 1'
EXEC(#PivotTBL)
--Drop temporary table
IF OBJECT_ID('dbo.tmpAssesessment_Cast', 'U') IS NOT NULL
DROP TABLE dbo.tmpAssesessment_Cast;
DROP TABLE #tmpAssessmentRows
--Return the assessment_cast table data
SELECT * FROM assessment_cast
END TRY
BEGIN CATCH
-- Raise an error with the details of the exception
DECLARE #ErrMsg nvarchar(4000), #ErrSeverity INT,#ErrorState INT
SELECT #ErrSeverity=ERROR_SEVERITY(),
#ErrMsg= ERROR_MESSAGE(),
#ErrorState=ERROR_STATE();
RAISERROR(#ErrMsg, #ErrSeverity, #ErrorState)
EXEC sp_addmessage 50005,#ErrSeverity,#ErrMsg,'us_english', 'with_log'
END CATCH
END
GO

Conditional clause to DROP Table

I was trying to write a sql procedure to drop table who have a certain pattern in their names.
Something like the below code :
DECLARE #temp TABLE
(
ID bigint IDENTITY(1,1),
tabname sysname NOT NULL
)
INSERT INTO #temp
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE '%:%'
DECLARE #ProcessedID bigint = 0
DECLARE #tablename sysname
SELECT #ProcessedID = ID, #tablename = tabname FROM #temp WHERE ID > #ProcessedID ORDER BY ID DESC
WHILE(#ProcessedID IS NOT NULL)
BEGIN
DROP TABLE dbo.[#tablename]
SELECT #ProcessedID = ID, #tablename = tabname FROM #temp WHERE ID > #ProcessedID ORDER BY ID DESC
END
But #tablename is not replaced with the right table name. Can any one point me in the right direction.
You need to do it dynamically when you want to use a variable name as an argument, so you need to wrap it in a string and execute that string and then do some small changes to the WHILE condition to fit.
I'd properly do something like this:
DECLARE #temp TABLE
(
ID bigint IDENTITY(1,1),
tabname sysname NOT NULL
):
INSERT INTO #temp
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE '%:%';
DECLARE #tablename VARCHAR(255);
DECLARE #Count INT = ISNULL((SELECT COUNT(*) FROM #temp AS t), 0);
WHILE(#Count > 0)
BEGIN
SELECT #tablename = tabname FROM #temp AS t; --if the order of drop is not significant
EXEC('DROP TABLE dbo.[' + #tablename+ ']');
DELETE FROM #temp WHERE tabname = #tablename;
SET #Count = ISNULL((SELECT COUNT(*) FROM #temp AS t), 0);
END

retrieving all Foreign Keys and their records

What I'm trying to achieve is the following.
When I delete a record I want to check if there are any FK relationships and it needs to be recursive. That way I can display a list of all records that are related to the one you want to delete.
So a small example of nested links
project 1 -> phase 1 -> block 1 -> ..
So when I try to delete project 1 I need to get a list of the items you need to delete first:
phase 1
block 1
....
I wanted to do this with a stored procedure that takes an ID and a tablename (format [chema].[tablename]) and finds all these linked records.
The problem I'm having is with the recursive part.
Here's my code so far:
ALTER PROCEDURE core.usp_CanBeDeleted
#entityId int,
#entityName nvarchar(250)
AS
BEGIN
DECLARE #NumberRecords int, #RowCount int
DECLARE #childId int
DECLARE #query nvarchar(max)
DECLARE #eName nvarchar(250) , #keyName nvarchar(250)
DECLARE #columnName nvarchar(250)
DECLARE #keys TABLE(
RowID int IDENTITY(1, 1),
name nvarchar(250),
entityName nvarchar(250),
columnName nvarchar(250)
)
if not exists (select * from sysobjects where name='partialResults' and xtype='U')
BEGIN
CREATE TABLE partialResults(
RowID int IDENTITY(1, 1),
id int,
parentId int,
name nvarchar(250),
FK_name nvarchar(250)
)
END
DECLARE #recusiveResults TABLE(
RowID int,
id int,
parentId int,
name nvarchar(250),
FK_name nvarchar(250)
)
DECLARE #results TABLE(
RowID int,
id int,
parentId int,
name nvarchar(250),
FK_name nvarchar(250)
)
SET #RowCount = 1
-- get all FK's of the entity
INSERT INTO #keys
SELECT name, '[' + OBJECT_SCHEMA_NAME(parent_object_id) + '].[' + OBJECT_NAME(parent_object_id)+ ']',cu.column_name
from sys.foreign_keys k
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
ON k.name = CU.CONSTRAINT_NAME
where k.referenced_object_id = OBJECT_ID(#entityName)
-- set variable to number of records in temp table
SET #NumberRecords = ##ROWCOUNT
-- loop through the FK's an get all linked entities
WHILE(#RowCount <= #NumberRecords)
BEGIN
SELECT #keyName = name, #eName = entityName, #columnName = columnName
FROM #keys
WHERE RowId = #RowCount
-- get all FK information
SET #query = 'INSERT INTO partialResults(FK_name, name, id, parentId)'
+ ' SELECT ''' + #keyName + ''','''+ #eName + ''',' + 'id,' + cast(#entityId as varchar(25)) + ' as parentid'
+ ' FROM ' +#eName
+ ' WHERE id in '
+ ' (SELECT ' + #columnName
+ ' FROM ' + #entityName
+ ' WHERE id = ' + cast(#entityId as varchar(25))
+ ' )'
--print #query
EXEC (#query)
SET #RowCount = #RowCount + 1
END
-- rest number of records
SET #RowCount = 1
SELECT #NumberRecords = count(id)
FROM partialResults
-- save partialResults
INSERT INTO #results--(FK_name, name, id, parentId)
SELECT *--FK_name, name, id, parentId
FROM partialResults
DELETE FROM partialResults
WHILE(#RowCount <= #NumberRecords)
BEGIN
-- select next row
SELECT #childId = id, #eName = name
FROM #results
WHERE RowId = #RowCount
INSERT INTO #recusiveResults
EXEC core.usp_CanBeDeleted #childId, #eName
SET #RowCount = #RowCount + 1
END
INSERT INTO #results
SELECT *
FROM #recusiveResults
if exists (select * from sysobjects where name='partialResults' and xtype='U')
BEGIN
-- remove temp tables
DROP TABLE partialResults
END
-- return results
SELECT *
FROM #results
END
GO
the problem lies here:
INSERT INTO #recusiveResults
EXEC core.usp_CanBeDeleted #childId, #eName
Apparantly you can't nest an insert exec.
however I don't really see any other way to do it.
I've tried converting it into a function but then there are other problems like the dynamic query.
Any help would be greatly apreciated.
Split the procedure into an outer and an inner procedure.
In the outer procedure create a #results temp-table and then call the inner procedure.
In the inner procedure put all the logic including the recursion, but instead of selecting out the result at the end insert the result into the already existing #results table.
That way you safe a lot of time because you dont have to move data around as much. You also don't have to nest INSERT...EXEC anymore.
You also don't need the dbo.PartialResults table anymore as you can write directly into the #results table within the dynamic statement. If you still need it, to make the recursion work replace it with a #partialResults temp table that you create in the inner procedure (DON'T check for existence, just create the new one. See http://sqlity.net/en/1109/temp-tables-scoping-eclipsing/ for an explanation of temp table scoping). That way each execution is creating its own temp table and you don't have to deal with the clean-up. This is also a little less heavy compared to using a real table.
Finally, all the table variables can go too.
At the end of the inner procedure you can then do a simple SELECT * FROM #results; to output all the collected results.

Using variable name to run query on multiple tables

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
Declare #SQLStr = 'Select * into X from ' + #tablename
exec(#SQLStr)
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 TABLE tempga0 (
_key_out int,
sumscore numeric(18,9),
reccount int,
ave numeric(18,9))
--rest of the tables to be created here...
Create all the tables, and when you start your While loop add a
WHILE (#id < 9)
BEGIN
TRUNCATE TABLE tempga0
--truncate the rest of the tables
--Do the rest of your stuff here
END
Hope it helps