Check if table exists in SQL Server

前端 未结 28 2100
梦如初夏
梦如初夏 2020-11-22 04:23

I would like this to be the ultimate discussion on how to check if a table exists in SQL Server 2000/2005 using SQL Statements.

When you Google for the answer, you g

28条回答
  •  生来不讨喜
    2020-11-22 04:52

    Just wanted to mention one situation where it would probably be a little easier to use the OBJECT_ID method. The INFORMATION_SCHEMA views are objects under each database-

    The information schema views are defined in a special schema named INFORMATION_SCHEMA. This schema is contained in each database.

    https://msdn.microsoft.com/en-us/library/ms186778.aspx

    Therefore all tables you access using

    IF EXISTS (SELECT 1 
               FROM [database].INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_TYPE='BASE TABLE' 
               AND TABLE_NAME='mytablename') 
       SELECT 1 AS res ELSE SELECT 0 AS res;
    

    will only reflect what is in [database]. If you wanted to check if tables in another database exist, without dynamically changing the [database] each time, OBJECT_ID will let you do this out of the box. Ex-

    IF OBJECT_ID (N'db1.schema.table1', N'U') IS NOT NULL 
       SELECT 1 AS res ELSE SELECT 0 AS res;
    

    works just as well as

    IF OBJECT_ID (N'db2.schema.table1', N'U') IS NOT NULL 
       SELECT 1 AS res ELSE SELECT 0 AS res;
    

    SQL SERVER 2016 Edit:

    Starting with 2016, Microsoft simplified the ability to check for non-existent objects prior to dropping, by adding the if exists keywords to drop statements. For example,

    drop table if exists mytablename
    

    will do the same thing as OBJECT_ID / INFORMATION_SCHEMA wrappers, in 1 line of code.

    https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016/

提交回复
热议问题