检查SQL Server中是否存在表

发布于 2024-07-05 22:34:19 字数 576 浏览 6 评论 0原文

我希望这是关于如何使用 SQL 语句检查 SQL Server 2000/2005 中表是否存在的最终讨论。

这里有两种可能的方法。 哪一种是标准/最佳方法?

第一种方式:

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;

第二种方式:

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

MySQL提供了简单的

SHOW TABLES LIKE '%tablename%'; 

语句。 我正在寻找类似的东西。

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.

Here are two possible ways of doing it. Which one is the standard/best way of doing it?

First way:

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;

Second way:

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

MySQL provides the simple

SHOW TABLES LIKE '%tablename%'; 

statement. I am looking for something similar.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

触ぅ动初心 2024-07-12 22:34:20

为什么大多数用户说“if *** is not null”!?尝试“if *** is null”:)

IF OBJECT_ID(N'[dbo].[Error]', N'U') IS null
BEGIN
    CREATE TABLE [dbo].[Error](
        [id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
        [Values] [nvarchar](MAX) NOT NULL,
        [Created] [datetimeoffset](0) NOT NULL,
        )
END

why most of user say 'if *** is not null' !?, try 'if *** is null' :)

IF OBJECT_ID(N'[dbo].[Error]', N'U') IS null
BEGIN
    CREATE TABLE [dbo].[Error](
        [id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
        [Values] [nvarchar](MAX) NOT NULL,
        [Created] [datetimeoffset](0) NOT NULL,
        )
END
捂风挽笑 2024-07-12 22:34:20

如果您只想返回 true 或 false 如果 SQL Server 中存在或不存在
您可以使用以下查询,只需将 tableName 替换为您的表名称

IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'
AND TABLE_NAME='表名')
选择 1 AS 资源 ELSE 选择 0 AS 资源;

if you want just to return true or false if exists or not in the SQL server
you can use the following query just replace tableName with your table Name

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

被你宠の有点坏 2024-07-12 22:34:20

运行此查询来检查数据库中是否存在该表:

IF(SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'YourTableName') IS NOT NULL
PRINT 'Table Exists';

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';
十秒萌定你 2024-07-12 22:34:20

SQL Server 2000中,您可以尝试:

IF EXISTS(SELECT 1 FROM sysobjects WHERE type = 'U' and name = 'MYTABLENAME')
BEGIN
   SELECT 1 AS 'res' 
END

In SQL Server 2000 you can try:

IF EXISTS(SELECT 1 FROM sysobjects WHERE type = 'U' and name = 'MYTABLENAME')
BEGIN
   SELECT 1 AS 'res' 
END
陈甜 2024-07-12 22:34:20

对于此类查询,最好使用 INFORMATION_SCHEMA 视图。 这些视图(大部分)是许多不同数据库的标准,并且很少随着版本的不同而改变。

要检查表是否存在,请使用:

IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'TheSchema' 
                 AND  TABLE_NAME = 'TheTable'))
BEGIN
    --Do Stuff
END

For queries like this it is always best to use an INFORMATION_SCHEMA view. These views are (mostly) standard across many different databases and rarely change from version to version.

To check if a table exists use:

IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'TheSchema' 
                 AND  TABLE_NAME = 'TheTable'))
BEGIN
    --Do Stuff
END
握住你手 2024-07-12 22:34:20

另请注意,如果出于任何原因您需要检查临时表,您可以执行以下操作:

if OBJECT_ID('tempdb..#test') is not null
 --- temp table exists

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
三生一梦 2024-07-12 22:34:20

从我记事起,我们就一直使用 OBJECT_ID 样式

IF OBJECT_ID('*objectName*', 'U') IS NOT NULL 

We always use the OBJECT_ID style for as long as I remember

IF OBJECT_ID('*objectName*', 'U') IS NOT NULL 
网名女生简单气质 2024-07-12 22:34:20

请参阅以下方法,

方法 1:使用 INFORMATION_SCHEMA.TABLES 视图

我们可以编写如下查询来检查当前数据库中是否存在 Customers 表。

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

方法 2:使用 OBJECT_ID() 函数

我们可以使用如下所示的 OBJECT_ID() 函数来检查当前数据库中是否存在 Customers 表。

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

方法 3:使用 sys.Objects 目录视图

我们可以使用 Sys.Objects 目录视图来检查 Table 是否存在,如下所示:

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

方法 4:使用 sys.Tables 目录视图

我们可以使用Sys.Tables目录视图来检查表是否存在,如下所示:

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

方法5:避免使用sys.sysobjects系统表

我们应该避免直接使用sys.sysobjects系统表,在 Sql Server 的某些未来版本中将不再推荐直接访问它。 根据 Microsoft BOL 链接,Microsoft 建议直接使用目录视图 sys.objects/sys.tables 而不是 sys.sysobjects 系统表。

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

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

Please see the below approaches,

Approach 1: Using INFORMATION_SCHEMA.TABLES view

We can write a query like below to check if a Customers Table exists in the current database.

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

Approach 2: Using OBJECT_ID() function

We can use OBJECT_ID() function like below to check if a Customers Table exists in the current database.

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

Approach 3: Using sys.Objects Catalog View

We can use the Sys.Objects catalog view to check the existence of the Table as shown below:

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

Approach 4: Using sys.Tables Catalog View

We can use the Sys.Tables catalog view to check the existence of the Table as shown below:

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

Approach 5: Avoid Using sys.sysobjects System table

We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per Microsoft BOL link, Microsoft is suggesting to use the catalog views sys.objects/sys.tables instead of sys.sysobjects system table directly.

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

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

七颜 2024-07-12 22:34:20

在不同的数据库中查找表:

if exists (select * from MyOtherDatabase.sys.tables where name = 'MyTable')
    print 'Exists'

Looking for a table on a different database:

if exists (select * from MyOtherDatabase.sys.tables where name = 'MyTable')
    print 'Exists'
梦情居士 2024-07-12 22:34:20

只是想提一下一种情况,使用 OBJECT_ID 方法可能会更容易一些。 INFORMATION_SCHEMA 视图是每个数据库下的对象 -

信息模式视图在名为的特殊模式中定义
信息架构。 该架构包含在每个数据库中。

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

因此,您访问的所有表

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;

将仅反映 [database] 中的内容。 如果您想检查另一个数据库中的表是否存在,而不需要每次动态更改[database]OBJECT_ID将让您做到这一点盒子的。 Ex-

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

一样

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

:从 2016 年开始,Microsoft 通过添加 if isn't 简化了在删除之前检查不存在的对象的功能drop 语句的关键字。 例如,

drop table if exists mytablename

将在 1 行代码中执行与 OBJECT_ID / INFORMATION_SCHEMA 包装器相同的操作。

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

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/

甜点 2024-07-12 22:34:20
IF OBJECT_ID('mytablename') IS NOT NULL 
IF OBJECT_ID('mytablename') IS NOT NULL 
娇女薄笑 2024-07-12 22:34:20

您可以使用下面的代码

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

或者

IF (EXISTS (SELECT * FROM sys.tables WHERE [name] = 'TableName'))
BEGIN
  PRINT 'Table Exists'
END
ELSE
BEGIN 
  PRINT 'Table NOT Exists'
END

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
堇年纸鸢 2024-07-12 22:34:20

使用信息模式是执行此操作的 SQL 标准方法,因此所有支持它的数据库都应该使用它。 请参阅此答案中的方法 1。

Using the Information Schema is the SQL Standard way to do it, so it should be used by all databases that support it. See Approach 1 in this answer.

原谅过去的我 2024-07-12 22:34:20
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

在上面的代码中,表名称为 Mapping_APCToFNavigator

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.

很酷不放纵 2024-07-12 22:34:20

如果您需要使用不同的数据库:

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

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
人│生佛魔见 2024-07-12 22:34:20

我知道这是一个老问题,但如果您打算经常调用它,我发现了这种可能性。

create procedure Table_Exists
@tbl varchar(50)
as
return (select count(*) from sysobjects where type = 'U' and name = @tbl)
go

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
征﹌骨岁月お 2024-07-12 22:34:20

只是为了开发人员和其他 DBA 的利益而在此处添加

一个脚本,该脚本接收 @Tablename 作为参数

(可能包含也可能不包含 schemaname),并在 schema.table 存在时返回以下信息:

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

我生成了要使用的脚本每次我需要测试表或视图是否存在时,在其他脚本中,当存在时,获取其 object_id 以用于其他目的。

当您传递空字符串、错误的架构名称或错误的表名称时,它会引发错误。

例如,这可以在过程内部并返回 -1。

例如,我的一个数据仓库数据库中有一个名为“Facts.FactBackOrder”的表。

这就是我实现这一目标的方法:

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 

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 
泪痕残 2024-07-12 22:34:20

如果这是“最终”讨论,那么应该注意的是,如果服务器已链接,Larry Leonard 的脚本也可以查询远程服务器。

if exists (select * from REMOTE_SERVER.MyOtherDatabase.sys.tables where name = 'MyTable')
    print 'Exists'

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'
梅倚清风 2024-07-12 22:34:20
IF EXISTS 
(
    SELECT  * 

    FROM    INFORMATION_SCHEMA.TABLES 

    WHERE   TABLE_SCHEMA = 'PutSchemaHere'     
            AND  
            TABLE_NAME   = 'PutTableNameHere'
)
IF EXISTS 
(
    SELECT  * 

    FROM    INFORMATION_SCHEMA.TABLES 

    WHERE   TABLE_SCHEMA = 'PutSchemaHere'     
            AND  
            TABLE_NAME   = 'PutTableNameHere'
)
痴意少年 2024-07-12 22:34:20

我认为以下查询有效:

IF EXISTS (select * from sys.tables 
WHERE name='mytablename' )
BEGIN
     print 'table exists in the database'
END

I think the following query works:

IF EXISTS (select * from sys.tables 
WHERE name='mytablename' )
BEGIN
     print 'table exists in the database'
END
ま柒月 2024-07-12 22:34:20

我在选择 INFORMATIONAL_SCHEME 和 OBJECT_ID 时遇到了一些问题。 我不知道这是 ODBC 驱动程序的问题还是其他问题。来自 SQL Management Studio 的查询都没有问题。

解决方案如下:

SELECT COUNT(*) FROM <yourTableNameHere>

因此,如果查询失败,则数据库中可能不存在这样的表(或者您没有访问它的权限)。

检查是通过比较处理 ODBC 驱动程序的 SQL 执行器返回的值(在我的例子中为整数)来完成的。

if (sqlexec(conectionHandle, 'SELECT COUNT(*) FROM myTable') == -1) {
  // myTable doesn't exist..
}

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..
}
寂寞陪衬 2024-07-12 22:34:20
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
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
债姬 2024-07-12 22:34:20

你可以使用这个:

     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

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
左秋 2024-07-12 22:34:20
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
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
鱼忆七猫命九 2024-07-12 22:34:20

还有一个选项可以检查该表是否跨数据库存在

IF EXISTS(SELECT 1 FROM [change-to-your-database].SYS.TABLES WHERE NAME = 'change-to-your-table-name')
BEGIN
    -- do whatever you want
END

There is one more option to check if the table exists across databases

IF EXISTS(SELECT 1 FROM [change-to-your-database].SYS.TABLES WHERE NAME = 'change-to-your-table-name')
BEGIN
    -- do whatever you want
END
等数载,海棠开 2024-07-12 22:34:20

如果有人尝试在 linq to sql (或者特别是 linqpad)中执行相同的操作,请打开包含系统表和视图的选项并执行以下代码:

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

假设您有一个对象,其名称位于名为 item 的属性中,并且架构在名为 schema 的属性中,其中源变量名称为 a

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

濫情▎り 2024-07-12 22:34:20
select name from SysObjects where xType='U' and name like '%xxx%' order by name
select name from SysObjects where xType='U' and name like '%xxx%' order by name
无声无音无过去 2024-07-12 22:34:20

对于尚未找到解决方案的人来说,需要了解一些重要信息:
SQL 服务器!= MYSQL
如果您想使用 MYSQL 进行此操作,

    $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";

则将其发布到此处非常简单,因为它是 Google 的热门搜索。

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.

轮廓§ 2024-07-12 22:34:20

-- -- 创建过程来检查表是否存在


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 ;

-- -- 如何使用:检查表迁移是否存在


 CALL checkIfTableExists('muDbName', 'migrations', @output);

-- -- 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);
浅笑依然 2024-07-12 22:34:20

我在这里以创建视图为例

因为 ALTER/CREATE 命令不能位于 BEGIN/END 块内。 您需要测试是否存在并在创建之前删除它。

IF Object_ID('TestView') IS NOT NULL
DROP VIEW TestView

GO

CREATE VIEW TestView
   as
   . . .

GO

如果您担心权限丢失,您也可以编写 GRANT 语句脚本并在最后重新运行这些语句。

您可以将创建/更改包装到字符串中并执行 EXEC - 对于大视图来说这可能会变得难看

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文