IF EXISTS doesn't work for me

  • I'm trying to chekck the existance of a table first and then get a value ONLY IF when the table is there. So, I tried this;

    if exists (select name from [LinkedServer].[dbName].[sys].[sysobjects] where name = 'tableName1')

    begin

    insert into tableName2 (value1, values)

    select values1, value2 from [LinkedServer].[dbName].dbo.tableName1

    end

    However, this statement still executes even if "IF EXITST"returns nothing and fails with "table does not exists".

    Can someone tell me what am i doing wrong here?

    Thanks!!

  • Biank (3/13/2013)


    I'm trying to chekck the existance of a table first and then get a value ONLY IF when the table is there. So, I tried this;

    if exists (select name from [LinkedServer].[dbName].[sys].[sysobjects] where name = 'tableName1')

    begin

    insert into tableName2 (value1, values)

    select values1, value2 from [LinkedServer].[dbName].dbo.tableName1

    end

    However, this statement still executes even if "IF EXITST"returns nothing and fails with "table does not exists".

    Can someone tell me what am i doing wrong here?

    Thanks!!

    The IF EXISTS is done at run time. SQL Server checks for the existence for tableName1 in the INSERT statement during compile time. For what you want, you need to put the INSERT into a dynamic sql statement so that it is run only if the table exists. Also, you should use sys.objects not sys.sysobjects. You could also use sys.tables as it only has user tables.

  • Thank you, it works that way.

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply