Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Can you use variables as table names in a stored procedure?

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2002-07-22 : 08:17:41
Ron writes "Can you use variables as table names in a stored procedure?

Here is a very simple example that shows what I want to do:
Declare @vchTable varChar(100)
select @vchTable = 'account'
select * from @vchTable


Although in my case @vchTable would be a parameter and I would being doing something else to the table. Here is an outtake of some of my ASP code. Notice the variable strTable. I would like to convert this to a stored procedure.

~~~~~~~ ASP code outtake ~~~~~~~~~
set rsTable = server.createObject("ADODB.recordSet")
set rsColumns = server.createObject("ADODB.recordSet")
rsTable.open "select id from sysobjects where name = '" _
& strTable & "'", objSLXConn, adOpenForwardOnly, adLockReadOnly
rsColumns.open "select Name from syscolumns where id = " & rsTable("id"), _
objSLXConn, adOpenForwardOnly, adLockReadOnly

Dim strColumns, arySLX, aryRaw
i = 0
while not rsColumns.EOF
if (i > 0) then
strColumns = strColumns & "," & rsColumns("name")
else
strColumns = rsColumns("name")
end if
i = (i + 1)
rsColumns.moveNext
wend
rsColumns.Close
set rsColumns = Nothing

arySLX = split(Application("SSGI_SLX"), "=")
aryRaw = split(Application("SSGI_SLX_Raw"), "=")
objConn.Execute "Insert into " & aryRaw(uBound(aryRaw)) _
& ".dbo." & strTable & "(" & strColumns & ") " _
& "Select " & strColumns & " from " & arySLX(uBound(arySLX)) _
& ".dbo." & strTable, i, adCmdText
~~~~~~~ ASP code outtake ~~~~~~~~~

I'm using SQL Server 2000 with Windows 2000 advanced server.

Thanks for any help,
Ron"

Nazim
A custom title

1408 Posts

Posted - 2002-07-22 : 08:39:56
You can do it thru Dynamic Sql. Read this article Merkin wrote http://www.sqlteam.com/item.asp?ItemID=4619 .

-------------------------
What lies behind you and what lies ahead of you are small matters compared to what lies within you.-Ralph Waldo Emerson
Go to Top of Page
   

- Advertisement -