1

此代码块不起作用:

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 被创建了 2 次,这当然会产生错误。

我不知道为什么。

这是代码稍作改动:

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

这部分在没有 'hellooo' 的情况下成功执行。但是,如果我在下面的“创建表”行中进行评论,则会出现错误“数据库中已经有一个名为 '#MPLIST2' 的对象”。

4

1 回答 1

1

出现此问题的原因是整个语句是同时编译的。因此,创建现有表的条件(例如)会导致错误。一种解决方案是动态 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

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

于 2016-04-29T10:38:57.777 回答