Check if table exists in SQL Server

前端 未结 28 1547
梦如初夏
梦如初夏 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 05:09
    IF EXISTS 
    (
        SELECT  * 
    
        FROM    INFORMATION_SCHEMA.TABLES 
    
        WHERE   TABLE_SCHEMA = 'PutSchemaHere'     
                AND  
                TABLE_NAME   = 'PutTableNameHere'
    )
    
    0 讨论(0)
  • 2020-11-22 05:09

    If anyone is trying to do this same thing in linq to sql (or especially linqpad) turn on option to include system tables and views and do this code:

    let oSchema = sys.Schemas.FirstOrDefault(s=>s.Name==a.schema )
    where oSchema !=null
    let o=oSchema!=null?sys.Objects.FirstOrDefault (o => o.Name==a.item && o.Schema_id==oSchema.Schema_id):null
    where o!=null
    

    given that you have an object with the name in a property called item, and the schema in a property called schema where the source variable name is a

    0 讨论(0)
  • 2020-11-22 05:10

    If you need to work on different databases:

    DECLARE @Catalog VARCHAR(255)
    SET @Catalog = 'MyDatabase'
    
    DECLARE @Schema VARCHAR(255)
    SET @Schema = 'dbo'
    
    DECLARE @Table VARCHAR(255)
    SET @Table = 'MyTable'
    
    IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES   
        WHERE TABLE_CATALOG = @Catalog 
          AND TABLE_SCHEMA = @Schema 
          AND TABLE_NAME = @Table))
    BEGIN
       --do stuff
    END
    
    0 讨论(0)
  • 2020-11-22 05:10

    You can use below code

    IF (OBJECT_ID('TableName') IS NOT NULL )
    BEGIN
      PRINT 'Table Exists'
    END
    ELSE
    BEGIN 
      PRINT 'Table NOT Exists'
    END
    

    Or

    IF (EXISTS (SELECT * FROM sys.tables WHERE [name] = 'TableName'))
    BEGIN
      PRINT 'Table Exists'
    END
    ELSE
    BEGIN 
      PRINT 'Table NOT Exists'
    END
    
    0 讨论(0)
提交回复
热议问题