Friday, March 30, 2012

How to insert on table with a variable name

Here is the jist of what I want to do, but I know the syntax is wrong...please help

CREATE PROCEDURE mySP
(
@.tablename As varChar(50),
@.input_name As varChar(100)
)
As
INSERT @.tablename (name)
VALUES (@.input_name)

assume the table exists already, and has a 'name' field in it.

thanks guysKatie,

I can't see why you would want to do that. However, the exact code would be:

exec ('INSERT INTO ' + @.tableName + ' VALUES (' + @.input_name + ')')

Be aware that

a) You really should avoid using 'exec' where possible since 'exec' will hinder Sql Server in pre-compiling the Stored Procedure
b) You really want to use a column-list with insert.

regards,

Kristof|||Originally posted by beyond cool
Katie,

I can't see why you would want to do that. However, the exact code would be:

exec ('INSERT INTO ' + @.tableName + ' VALUES (' + @.input_name + ')')

Be aware that

a) You really should avoid using 'exec' where possible since 'exec' will hinder Sql Server in pre-compiling the Stored Procedure
b) You really want to use a column-list with insert.

regards,

Kristof

is there a way around using 'exec'?|||Originally posted by beyond cool
Katie,

I can't see why you would want to do that. However, the exact code would be:

exec ('INSERT INTO ' + @.tableName + ' VALUES (' + @.input_name + ')')

Be aware that

a) You really should avoid using 'exec' where possible since 'exec' will hinder Sql Server in pre-compiling the Stored Procedure
b) You really want to use a column-list with insert.

regards,

Kristof

Yea, I just know basics of stored procedures, I'd love to hear how this sort of thing is usually done.

No comments:

Post a Comment