简单if语句不起作用(字符串比较)



此代码块不工作:

DECLARE @CollationName varchar(50)
set @CollationName = (
    select collation_name
    from information_schema.columns
    where table_name = 'MeteringPointPrice' and column_name = 'MeteringPointId'
)
if OBJECT_ID('tempdb..#MPLIST2') IS NOT NULL
    drop table #MPLIST2
if @CollationName = 'SQL_Danish_Pref_CP1_CI_AS'
    create table #MPLIST2 (MeteringPointId varchar(18) COLLATE SQL_Danish_Pref_CP1_CI_AS)
if @CollationName = 'Danish_Norwegian_CI_AS'
    create table #MPLIST2(MeteringPointId varchar(18) COLLATE Danish_Norwegian_CI_AS)
select @CollationName gives: Danish_Norwegian_CI_AS

但是两个if语句都在运行,所以临时表#MPLIST2被创建了两次,这当然会产生错误。

我不明白为什么。

这里的代码有点变化:

DECLARE @CollationName varchar(50)
set @CollationName = (
    select collation_name
    from information_schema.columns
    where table_name = 'MeteringPointPrice' and column_name = 'MeteringPointId'
)

if OBJECT_ID('tempdb..#MPLIST2') IS NOT NULL
    drop table #MPLIST2
if @CollationName = 'Danish_Norwegian_CI_AS'
    begin
        create table #MPLIST2 (MeteringPointId varchar(18) COLLATE Danish_Norwegian_CI_AS)
    end
if OBJECT_ID('tempdb..#MPLIST2') IS NULL
    begin
        select 'hellooo'
        --create table #MPLIST2 (MeteringPointId varchar(18) COLLATE SQL_Danish_Pref_CP1_CI_AS)
    end

此部分在没有"helloo"的情况下成功执行。但是,如果我在下面的"创建表"行中注释,那么它会给出错误"数据库中已经有一个名为'#MPLIST2'的对象。"

由于整个语句是同时编译的,所以会出现问题。因此,创建现有表的条件(例如)会导致错误。一种解决方案是动态SQL,但这很混乱。另一种是简单地使用GO:

DECLARE @CollationName varchar(50)
set @CollationName = (
    select collation_name
    from information_schema.columns
    where table_name = 'MeteringPointPrice' and column_name = 'MeteringPointId'
)
GO
if OBJECT_ID('tempdb..#MPLIST2') IS NOT NULL
    drop table #MPLIST2
GO
if @CollationName = 'Danish_Norwegian_CI_AS'
    begin
        create table #MPLIST2 (MeteringPointId varchar(18) COLLATE Danish_Norwegian_CI_AS)
    end;
GO
if OBJECT_ID('tempdb..#MPLIST2') IS NULL
    begin
        select 'hellooo'
        --create table #MPLIST2 (MeteringPointId varchar(18) COLLATE SQL_Danish_Pref_CP1_CI_AS)
    end
GO

这会在脚本中生成单独的事务批,从而防止出现错误。

最新更新