Check if table exists in SQL Server

前端 未结 28 1422
梦如初夏
梦如初夏 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/

    0 讨论(0)
  • 2020-11-22 04:52

    You can use this :

         IF OBJECT_ID (N'dbo.T', N'U') IS NOT NULL 
            BEGIN 
                print 'deleted table';
                drop table t 
            END
         else 
            begin 
                print 'table not found' 
            end
    
     Create table t (id int identity(1,1) not null, name varchar(30) not null, lastname varchar(25) null)
     insert into t( name, lastname) values('john','doe');
     insert into t( name, lastname) values('rose',NULL);
    
     Select * from t
    1   john    doe
    2   rose    NULL
    
     -- clean
     drop table t
    
    0 讨论(0)
  • 2020-11-22 04:52

    -- -- create procedure to check if a table exists


    DELIMITER $$
    
    DROP PROCEDURE IF EXISTS `checkIfTableExists`;
    
    CREATE PROCEDURE checkIfTableExists(
        IN databaseName CHAR(255),
        IN tableName CHAR(255),
        OUT boolExistsOrNot CHAR(40)
    )
    
      BEGIN
          SELECT count(*) INTO boolExistsOrNot FROM information_schema.TABLES
          WHERE (TABLE_SCHEMA = databaseName)
          AND (TABLE_NAME = tableName);
      END $$
    
    DELIMITER ;
    

    -- -- how to use : check if table migrations exists


     CALL checkIfTableExists('muDbName', 'migrations', @output);
    
    0 讨论(0)
  • 2020-11-22 04:54
    IF OBJECT_ID('mytablename') IS NOT NULL 
    
    0 讨论(0)
  • 2020-11-22 04:54
    IF EXISTS (
    SELECT *
    FROM INFORMATION_SCHEMA.TABLES
    WHERE 
    TABLE_CATALOG = 'Database Name' and
    TABLE_NAME = 'Table Name' and 
    TABLE_SCHEMA = 'Schema Name') -- Database and Schema name in where statement can be deleted
    
    BEGIN
    --TABLE EXISTS
    END
    
    ELSE BEGIN
    --TABLE DOES NOT EXISTS
    END
    
    0 讨论(0)
  • 2020-11-22 04:54

    If this is to be the 'ultimate' discussion, then it should be noted that Larry Leonard's script can query a remote server as well if the servers are linked.

    if exists (select * from REMOTE_SERVER.MyOtherDatabase.sys.tables where name = 'MyTable')
        print 'Exists'
    
    0 讨论(0)
提交回复
热议问题