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

Passing TableName as parameter in SP 1

Status
Not open for further replies.

5679

Programmer
Feb 14, 2003
32
AU
I want to pass a a table name as parameter in a stored procedure to allow it to chioose its table, but it doesnt work. i`ve tried the following:-

CREATE PROCEDURE testTables
@tableName varchar (50),
@name_New varchar(50)
AS
INSERT INTO [@tableName]
VALUES
(@name_New)

testTables 'TESTING','myName'

'TESTING' is the table name and 'myName' is a value to be inserted in the table TESTING
 
You have to use the
EXEC
command and pass it a string like
EXEC 'INSERT INTO ' + @tablename + ' VALUES (' + @name_New +')'



Hope I've been helpful,
Wayne Francis

If you want to get the best response to a question, please check out FAQ222-2244 first
 
my stored procedure is:-

CREATE PROCEDURE testTables
@tableName sysname,
@name_New varchar(50)
AS
EXEC ('INSERT INTO ' + @tablename + '(name) VALUES (' + @name_New +')')

But, when i execute it as follows:-
testTables 'TESTING','myName'

I get the following error:-
server: Msg 128, Level 15, State 1, Line 1
The name 'SDFDFS' is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted.

any hints?
 
I copied this from another post a few weeks ago. It works ASIS on my users table. Maybe you can tweak it.

DECLARE @tablename SYSNAME
declare @SQLCommand VarChar(200)
SET @tablename = 'users'
SET @SQLCommand = 'SELECT * FROM ' + @tablename
print @sqlcommand
EXEC (@SQLCommand)

 
I just copied the code but in looking it up it looks like:

sysname is a system-supplied user-defined
data type that is functionally equivalent to nvarchar(128)
 
try running this
executing this SP in QA and see the output

Code:
CREATE PROCEDURE testTables
    @tableName sysname,
    @name_New varchar(50)
AS
PRINT 'INSERT INTO ' + @tablename + '(name) VALUES (' + @name_New +')'

What I'll expect you'll find is that your statement looks like

Code:
INSERT INTO blah (name) VALUES (yadda)

You are not surrounding the @name_New variable in the concatinated string in single quotes.

Should look like this
Code:
'INSERT INTO ' + @tablename + '(name) VALUES (''' + @name_New +''')'


Hope I've been helpful,
Wayne Francis

If you want to get the best response to a question, please check out FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top