在MSSQL中按变量删除类型

时间:2019-01-24 06:56:31

标签: 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) 
        drop type @tName
    end     
end
go   

exec DropSomething N'typeName','type'

这是错误消息:

  

消息102,级别15,状态1,过程DropSomething,第16行[批处理开始第19行]   “ @tName”附近的语法不正确。

1 个答案:

答案 0 :(得分:2)

您无法在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