Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

dynamic table creation (table name as variable)

Status
Not open for further replies.

TerraSamba

Programmer
Aug 19, 2002
57
NL
I want to create and reference some tables dynamicly in a Stored Proc.

For instance

DECLARE @Tablename VARCHAR(50)
DECLARE @Count INT

WHILE @Count<5
BEGIN
SELECT *
INTO @Tablename + CAST(@COUNT AS VARCAHR(5))
FROM MyTable
WHERE MyCol1=100 + @Count

SET @Count=@Count+1
END

Is there a way to reference tables through their names with the use of a variable for their name?

I do not need work-arounds for this problem. I already solved that part, but I want to know if their is a way to refer to a table in SQL by means of a (string type) variable.

Thanx,

The gap between theory and practice is not as wide in theory as it is in practice.
 
You must use dynamic SQL to do this:

Code:
DECLARE @tbl varchar(20)
SET @tbl = 'table1'

EXEC('SELECT * FROM ' + @tbl)

--James
 
Create the stmt into a nvarchar variable and use the sp_executesql

Declare @stmt nvarchar(2500)

Set @stmt =
'SELECT * INTO' + @Tablename +
'CAST(@COUNT AS VARCAHR(5))
FROM MyTable
WHERE MyCol1=100 + ' + @Count

sp_executesql @stmt
 
Super thanx !


The gap between theory and practice is not as wide in theory as it is in practice.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top