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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing table name in to procedure as a variable

Status
Not open for further replies.

DaveJunior

Programmer
Jan 7, 2003
11
GB
Hi, I am a quite new at SQL and wondered if someone could give me a hand...

I am trying to pass the table name that I am searching through into a stored procedure as a variable however it gives me the error message: "The variable name '@TheTable' has already been declared. Variable names must be unique within a query batch or stored procedure." Any ideas? The code I am using is:

Code:
CREATE PROC Forum__CheckNoOfReplies @TheTable varchar(100), @TheID int(4) As
	SELECT AllowedReplies
	FROM @TheTable
	WHERE ID = @TheID
GO

I am calling it like:

Code:
EXEC CheckNoOfReplies 'Forum_Classfieds', '54'

Any help would be great, cheers.
 
Why do you need to send the table as a variable name? Do you have multiple tables with the same structure?

It can be done with dynamic Tsql

CREATE PROC Forum__CheckNoOfReplies (
@TheTable varchar(100), @TheID int(4))
As
exec('SELECT AllowedReplies
FROM ' + @TheTable +
' WHERE ID = ' + cast(@TheID as varchar(12)))


If you have this need it is often an indication that your database design is a bit off.
 
I suppose it highly depends on your platform. In Oracle you may use EXECUTE IMMEDIATE for single-row query or REF CURSORs for multiple rows. Though I'm sure that any dynamic sql is not the matter of ANSI. Regards, Dima
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top