• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 480
  • Last Modified:

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

0
QPR
Asked:
QPR
1 Solution
 
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
 
QPRAuthor Commented:
Thought that may be the case - thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now