vendredi 29 avril 2016

Simple if statement not working (string comparison)

This block of code is not working:

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

But both if statements are run so the temporary table #MPLIST2 is created 2 times, which of course gives an error.

I cannot figure out why.

Here is the code changed a little bit:

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

This part executes succesfully without 'hellooo'. But if I comment in the "create table' line below, then it gives the error "There is already an object named '#MPLIST2' in the database."

Aucun commentaire:

Enregistrer un commentaire