Reputation: 747
I would like to create a simple stored procedure which take as a parameter existing tables.
I thought this procedure should work:
@UserID INT,
@TableName varchar(255)
AS
BEGIN
IF(@UserID is not null)
BEGIN
update t
set t.ProductID = 100
from dbo.[@TableName] t
END
When I execute this stored procedure with a table name, the query completed with errors:
Invalid object name 'dbo.@TableName'.
Any advice?
Upvotes: 1
Views: 283
Reputation: 70776
You'd have to do something like the following:
DECLARE @SQL NVARCHAR(100)
SET @SQL = 'UPDATE ' + @TABLENAME + ' SET t.ProductID = 100 '
EXEC sp_executesql @SQL
Note: You have no WHERE
clause so all items in the @TableName
will be updated.
Upvotes: 3