Comprobar si la tabla existe en SQL Server


Me gustaría que esta fuera la última discusión sobre cómo verificar si existe una tabla en SQL Server 2000/2005 usando la instrucción SQL.

Cuando buscas en Google la respuesta, obtienes muchas respuestas diferentes. ¿Hay una forma oficial / hacia atrás y hacia adelante compatible de hacerlo?

Aquí hay dos formas posibles de hacerlo. ¿Cuál de los dos es el estándar / mejor manera de hacerlo?

Primera manera:

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

Segunda manera:

IF OBJECT_ID (N'mytablename', N'U') IS NOT NULL 
   SELECT 1 AS res ELSE SELECT 0 AS res;

MySQL proporciona el simple

SHOW TABLES LIKE '%tablename%'; 

Declaración. Estoy buscando algo similar.

Author: DrHouseofSQL, 2008-10-03

22 answers

Para consultas como esta siempre es mejor usar una vista INFORMATION_SCHEMA. Estas vistas son (en su mayoría) estándar en muchas bases de datos diferentes y rara vez cambian de versión a versión.

Para comprobar si existe una tabla use:

IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'TheSchema' 
                 AND  TABLE_NAME = 'TheTable'))
BEGIN
    --Do Stuff
END
 1086
Author: akmad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-03 10:26:39

También tenga en cuenta que si por alguna razón necesita verificar una tabla temporal, puede hacer esto:

if OBJECT_ID('tempdb..#test') is not null
 --- temp table exists
 228
Author: James Bloomer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-28 14:50:03

Siempre usamos el estilo OBJECT_ID durante el tiempo que recuerdo

IF OBJECT_ID('*objectName*', 'U') IS NOT NULL 
 186
Author: Bob King,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-15 12:44:15

Por favor, vea los siguientes enfoques,

Enfoque 1: Uso de INFORMATION_SCHEMA.Vista de TABLAS

Podemos escribir una consulta como la siguiente para comprobar si existe una Tabla de Clientes en la base de datos actual.

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'Customers')
BEGIN
    PRINT 'Table Exists'
END

Enfoque 2: Usando la función OBJECT_ID ()

Podemos usar la función OBJECT_ID() como a continuación para comprobar si existe una Tabla Customers en la base de datos actual.

IF OBJECT_ID(N'dbo.Customers', N'U') IS NOT NULL
BEGIN
    PRINT 'Table Exists'
END

Enfoque 3: Usando sys.Vista de catálogo de objetos

Podemos utilizar el Sys.Vista de catálogo de objetos para comprobar la existencia de la Tabla como se muestra a continuación:

IF EXISTS(SELECT 1 FROM sys.Objects WHERE  Object_id = OBJECT_ID(N'dbo.Customers') AND Type = N'U')
BEGIN
   PRINT 'Table Exists'
END

Enfoque 4: Usando sys.Vista de catálogo de tablas

Podemos usar el Sys.Vista de catálogo de tablas para comprobar la existencia de la Tabla como se muestra a continuación:

 IF EXISTS(SELECT 1 FROM sys.Tables WHERE  Name = N'Customers' AND Type = N'U')
 BEGIN
      PRINT 'Table Exists'
 END

Enfoque 5: Evite Usar sys.sysobjects System table

Debemos evitar usar sys.sysobjects System Table directly, el acceso directo a ella quedará obsoleto en algunas versiones futuras de Sql Server. Según Microsoft BOL link, Microsoft está sugiriendo utilizar las vistas de catálogo sys.objects / sys.tablas en lugar de sys.sysobjects system table directamente.

  IF EXISTS(SELECT name FROM sys.sysobjects WHERE Name = N'Customers' AND xtype = N'U')
  BEGIN
     PRINT 'Table Exists'
  END

Referido de: http://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server /

 92
Author: BrainCoder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-22 12:01:58

Buscando una tabla en una base de datos diferente:

if exists (select * from MyOtherDatabase.sys.tables where name = 'MyTable')
    print 'Exists'
 30
Author: Larry Leonard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-15 17:19:42
IF OBJECT_ID('mytablename') IS NOT NULL 
 19
Author: sansalk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-15 12:44:52

Solo quería mencionar una situación en la que probablemente sería un poco más fácil usar el método OBJECT_ID. Las vistas INFORMATION_SCHEMA son objetos bajo cada base de datos-

Las vistas de esquema de información se definen en un esquema especial llamado INFORMATION_SCHEMA. Este esquema está contenido en cada base de datos.

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

Por lo tanto, todas las tablas a las que accede usando

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;

Solo reflejará lo que está en [database]. Si desea comprobar si existen tablas en otra base de datos, sin cambiar dinámicamente la [database] cada vez, OBJECT_ID le permitirá hacer esto fuera de la caja. Ex -

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

Funciona igual de bien que

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

SQL SERVER 2016 Editar :

A partir de 2016, Microsoft simplificó la capacidad de verificar objetos inexistentes antes de eliminar, agregando las palabras clave if exists a las instrucciones drop. Por ejemplo,

drop table if exists mytablename

Hará el lo mismo que OBJECT_ID / INFORMATION_SCHEMA envolturas, en 1 línea de código.

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

 18
Author: iliketocode,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-09 15:13:50

Usar el Esquema de Información es la forma estándar de SQL para hacerlo, por lo que debe ser utilizado por todas las bases de datos que lo soportan.

 17
Author: Vinko Vrsalovic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-03 16:03:54
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

Aquí en el código anterior, el nombre de la tabla es Mapping_APCToFANavigator.

 10
Author: dilip kumar singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-04 17:35:56

Si necesita trabajar en diferentes bases de datos:

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
 8
Author: Even Mien,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-21 14:58:15

Sé que es una vieja pregunta pero he encontrado esta posibilidad si planeas llamarla a menudo.

create procedure Table_Exists
@tbl varchar(50)
as
return (select count(*) from sysobjects where type = 'U' and name = @tbl)
go
 8
Author: dko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-21 15:37:37

Simplemente añadiendo aquí, para el beneficio de los desarrolladores y compañeros DBA

Un script que recibe @Tablename como parámetro

(que puede o no contener el nombre de esquema) y devuelve la información siguiente si el esquema.table exists:

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

Produje este script para ser usado dentro de otros scripts cada vez que necesito probar si existe o no una tabla o vista, y cuando lo hace, obtengo su object_id para ser usado para otros propósitos.

Se plantea un error cuando cualquiera de los dos pasó una cadena vacía, un nombre de esquema incorrecto o un nombre de tabla incorrecto.

Esto podría estar dentro de un procedimiento y devolver -1 por ejemplo.

Como ejemplo, tengo una tabla llamada " Hechos.FactBackOrder " en una de mis bases de datos de Data Warehouse.

Así es como logré esto:

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 
 5
Author: marcello miorelli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-23 17:55:50

En SQL Server 2000 puede intentar:

IF EXISTS(SELECT 1 FROM sysobjects WHERE type = 'U' and name = 'MYTABLENAME')
BEGIN
   SELECT 1 AS 'res' 
END
 4
Author: dipi evil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-16 13:42:06
IF EXISTS 
(
    SELECT  * 

    FROM    INFORMATION_SCHEMA.TABLES 

    WHERE   TABLE_SCHEMA = 'PutSchemaHere'     
            AND  
            TABLE_NAME   = 'PutTableNameHere'
)
 3
Author: Moccassin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-04 17:32:27
    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
 3
Author: BTE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-18 14:36:47

Algo importante para saber para cualquiera que aún no haya encontrado su solución: SQL server != MYSQL . Si quieres hacerlo con MYSQL, es bastante 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";

Publicando esto aquí porque es el mayor éxito en Google.

 2
Author: Blauhirn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-23 13:55:00
select name from SysObjects where xType='U' and name like '%xxx%' order by name
 1
Author: MarceloMadnezz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-10 18:54:51

Si alguien está tratando de hacer lo mismo en linq to sql (o especialmente linqpad) active la opción para incluir tablas y vistas del sistema y haga este código:

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

Dado que tiene un objeto con el nombre en una propiedad llamada item, y el esquema en una propiedad llamada schema donde el nombre de la variable de origen es a

 0
Author: Maslow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-07 18:48:06

Si esta es la discusión 'última', entonces debe tenerse en cuenta que el script de Larry Leonard también puede consultar un servidor remoto si los servidores están vinculados.

if exists (select * from REMOTE_SERVER.MyOtherDatabase.sys.tables where name = 'MyTable')
    print 'Exists'
 0
Author: user3651072,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-18 22:32:56

Create crear procedimiento para comprobar si existe una tabla


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 modo de empleo : comprobar si existen migraciones de tabla


 CALL checkIfTableExists('muDbName', 'migrations', @output);
 0
Author: Mathieu Dierckx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-06 09:39:37
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
Author: Krishnaraj Barvathaya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-19 08:54:28

Considere que en una base de datos tiene una tabla t1. desea ejecutar script en otra base de datos como-si t1 existe entonces no hacer nada más crear t1. Para ello, abra visual studio y haga lo siguiente:

Haga clic con el botón derecho en t1, luego Script table as, luego DROP y Create To, luego New Query Editor

Encontrará la consulta deseada. Pero antes de ejecutar ese script, no olvide comentar la instrucción drop en la consulta, ya que no desea crear una nueva si ya hay una.

Gracias

 -5
Author: sumon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-10 18:32:06