4

So far I've been using the format below for creating/updating tables

IF EXISTS (SELECT 1 FROM sysobjects WHERE name = 'table_name' AND type = 'U') 
DROP TABLE [dbo].[table_name]
GO
CREATE TABLE [dbo].[table_name]()
GO

But recently I came across a case where two schemas have a table with the same name. How can I check if the table exists in a specific schema? Its only the partSELECT 1 FROM sysobjects WHERE name = 'table_name' AND type = 'U' that needs fixing, I've changed the rest to:

IF EXISTS (SELECT 1 FROM sysobjects WHERE name = 'table_name' AND type = 'U') 
DROP TABLE [schema_name].[table_name]
GO
CREATE TABLE [schema_name].[table_name]()
GO

My current server version is 2008R2 so I would prefer answers that also work for that version. I have many other checks is done this way so I don't really want to completely change this pattern.

1
  • 1
    Consider using the more concise OBJECT_ID function: IF OBJECT_ID(N'[schema_name].[table_name]') IS NOT NULL....
    – Dan Guzman
    Commented Feb 8, 2019 at 11:16

3 Answers 3

12

TRY

IF OBJECT_ID('[schema_name].[table_name]') IS NOT NULL
        DROP TABLE [schema_name].[table_name]
    GO
0
6

Use this syntax.

DROP TABLE IF EXISTS [schema_name].[table_name]

1
  • 4
    Note that DROP...IF EXISTS requires SQL Server 2016 or later.
    – Dan Guzman
    Commented Feb 8, 2019 at 11:18
5

You could use the schemas object as well. For example:

IF EXISTS (SELECT 1
           FROM sys.tables t
                JOIN sys.schemas s ON t.schema_id = s.schema_id
           WHERE s.[name] = N'schema_name'
             AND t.name = N'table_name'
             AND t.type = 'U')
    DROP TABLE [schema_name].[table_name];
GO
3
  • 2
    @nickzoum personally, I suggest the OBJECT_ID answer from S.Jose. It is far more succinct.
    – Thom A
    Commented Feb 8, 2019 at 11:23
  • Every other check is done this way. I don't really want to completely change the pattern. I also spotted a u_id variable in sysobjects is that not the same as schema_id in sys.tables?
    – nick zoum
    Commented Feb 8, 2019 at 11:25
  • 1
    Fair enough. Might be worth while in the future if you do want to make it more succinct though :)
    – Thom A
    Commented Feb 8, 2019 at 11:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.