1
votes

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?

1
you can't do query a dynamic table name like that. Would need to use dynamic TSQL - Mitch Wheat
Canonical reading on this; sommarskog.se/dynamic_sql.html - Alex K.

1 Answers

3
votes

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.