在 MSSQL 中按变量删除类型

drop type by variable in MSSQL

如何在 MSSQL 中使用变量删除类型? 我不能通过以下方式删除它:

create procedure DropSomething(
@tName nvarchar(1000)
, @tCode nvarchar(1000)
)
as
begin
    set nocount on
    if @tCode = 'type'
    begin
        if exists(select [name] from sys.types where [name] = @tName) 
        drop type @tName
    end     
end
go   

exec DropSomething N'typeName','type'

错误信息如下:

Msg 102, Level 15, State 1, Procedure DropSomething, Line 16 [Batch Start Line 19] The syntax near '@tName' is incorrect.

您不能在 SQL 中参数化标识符。参数是数据的占位符,标识符不是数据。

您需要使用动态 SQL:

if @tCode = 'type'
begin
    if exists(select [name] from sys.types where [name] = @tName) 
    begin
        declare @sql nvarchar(200) = 'drop type ' + QUOTENAME(@tName)
        exec(@sql)
    end
end