[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 455
  • 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

Featured Post

Veeam and MySQL: How to Perform Backup & Recovery

MySQL and the MariaDB variant are among the most used databases in Linux environments, and many critical applications support their data on them. Watch this recorded webinar to find out how Veeam Backup & Replication allows you to get consistent backups of MySQL databases.

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