这段代码不起作用:
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'在数据库中。"
答案 0 :(得分: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
这会在脚本中生成单独的事务批处理,从而防止出错。