0

I am trying to create a stored procedure in SQL Server 2008 which can insert data into any table (not table specific). I created one shown below, but during execution of the procedure an exception is thrown i.e.

Invalid object name 'dbo.@table'.

Stored procedure code:

CREATE PROCEDURE dbo.sp_InsertValues
   @table varchar(15)
   , @fields varchar(100)
   , @values varchar(100)   
AS
BEGIN
   INSERT INTO [dbo].[@table] (@fields) VALUES (@values)
END
GO

Remember I checked the parameters table, columns and values parameters are not null.

3
  • 3
    To do this, you are going to have to create dynamic sql out of the parameters you are passing in. Commented Oct 21, 2012 at 1:30
  • To flesh out Adam's comment, see Execute. Commented Oct 21, 2012 at 2:48
  • This technique is not good because it does not use parameterized SQL for no good reason. Please do not do it this way. Research, why parameterized SQL is important before deciding on this way of inserting data. Commented Oct 21, 2012 at 10:48

1 Answer 1

2

You will need to build the command using dynamic SQL and then execute it. Try this:

CREATE PROCEDURE dbo.sp_InsertValues
   @table nvarchar(15)
   , @fields nvarchar(100)
   , @values nvarchar(100)   
AS
BEGIN
    DECLARE @SQL NVARCHAR(MAX)
    SET @SQL = 'INSERT INTO [dbo].' + QUOTENAME(@table) + '(' + @fields +') VALUES (' +  @values + ')'
    EXEC(@SQL)
END
GO
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.