You can use a table variable with dynamic SQL, but you must declare the table inside the dynamic SQL itself. The following query will fail with the error “Must declare the variable '@MyTable'.”

DECLARE @MyTable TABLE
(
  ProductID int ,
  Name varchar(10)
)
 
 
EXEC sp_executesql N'SELECT * FROM @MyTable'