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错误消息,如下所示。

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.

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

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.objectsWHERE object_id = OBJECT_ID(N'dbo.stpGetAllMembers')
)BEGINPRINT 'Stored procedure already exists';
END;

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

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

IF EXISTS
(SELECT *FROM sys.objectsWHERE object_id = OBJECT_ID(N'dbo.stpGetAllMembers_1')
)BEGINPRINT 'Stored procedure already exists';
END;

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.objectsWHERE object_id = OBJECT_ID(N'dbo.stpGetAllMembers')
)BEGINDROP 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表是否存在,如果存在,则将其删除。

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并输入。

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

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

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;

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 stpGetAllMembersPRINT '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
ASSELECT 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/

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

  1. SQL Server数据库中批量导入数据的四种方法总结

    在软件项目实施的时候,数据导入一直是项目人员比较头疼的问题.其实,在SQL Server中集成了很多成批导入数据的方法.有些项目实施顾问头疼的问题,在我们数据库管理员眼中,是小菜一碟.现在的重点就是, ...

  2. SQL Server数据库中批量导入数据

    在软件项目实施的时候,数据导入一直是项目人员比较头疼的问题.其实,在SQL Server中集成了很多成批导入数据的方法.有些项目实施顾问头疼的问题,在我们数据库管理员眼中,是小菜一碟.现在的重点就是, ...

  3. 在ASP.NET中将图片存储到Sql Server数据库中

    在ASP.NET中将图片存储到Sql Server数据库中 http://hi.baidu.com/rayshow/blog/item/360e8ff9662c8b5a252df268.html 索引 ...

  4. 清空SQL Server数据库中所有表数据的方法(转)

    清空SQL Server数据库中所有表数据的方法 其实删除数据库中数据的方法并不复杂,为什么我还要多此一举呢,一是我这里介绍的是删除数据库的所有数据,因为数据之间可能形成相互约束关系,删除操作可能陷入 ...

  5. mysql raiserror_RAISERROR在SQL Server数据库中的用法

    raiserror  是由单词 raise error 组成 raise  增加; 提高; 提升 raiserror 的作用: raiserror 是用于抛出一个错误.[ 以下资料来源于sql ser ...

  6. SQL Server数据库中、获得刚插入新记录的自动ID号

    以下的文章主要是介绍在SQL Server数据库中正确获得刚插入一条新记录的自动ID号的实际操作过程,下面就是文章对其的主要内容的具体描述,望大家在浏览之后会对其有更深的了解. 使用[IDENT_CU ...

  7. 从sqlserver中数据写入mysql_[SQL Server]SQL Server数据库中如何返回INSERT INTO语句插入/写入数据后的记录值(比如ID等)?...

    问题描述 SQL Server数据库中,有时候当我们使用INSERT INTO语句写入数据后,需要返回写入数据对应的自增ID或者GUID,以便根据此记录进行后续的操作.那么SQL语句如何实现返回记录值 ...

  8. SQL Server数据库中使用sql脚本删除指定表的列

    在SQL Server数据库中删除某一列,使用数据库管理工具直接可视化操作是很简单的,但是如果要用sql脚本呢?可能你会说很简单,直接用 ALTER TABLE [要删除的字段所在的表名] DROP ...

  9. 浅析SQL Server数据库中的伪列以及伪列的含义

    浅析SQL Server数据库中的伪列以及伪列的含义 原文:浅析SQL Server数据库中的伪列以及伪列的含义 本文出处:http://www.cnblogs.com/wy123/p/6833116 ...

  10. 通过VB向SQL Server数据库中录入数据

    Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 一.数据录入 通过VB向SQL Se ...

最新文章

  1. 程序员必读10本算法书推荐
  2. 从数理统计简史中看正态分布的历史由来
  3. 重写 button 的创建方法
  4. java使用jstat分析内存
  5. JAVA程序员面试必知32个知识点
  6. Lenovo ThinkPad 3999元型号发布 并不属于SL系列
  7. WPF编程学习 —— 样式
  8. exchange 2010 允许 relay设定
  9. 【转】Boost库概述
  10. 多语言页面语言标签的使用更适合推广
  11. 深度学习论文和开源代码
  12. cpu的用户态和内核态和内存的用户空间内核空间
  13. 20191209每日一句
  14. 大数据的十大应用领域
  15. vc使用默认的浏览器打开网页
  16. 从子域名看百度,新浪,搜狐,QQ和网易
  17. win10网络不出现计算机列表,win10笔记本WiFi网络列表不显示内容的解决方法
  18. 旧 Mac、PC 别扔,变身 Chromebook 了解一下
  19. 计算机软件工程专业心得,非计算机专业学软件工程的一点心得体会
  20. 如何下载生物数据(四):SRA数据下载

热门文章

  1. android build.gradle的repositories设置
  2. 微信小程序 数组索引 data-“”解释
  3. Jmeter中的变量(三)
  4. BAPI:KBPP_EXTERN_UPDATE_CO, TCODE:CJ30/CJ40 第二部分
  5. Promise方法汇总
  6. 喝酒、吸烟和喝茶三者相对而言,哪个对身体有益?哪个对身体有害?
  7. htaccess文件是什么
  8. 电脑ip4和ip6的怎么选择?
  9. 基金定投十年不止赢不止损会怎么样?
  10. 离婚前一晚是什么心情呢?