INSERT INTO @table

I have an SP that logs some actions. I want to change the SP so I can use it to write to one of 3 tables so have added an input parameter @table
Within the SP is... INSERT INTO @table
I keep getting the error: Must declare the variable '@table'.
It is declared. Do I have to create a sql string and then execute that in order to make this work?
CREATE PROCEDURE dbo.WriteLog
	@table varchar(50),
	@Task varchar(50),
	@Description varchar(255),
	@Type int = 0
AS
SET NOCOUNT ON
 
INSERT INTO @table VALUES 
	(@Type, @Task, Getdate(), @Description)
GO

Open in new window

LVL 29
QPRAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

BrandonGalderisiCommented:
Two things:

You can insert a function using the values clause.  You have to use select.

@Table is a varchar datatype and not a table datatype.  You cannot have table variables as input/output parameters to procedures.


0
Guy Hengel [angelIII / a3]Billing EngineerCommented:
you cannot do directly like that, but would need dynamic sql:
CREATE PROCEDURE dbo.WriteLog
      @table varchar(50),
      @Task varchar(50),
      @Description varchar(255),
      @Type int = 0
AS
SET NOCOUNT ON
DECLARE @sql NVARCHAR(1000)
SET @sql = 'INSERT INTO [' + @table + '] VALUES 
      (@Type, @Task, Getdate(), @Description)'
EXEC sp_executesql @sql, N'@type int, @task varchar(50), @description varchar(255)', @type, @task, @description 
GO

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
QPRAuthor Commented:
Thought that may be the case - thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.