SQL Server数据库中的T-SQL如果存在语句概述

This article walks through different versions of the T-SQL IF EXISTS statement for the SQL database using various examples.

本文使用各种示例介绍了用于SQL数据库的T-SQL IF EXISTS语句的不同版本。

  • IF EXISTS in SQL 2014 or before

    如果SQL 2014或更早版本存在
  • DROP ..IF EXISTS in SQL Server 2016 to SQL Server 2019

    将SQL Server 2016中存在的.IF拖放到SQL Server 2019

介绍 (Introduction)

Suppose you want to deploy objects such as tables, procedures, functions in the SQL Server database. If you execute CREATE statements for these objects, and that object already exists in a database, you get message 2714, level 16, state 3 error message as shown below.

假设您要在SQL Server数据库中部署表,过程,函数等对象。 如果对这些对象执行CREATE语句,并且该对象已存在于数据库中,则会收到消息2714,级别16,状态3错误消息,如下所示。

object already exists error message

You may write a DROP statement before executing the create statement. It works fine if the object exists in the database.

您可以在执行create语句之前编写DROP语句。 如果对象存在于数据库中,它将正常工作。

In case the object does not exist, and you try to drop, you get the following error.

如果对象不存在,并尝试删除该对象,则会出现以下错误。

Cannot drop the procedure error

To avoid this situation, usually, developers add T-SQL If Exists statement and drop the object if it is already available in the database.

为了避免这种情况,通常,开发人员添加T-SQL If Exists语句,并删除该对象(如果数据库中已存在该对象)。

Let’s say we wish to deploy a stored procedure ‘stpGetAllMembers’ in the SQLShack test database. We can use multiple methods to check whether the procedure existence in the SQL database but let’s query sys.objects system table for it.

假设我们希望在SQLShack测试数据库中部署存储过程“ stpGetAllMembers”。 我们可以使用多种方法来检查该过程是否存在于SQL数据库中,但是让我们查询sys.objects系统表。

The following code does the below things for us:

以下代码为我们完成了以下操作:

  • First, it executes the select statement inside the IF Exists

    首先,它在IF Exists内部执行select语句
  • TRUE for IF Exists TRUE
  • It starts the code inside a begin statement and prints the message

    它在begin语句中启动代码并输出消息
IF EXISTS
(
    SELECT *
    FROM sys.objects
    WHERE object_id = OBJECT_ID(N'dbo.stpGetAllMembers')
)
    BEGIN
        PRINT 'Stored procedure already exists';
END;

object already exists

If the procedure does not exist, it does not run the code in a begin statement.

如果该过程不存在,则不会在begin语句中运行该代码。

IF EXISTS
(
    SELECT *
    FROM sys.objects
    WHERE object_id = OBJECT_ID(N'dbo.stpGetAllMembers_1')
)
    BEGIN
        PRINT 'Stored procedure already exists';
END;

T-SQL If Exists syntax

Now, we want to drop this procedure if it already exists in the database. We can add a DROP PROCEDURE command inside a begin statement. It drops the stored procedure if it already exists in the database.

现在,如果数据库中已经存在此过程,我们想删除它。 我们可以在begin语句内添加DROP PROCEDURE命令。 如果存储过程已存在于数据库中,它将删除该存储过程。

IF EXISTS
(
    SELECT *
    FROM sys.objects
    WHERE object_id = OBJECT_ID(N'dbo.stpGetAllMembers')
)
    BEGIN
        DROP PROCEDURE stpGetAllMembers;
END;

We can use this method with other SQL Server objects as well. The following query checks for the SQL table existence and drops it if it is there.

我们也可以将这种方法与其他SQL Server对象一起使用。 以下查询检查SQL表是否存在,如果存在,则将其删除。

Drop a procedure

In the article, SQL Code Snippets in Azure Data Studio, we discussed code snippets for writing T-SQL. I thought of checking the syntax for the sqlCreateStoredProc snippet for a new stored procedure.

Azure Data Studio中SQL代码段中 ,我们讨论了编写T-SQL的代码段。 我想到要为新存储过程检查sqlCreateStoredProc片段的语法。

To view this snippet definition, type create proc, press the sqlCreateStoredProc and enter.

要查看此代码段定义,请键入create proc,按sqlCreateStoredProc并输入。

Snippet definition

As shown in the following image, this snippet also uses the IF EXISTS method for writing a stored procedure.

如下图所示,该代码段还使用IF EXISTS方法来编写存储过程。

Code Snippet for SQL database  in Azure Data Studio

DROP IF EXISTS语句 (DROP IF EXISTS statement)

SQL Server 2016 provides an enhancement to check the object’s existence and drop if it already exists. It introduces DROP IF EXISTS command for this purpose.

SQL Server 2016提供了一种增强功能,可以检查对象的存在并删除该对象(如果已存在)。 为此,它引入了DROP IF EXISTS命令。

DROP IF EXISTS的语法 (The syntax for DROP IF EXISTS)

DROP OBJECT_TYPE [ IF EXISTS ] OBJECT_NAME

DROP OBJECT_TYPE [如果存在] OBJECT_NAME

  • It drops the object if it already exists in the SQL database

    如果对象已经存在于SQL数据库中,它将删除该对象
  • We can also use it to drop the column or constraints as well

    我们也可以使用它来删除列或约束
  • If the specified object does not exist, it does not give any error message. It continues the execution for the next command

    如果指定的对象不存在,则不会给出任何错误消息。 继续执行下一条命令

We can use Database, Table, Function, Trigger, Stored Procedure, Column, User, View, Schema, Index, Role for this command.

我们可以为此命令使用数据库,表,函数,触发器,存储过程,列,用户,视图,模式,索引,角色。

Let’s understand this new T-SQL IF EXISTS clause using various examples.

让我们使用各种示例来了解这个新的T-SQL IF EXISTS子句。

如果存在,则删除存储过程 (DROP Stored Procedure IF EXISTS)

In the previous example, we used DROP Stored Procedure stpGetAllMembers for demonstration purposes. This stored procedure does not exist now. Let’s use the new method and try to drop the stored procedure.

在前面的示例中,我们使用了DROP存储过程stpGetAllMembers进行演示。 该存储过程现在不存在。 让我们使用新方法并尝试删除存储过程。

DROP PROCEDURE IF EXISTS stpGetAllMembers;

DROP PROCEDURE IF EXISTS for SQL database

We can add further code such as print statements, create statements. The following code prints a message after the DROP PROCEDURE command.

我们可以添加更多代码,例如打印语句,创建语句。 以下代码在DROP PROCEDURE命令之后输出一条消息。

DROP PROCEDURE IF EXISTS stpGetAllMembers
    PRINT 'Stored proc does not exist'

Let’s create the stored procedure using this new syntax T-SQL IF EXISTS command. The following query drops the stored procedure if it already exists, in case it does not exist, it will create one.

让我们使用此新语法T-SQL IF EXISTS命令创建存储过程。 以下查询将删除该存储过程(如果已存在),如果该存储过程不存在,它将创建一个存储过程。

DROP PROCEDURE IF EXISTS stpGetAllMembers;
GO
CREATE PROCEDURE stpGetAllMembers
AS
     SELECT table_catalog [database], 
            table_schema [schema], 
            table_name [name], 
            table_type [type]
     FROM INFORMATION_SCHEMA.TABLES;

删除查看是否存在 (DROP View IF EXISTS)

We can use the following query for SQL 2016 or later to drop a view.

我们可以对SQL 2016或更高版本使用以下查询来删除视图。

DROP VIEW IF EXISTS vwABC
GO

In SQL Server 2014 or earlier version, we use the following code. It checks the views using sys.objects for type V.

在SQL Server 2014或更早版本中,我们使用以下代码。 它使用sys.objects检查视图的V类型。

IF  EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'vwABC') 
    AND type = N'V')
DROP VIEW vwABC
GO

存在DROP约束 (DROP Constraint IF EXISTS)

We can use the following command to drop a UNIQUE constraint using DROP CONSTRAINT IF EXISTS statement.

我们可以使用以下命令通过DROP CONSTRAINT IF EXISTS语句删除UNIQUE约束。

ALTER TABLE DemoTable DROP CONSTRAINT IF EXISTS EmpID
GO

The following code works in SQL 2014 or before. Type UQ in the sys.objects refers to a UNIQUE constraint.

以下代码可在SQL 2014或更低版本中使用。 sys.objects中的UQ类型引用UNIQUE约束。

IF  EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'EmpID') 
    AND type = N'UQ')
ALTER TABLE DemoTable DROP CONSTRAINT EmpID
GO

For a check constraint, change the type from UQ to C in the SQL 2014 or before version query. We do not need to change the query specified using DROP CONSTRAINT IF EXISTS statement.

对于检查约束,请在SQL 2014中或在版本查询之前将类型从UQ更改为C。 我们不需要更改使用DROP CONSTRAINT IF EXISTS语句指定的查询。

IF  EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'EmpID') 
    AND type = N'C')
ALTER TABLE DemoTable DROP CONSTRAINT EmpID
GO

如果存在则删除表 (DROP Table IF EXISTS)

We can use DROP TABLE IF EXISTS statement to drop a SQL table as well in SQL Server 2016 or later.

我们也可以使用DROP TABLE IF EXISTS语句在SQL Server 2016或更高版本中删除SQL表。

DROP TABLE IF EXISTS DemoTable
GO

For SQL 2014 or previous versions, we need to use IF EXISTS method as shown below. Type U refers to a user-defined SQL table.

对于SQL 2014或更早版本,我们需要使用IF EXISTS方法,如下所示。 类型U引用用户定义SQL表。

IF  EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'DemoTable') 
    AND type = N'U')
DROP TABLE DemoTable
GO

如果存在则删除数据库 (DROP Database IF EXISTS)

We can use the new T-SQL If Exists scripts for dropping a SQL database as well for SQL 2016 or later.

对于SQL 2016或更高版本,我们也可以使用新的T-SQL如果存在脚本删除SQL数据库。

DROP DATABASE IF EXISTS TargetDB
GO

Alternatively, use the following script with SQL 2014 or lower version. It is also valid in the higher SQL Server versions as well.

或者,将以下脚本用于SQL 2014或更低版本。 在更高版本SQL Server中也有效。

IF  EXISTS (SELECT 1 FROM sys.databases WHERE database_id = DB_ID(N'TargetDB'))
    DROP DATABASE TargetDB
GO

如果存在则删除列 (DROP Column IF EXISTS)

Sometimes we require to drop a column from a SQL table. It is a good practice as well to drop unwanted columns as well. It saves efforts for the SQL engine and improves query performance while retrieving fewer records for the output.

有时我们需要从SQL表中删除一列。 删除不需要的列也是一个好习惯。 它节省了SQL引擎的工作量,提高了查询性能,同时检索了较少的输出记录。

We drop a column using the Alter Table statement. We can leverage DROP COLUMN IF EXISTS as well in this alter statement. Suppose we want to drop a Country column from the Employee table. We use the following alter table statement.

我们使用Alter Table语句删除一列。 我们也可以在此alter语句中利用DROP COLUMN IF EXISTS。 假设我们要从Employee表中删除一个Country列。 我们使用以下alter table语句。

ALTER TABLE Employee DROP COLUMN IF EXISTS Country
GO

It is a single line and a straightforward query. Alternately, we use the following query using IF Exists. It seems to be more complicated than the earlier one. We should use the latest query syntax with the supported SQL Server versions.

它是单行和简单的查询。 或者,我们使用以下使用IF Exists的查询。 它似乎比以前的要复杂。 我们应该在支持SQL Server版本中使用最新的查询语法。

IF  EXISTS (SELECT 1 FROM sys.columns Where object_id = OBJECT_ID(N'Employee') 
    AND name = 'Country')
ALTER TABLE Employee DROP COLUMN Country
GO

结论 (Conclusion)

In this article, we explored two different versions of T-SQL IF Exists statements.

在本文中,我们探讨了T-SQL IF Exists语句的两个不同版本。

  • IF EXISTS in SQL 2014 or before

    如果SQL 2014或更早版本存在
  • DROP [Object] IF EXISTS in SQL Server 2016 or later

    SQL Server 2016或更高版本中存在DROP [Object] IF EXISTS

You should choose the syntax suitable for you. I would recommend the latest one (Drop [object[ IF Exists), if you are on SQL 2016 or later versions.

您应该选择适合您的语法。 如果您使用的是SQL 2016或更高版本,我建议使用最新版本(Drop [object [IF存在])。

翻译自: https://www.sqlshack.com/overview-of-the-t-sql-if-exists-statement-in-a-sql-server-database/

  • 0
    点赞
  • 0
    评论
  • 1
    收藏
  • 扫一扫,分享海报

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2022 CSDN 皮肤主题:编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值