Check if table exists in SQL Server

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

    Just adding here, for the benefit of developers and fellow DBAs

    a script that receives @Tablename as a parameter

    (which may or may not contain the schemaname) and returns the info below if the schema.table exists:

    the_name                object_id   the_schema  the_table       the_type
    [Facts].[FactBackOrder] 758293761   Facts       FactBackOrder   Table
    

    I produced this script to be used inside other scripts every time I need to test whether or not a table or view exists, and when it does, get its object_id to be used for other purposes.

    It raises an error when either you passed an empty string, wrong schema name or wrong table name.

    this could be inside a procedure and return -1 for example.

    As an example, I have a table called "Facts.FactBackOrder" in one of my Data Warehouse databases.

    This is how I achieved this:

    PRINT 'THE SERVER IS ' + @@SERVERNAME
    --select db_name()
    PRINT 'THE DATABASE IS ' + db_NAME() 
    PRINT ''
    GO
    
    SET NOCOUNT ON
    GO
    
    --===================================================================================
    -- @TableName is the parameter
    -- the object we want to deal with (it might be an indexed view or a table)
    -- the schema might or might not be specified
    -- when not specified it is DBO
    --===================================================================================
    
    DECLARE @TableName SYSNAME
    
    SELECT @TableName = 'Facts.FactBackOrder'
    --===================================================================================
    --===================================================================================
    DECLARE @Schema SYSNAME
    DECLARE @I INT
    DECLARE @Z INT 
    
    SELECT @TableName = LTRIM(RTRIM(@TableName))
    SELECT @Z = LEN(@TableName)
    
    IF (@Z = 0) BEGIN
    
                RAISERROR('Invalid @Tablename passed.',16,1)
    
    END 
    
    SELECT @I = CHARINDEX('.',@TableName )
    --SELECT @TableName ,@I
    
    IF @I > 0 BEGIN
    
            --===================================================================================
            -- a schema and table name have been passed
            -- example Facts.FactBackOrder 
            -- @Schema = Fact
            -- @TableName = FactBackOrder
            --===================================================================================
    
       SELECT @Schema    = SUBSTRING(@TABLENAME,1,@I-1)
       SELECT @TableName = SUBSTRING(@TABLENAME,@I+1,@Z-@I)
    
    
    
    END
    ELSE BEGIN
    
            --===================================================================================
            -- just a table name have been passed
            -- so the schema will be dbo
            -- example Orders
            -- @Schema = dbo
            -- @TableName = Orders
            --===================================================================================
    
       SELECT @Schema    = 'DBO'     
    
    
    END
    
            --===================================================================================
            -- Check whether the @SchemaName is valid in the current database
            --===================================================================================
    
    IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.SCHEMATA K WHERE K.[SCHEMA_NAME] = @Schema ) BEGIN
    
                RAISERROR('Invalid Schema Name.',16,1)
    
    END 
    
    --SELECT @Schema  as [@Schema]
    --      ,@TableName as [@TableName]
    
    
    DECLARE @R1 TABLE (
    
       THE_NAME SYSNAME
      ,THE_SCHEMA SYSNAME
      ,THE_TABLE SYSNAME
      ,OBJECT_ID INT
      ,THE_TYPE SYSNAME
      ,PRIMARY KEY CLUSTERED (THE_SCHEMA,THE_NAME)
    
    )
    
    ;WITH RADHE_01 AS (
    SELECT QUOTENAME(SCHEMA_NAME(O.schema_id)) + '.' + QUOTENAME(O.NAME) AS [the_name]
          ,the_schema=SCHEMA_NAME(O.schema_id)
          ,the_table=O.NAME
          ,object_id =o.object_id 
          ,[the_type]= CASE WHEN O.TYPE = 'U' THEN 'Table' ELSE 'View' END 
    from sys.objects O
    where O.is_ms_shipped = 0
    AND O.TYPE IN ('U','V')
    )
    INSERT INTO @R1 (
       THE_NAME 
      ,THE_SCHEMA 
      ,THE_TABLE 
      ,OBJECT_ID
      ,THE_TYPE 
    )
    SELECT  the_name
           ,the_schema
           ,the_table
           ,object_id
           ,the_type
    FROM RADHE_01
    WHERE the_schema = @Schema 
      AND the_table  = @TableName
    
    IF (@@ROWCOUNT = 0) BEGIN 
    
                 RAISERROR('Invalid Table Name.',16,1)
    
    END 
    ELSE BEGIN
    
        SELECT     THE_NAME 
                  ,THE_SCHEMA 
                  ,THE_TABLE 
                  ,OBJECT_ID
                  ,THE_TYPE 
    
        FROM @R1
    
    END 
    
    0 讨论(0)
  • 2020-11-22 05:06

    consider in one database you have a table t1. you want to run script on other Database like - if t1 exist then do nothing else create t1. To do this open visual studio and do the following:

    Right click on t1, then Script table as, then DROP and Create To, then New Query Editor

    you will find your desired query. But before executing that script don't forget to comment out the drop statement in the query as you don't want to create new one if there is already one.

    Thanks

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

    Also note that if for any reason you need to check for a temporary table you can do this:

    if OBJECT_ID('tempdb..#test') is not null
     --- temp table exists
    
    0 讨论(0)
  • 2020-11-22 05:07

    I know it is an old question but I have found this possibility if you plan to call it often.

    create procedure Table_Exists
    @tbl varchar(50)
    as
    return (select count(*) from sysobjects where type = 'U' and name = @tbl)
    go
    
    0 讨论(0)
  • 2020-11-22 05:08
    select name from SysObjects where xType='U' and name like '%xxx%' order by name
    
    0 讨论(0)
  • 2020-11-22 05:08

    I've had some problems either with selecting from INFORMATIONAL_SCHEME and OBJECT_ID. I don't know if it's an issue of ODBC driver or something.. Queries from SQL management studio, both, were okay.

    Here is the solution:

    SELECT COUNT(*) FROM <yourTableNameHere>
    

    So, if the query fails, there is, probably, no such table in the database (or you don't have access permissions to it).

    The check is done by comparing the value (integer in my case) returned by SQL executor which deals with ODBC driver..

    if (sqlexec(conectionHandle, 'SELECT COUNT(*) FROM myTable') == -1) {
      // myTable doesn't exist..
    }
    
    0 讨论(0)
提交回复
热议问题