5

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.... Commented Feb 8, 2019 at 11:16

3 Answers 3

13

TRY

IF OBJECT_ID('[schema_name].[table_name]') IS NOT NULL
        DROP TABLE [schema_name].[table_name]
    GO
Sign up to request clarification or add additional context in comments.

Comments

6

Use this syntax.

DROP TABLE IF EXISTS [schema_name].[table_name]

1 Comment

Note that DROP...IF EXISTS requires SQL Server 2016 or later.
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 Comments

@nickzoum personally, I suggest the OBJECT_ID answer from S.Jose. It is far more succinct.
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?
Fair enough. Might be worth while in the future if you do want to make it more succinct though :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.