如何在 T-SQL 中动态使用 table 类型

How to use table type in T-SQL dynamically

我想创建一个带有动态参数的存储过程。这些参数之一是 table 类型

CREATE TYPE [dbo].[IdTable] AS TABLE ([Id] [int] NULL)
GO

CREATE PROCEDURE [dbo].[SP_deleteCells]
    @table IdTable READONLY,
    @tableName NVARCHAR(50),
    @fieldName NVARCHAR(50),
    @result BIT OUTPUT
AS
    DECLARE @SQL NVARCHAR(500);

    SET @SQL='delete from TBL_CustomerTerminal where ID in (select ID from @table)'
    EXEC (@SQL);

    SET @result = @@ROWCOUNT;

我怎样才能不出错地执行这段代码??现在,我得到:

Must declare the table variable "@table"

使用sp_executesql

exec sp_executesql N'delete from TBL_CustomerTerminal where ID in (select ID from @table)'
  , N'@table dbo.IdTable readonly'  /* parameter declaration for sp_executesql */
  , @table /* pass the parameters */

上面的查询似乎不需要动态 SQL。但我认为这只是一个样本。

动态 SQL 查询有它自己的代码可见性。它看不到本地定义变量之外的任何变量。如果你想将参数传递给你的查询,你需要使用 sp_executesql 而不是 EXEC.

https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql