Check if table exists in SQL Server

前端 未结 28 1504
梦如初夏
梦如初夏 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:45

    Using the Information Schema is the SQL Standard way to do it, so it should be used by all databases that support it.

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

    Run this query to check if the table exists in the database:

    IF(SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'YourTableName') IS NOT NULL
    PRINT 'Table Exists';
    
    0 讨论(0)
  • 2020-11-22 04:47

    i taking here creating a view as example.

    Because ALTER/CREATE commands can't be within BEGIN/END blocks. You need to test for existence and the drop it before doing a create

    IF Object_ID('TestView') IS NOT NULL
    DROP VIEW TestView
    
    GO
    
    CREATE VIEW TestView
       as
       . . .
    
    GO
    

    If you are woried about the permissions being lost you can script the GRANT statements as well and re-run those at the end.

    You could wrap the create/alter into a string and do an EXEC - that might get ugly for large views

    DECLARE @SQL as varchar(4000)
    
    -- set to body of view
    SET @SQL = 'SELECT X, Y, Z FROM TABLE' 
    
    IF Object_ID('TestView') IS NULL
        SET @SQL = 'CREATE VIEW TestView AS ' + @SQL
    ELSE    
        SET @SQL = 'ALTER VIEW TestView AS ' + @SQL
    
    0 讨论(0)
  • 2020-11-22 04:48

    Something important to know for anybody who hasn't found their solution yet: SQL server != MYSQL. If you want to do it with MYSQL, it is quite simple

        $sql = "SELECT 1 FROM `db_name`.`table_name` LIMIT 1;";
        $result = mysql_query($sql);
        if( $result == false )
            echo "table DOES NOT EXIST";
        else
            echo "table exists";
    

    Posting this here because it's the top hit at Google.

    0 讨论(0)
  • 2020-11-22 04:51
    IF EXISTS 
    (
        SELECT   * 
        FROM     sys.objects 
        WHERE    object_id = OBJECT_ID(N'[dbo].[Mapping_APCToFANavigator]') 
                 AND 
                 type in (N'U')
    )
    BEGIN
    
        -- Do whatever you need to here.
    
    END
    

    Here in the above code, the table name is Mapping_APCToFANavigator.

    0 讨论(0)
  • 2020-11-22 04:51
    IF EXISTS (   SELECT * FROM   dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.TableName') AND OBJECTPROPERTY(id, N'IsUserTable') = 1 )
    BEGIN
      SELECT * FROM dbo.TableName;
    END
    GO
    
    0 讨论(0)
提交回复
热议问题