2016-04-29 83 views
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'。’

+0

標籤的DBMS。(遠離ANSI SQL ...) – jarlh

+0

如果已經有一個TABL e爲這個名字,也許你應該重新創建前輟學它; .-) – schlonzo

+0

Jarlh,對不起。這是tsql。 –

回答

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 

由此,在獨立事務的批次腳本,防止錯誤。使用