Sql 简单if语句不工作(字符串比较)
此代码块不工作:Sql 简单if语句不工作(字符串比较),sql,sql-server,tsql,if-statement,collate,Sql,Sql Server,Tsql,If Statement,Collate,此代码块不工作: 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 NO
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
此部分在没有“hellooo”的情况下成功执行。但是如果我在下面的“create table”行中进行注释,那么它会给出错误“数据库中已经有一个名为“#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
这将在脚本中生成单独的事务批处理,以防止出现错误。标记所使用的dbms。(远离ANSI SQL…)如果已经有一个表具有该名称,可能您应该在重新创建它之前删除它;-)Jarlh,抱歉。这是tsql。