Sql server 2008 MSSQL中的drop type by变量

Sql server 2008 MSSQL中的drop type by变量,sql-server-2008,Sql Server 2008,如何在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)

如何在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,15级,状态1,程序,第16行[批次起始行19] “@tName”附近的语法不正确


不能在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     

嗨,Zohar Peled,很成功,谢谢你的帮助!如果类型名中有空格?@TT。说得好。我没想过。我似乎认为伪造者有使用愚蠢名称的习惯:-)Hi@Zoharpled,它会有错误消息:Msg 102,级别15,状态1,过程DropSomething,第21行[批处理开始行18]“QUOTENAME”附近的语法不正确。