如何在 SQL Server 中检查表是否存在

如何在 SQL Server 中检查表是否存在?这是常见问题之一。

检查 SQL Server 中的表是否存在

在此示例中,我们使用 OBJECT_ID 向您展示如何检查表是否存在。我们在这里使用 IF ELSE 语句,根据条件结果打印不同的输出(消息)。

-- Query:- check table exists before creating

IF OBJECT_ID('dbo.Employees', 'U') IS NOT NULL 
BEGIN
  PRINT 'Table Exists in SQL Test Database'
END
ELSE
BEGIN
PRINT 'Table Does not Exists'
END

提示:在创建表之前,最好始终检查服务器表是否存在,然后再使用 IF ELSE。

Using If Else and OBJECT_ID 1

使用 Information_schema.tables 检查表是否存在

在此示例中,我们使用 Information_schema.tables 来检查表是否存在

这里我们使用 EXISTS 操作符来检查 Employees 表是否存在于数据库中。如果存在,它将返回第一个 PRINT 语句。否则,它将返回 ELSE 块中的语句。

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_NAME = N'Employees')
BEGIN
  PRINT 'Table Exists in SQL Test Database'
END
ELSE
BEGIN
PRINT 'Table Does not Exists'
END
How to check if a Table exists 2

让我向您展示 INFORMATION_SCHEMA.TABLES 中有哪些列。

SELECT * FROM INFORMATION_SCHEMA.TABLES
INFORMATION_SCHEMA.TABLES Data 3

现在,我将尝试使用一个不存在的表。

How to check if a Table exists 5

使用 SQL Server sys.Objects 检查表是否存在

在这里,我们使用 sys.Objects 检查表是否存在于服务器中。

-- SQL check if table exists before creating

IF EXISTS(SELECT 1 FROM sys.Objects 
    WHERE  Object_id = OBJECT_ID(N'dbo.Employees') 
           AND Type = N'U')
BEGIN
  PRINT 'Table Exists in SQL Test Database'
END
ELSE
BEGIN
PRINT 'Table Does not Exists'
END
Using sys.Objects 5

让我向您展示 sys.Objects 中可用的列列表。此处 type = U 表示用户表。

-- SQL check if table exists before creating

SELECT * FROM sys.Objects
WHERE TYPE = N'U'
sys.Objects Information

使用 sys.Tables

在此示例中,我们将展示如何使用 sys.Tables 检查表是否存在。

IF EXISTS(SELECT 1 FROM sys.Tables 
          WHERE  Name = N'Employees')
BEGIN
  PRINT 'Table Exists in SQL Test Database'
END
ELSE
BEGIN
PRINT 'Table Does not Exists'
END
Using sys.Tables 7

让我向您展示 sys.Tables 中可用的列列表。

SELECT * FROM sys.Tables
Sys.Tables Information