使用sp_executesql存储过程执行动态SQL查询

使用sp_executesql存储过程执行动态SQL查询Thesp_executesqlstoredprocedureisusedtoexecutedynamicSQLqueriesinSQLServer.AdynamicSQLqueryisaqueryinstringformat.ThereareseveralscenarioswhereyouhaveanSQLq…

大家好,又见面了,我是你们的朋友全栈君。

The sp_executesql stored procedure is used to execute dynamic SQL queries in SQL Server. A dynamic SQL query is a query in string format. There are several scenarios where you have an SQL query in the form of a string.

sp_executesql存储过程用于在SQL Server中执行动态SQL查询。 动态SQL查询是字符串格式的查询。 在几种情况下,您都可以使用字符串形式SQL查询。

For example, if a user wants to search for a product by name, he will enter the name of the product in a search box on the website. The product name, which is in the form of a string will be concatenated with a SELECT query to form another string. These types of queries need to be executed dynamically because different users will search for different product names and so a query will need to be generated dynamically depending on the product name.

例如,如果用户要按名称搜索产品,则将在网站上的搜索框中输入产品名称。 字符串形式的产品名称将与SELECT查询连接在一起以形成另一个字符串。 这些类型的查询需要动态执行,因为不同的用户将搜索不同的产品名称,因此将需要根据产品名称动态生成查询。

Now that you understand what dynamic SQL is, let’s see how the sp_executesql stored procedure can be used to execute dynamic SQL queries.

现在您了解了什么是动态SQL,让我们看看如何使用sp_executesql存储过程执行动态SQL查询。

Let’s first create some dummy data that we can use to execute the examples in this article.

首先,让我们创建一些虚拟数据,以用于执行本文中的示例。

创建虚拟数据 (Creating dummy data)

The following script creates a dummy database named BookStore with one table i.e. Books. The Books table has four columns: id, name, category, and price:

以下脚本使用一个表(即Books)创建一个名为BookStore的虚拟数据库。 Books表包含四列: idnamecategoryprice

CREATE Database BookStore;
GO
USE BookStore;
CREATE TABLE Books
(
id INT,
name VARCHAR(50) NOT NULL,
category VARCHAR(50) NOT NULL,
price INT NOT NULL
)

Let’s now add some dummy records in the Books table:

现在让我们在Books表中添加一些虚拟记录:

USE BookStore
 
INSERT INTO Books
    
VALUES
(1, 'Book1', 'Cat1', 1800),
(2, 'Book2', 'Cat2', 1500),
(3, 'Book3', 'Cat3', 2000),
(4, 'Book4', 'Cat4', 1300),
(5, 'Book5', 'Cat5', 1500),
(6, 'Book6', 'Cat6', 5000),
(7, 'Book7', 'Cat7', 8000),
(8, 'Book8', 'Cat8', 5000),
(9, 'Book9', 'Cat9', 5400),
(10, 'Book10', 'Cat10', 3200)

The above script adds 10 dummy records in the Books table.

上面的脚本在Books表中添加了10条虚拟记录。

使用sp_executesql存储过程 (Working with the sp_executesql stored procedure)

As I mentioned earlier, the sp_executesql stored procedure is used to execute dynamic SQL queries that are in the form of a string. Let’s see this in action.

如前所述,sp_executesql存储过程用于执行字符串形式的动态SQL查询。 让我们看看实际情况。

Run the following script:

运行以下脚本:

DECLARE @SQL_QUERY NVARCHAR(128)
SET @SQL_QUERY = N'SELECT id, name, price FROM Books WHERE price > 4000 '
EXECUTE sp_executesql @SQL_QUERY

In the script above, we declare a variable @SQL_QUERY and initialize it with a string query that returns the id, name, and price from the Books table where the price is greater than 4,000.

在上面的脚本中,我们声明一个变量@SQL_QUERY并使用字符串查询对其进行初始化,该字符串查询从Books表中返回价格大于4,000的id,名称和价格。

Next, we execute the sp_executesql stored procedure via the EXECUTE command. To execute a dynamic SQL query that is in the string format, you simply have to pass the string containing the query to the sp_executesql query.

接下来,我们通过EXECUTE命令执行sp_executesql存储过程。 若要执行字符串格式的动态SQL查询,只需要将包含查询的字符串传递给sp_executesql查询。

It is important to mention that the string should be in the Unicode format before the sp_executesql stored procedure executes it. This is the reason we put ‘N’ at the beginning of the string containing the @SQL_QUERY variable. The ‘N’ converts the query string into the Unicode string format. Here is the output of the above script:

值得一提的是,在sp_executesql存储过程执行该字符串之前,该字符串应为Unicode格式。 这就是我们将’N’放在包含@SQL_QUERY变量的字符串开头的原因。 “ N”将查询字符串转换为Unicode字符串格式。 这是上面脚本的输出:

Output of simple sp_executesql statement

In real life database queries, the filter or condition is passed by the users. For instance, a user may search books within a specific search limit. In that case, the SELECT query remains the same, only the WHERE condition is changed. It is convenient to store the WHERE clause in a separate string variable and then concatenate the SELECT condition with the WHERE clause to create the final query. This is shown in the following example:

在现实生活中的数据库查询中,过滤器或条件由用户传递。 例如,用户可以在特定搜索限制内搜索书籍。 在这种情况下,SELECT查询保持不变,只改变WHERE条件。 将WHERE子句存储在单独的字符串变量中,然后将SELECT条件与WHERE子句连接起来以创建最终查询是很方便的。 在下面的示例中显示:

DECLARE @CONDITION NVARCHAR(128)
DECLARE @SQL_QUERY NVARCHAR (MAX)
SET @CONDITION = 'WHERE price > 5000'
SET @SQL_QUERY =N'SELECT id, name, price FROM Books '+ @CONDITION
EXECUTE sp_executesql @SQL_QUERY

Here in the script above, we declare two variables: @CONDITION and @SQL_QUERY. The @CONDITION variable contains the WHERE clause in string format whereas the @SQL_QUERY contains the SELECT query. Next, these two variables are concatenated and passed to the sp_executesql stored procedure. Here is the output:

在上面的脚本中,我们声明两个变量:@CONDITION和@SQL_QUERY。 @CONDITION变量包含字符串格式的WHERE子句,而@SQL_QUERY包含SELECT查询。 接下来,将这两个变量连接起来并传递给sp_executesql存储过程。 这是输出:

Output of more complex sp-executesql statement

The output shows all the books where the price is greater than 5,000.

输出显示价格大于5,000的所有书籍。

将参数传递给sp_executesql存储过程 (Passing parameters to sp_executesql stored procedure)

You can also pass parameters to the sp_executesql stored procedure. This is particularly handy when you don’t know the values used to filter records before runtime. To execute a sp_executesql stored procedure with parameters, you need to perform the following steps:

您还可以将参数传递给sp_executesql存储过程。 当您在运行时不知道用于过滤记录的值时,这特别方便。 若要执行带有参数的sp_executesql存储过程,您需要执行以下步骤:

  1. First, you need to create a variable that is going to store the list of parameters

    首先,您需要创建一个变量,该变量将存储参数列表

  2. Next, in the query string, you need to pass the names of the parameters

    接下来,在查询字符串中,您需要传递参数名称

  3. Finally, you need to pass the query, the variable that contains a list of parameters and the actual parameters along with their values to the sp_executesql stored procedure

    最后,您需要将查询,包含参数列表和实际参数及其值的变量传递给sp_executesql存储过程。

Look at the following example:

看下面的例子:

DECLARE @CONDITION NVARCHAR(128)
DECLARE @SQL_QUERY NVARCHAR (MAX)
DECLARE @PARAMS NVARCHAR (1000)
SET @CONDITION = 'WHERE price > @LowerPrice AND price < @HigherPrice'
SET @SQL_QUERY = N'SELECT id, name, price FROM Books '+ @CONDITION
SET @PARAMS = '@LowerPrice INT, @HigherPrice INT'
EXECUTE sp_executesql @SQL_QUERY ,@PARAMS, @LowerPrice = 3000, @HigherPrice = 6000

In the script above, we create three variables: @CONDITION, @SQL_QUERY, and @PARAMS. The @PARAMS variable is a variable that stores the list of parameters that we will use in the string query format.

在上面的脚本中,我们创建三个变量:@ CONDITION,@ SQL_QUERY和@PARAMS。 @PARAMS变量是一个变量,它存储将在字符串查询格式中使用的参数列表。

If you look at the value of the @CONDITION variable, it contains a WHERE clause with two parameters: @LowerPrice and @HigherPrice. To specify a parameter inside a string query, you simply have to prefix with the ‘@’ operator before the name of the parameter. Here the @LowerPrice parameter is used to set the lower bound for the price of books whereas the @HigherPrice sets the higher bound for the value in the price column of the BookStore table.

如果您查看@CONDITION变量的值,则该变量包含带有两个参数的WHERE子句:@LowerPrice和@HigherPrice。 要在字符串查询中指定参数,您只需在参数名称前加上“ @”运算符即可。 在这里,@LowerPrice参数用于设置书籍价格的下限,而@HigherPrice设置BookStore表的price列中的值的上限。

Next, while executing the sp_executesql stored procedure, the @SQL_QUERY variable which contains the string query is passed along with the @PARAMS variable which contains the parameter list. The parameter names i.e. @LowerPrice and @HigherPrice are also passed to the sp_executesql stored procedure along with the values 3,000 and 6,000 respectively. In the output, you will see the records where the price is between 3,000 and 6,000 as shown below:

接下来,在执行sp_executesql存储过程时,将包含字符串查询的@SQL_QUERY变量与包含参数列表的@PARAMS变量一起传递。 参数名称(即@LowerPrice和@HigherPrice)也分别与值3,000和6,000一起传递到sp_executesql存储过程。 在输出中,您将看到价格在3,000到6,000之间的记录,如下所示:

Output of parameterised sp-executesql example

结论 (Conclusion)

This article explains the functionality of sp_executesql stored procedure which is used to execute dynamic SQL queries. The article shows how to execute the SELECT query in the form of a string via sp_executesql stored procedure. You also saw how to pass parameters to the sp_executesql stored procedure in order to execute queries where values are passed at runtime.

本文介绍了用于执行动态SQL查询的sp_executesql存储过程的功能。 本文介绍如何通过sp_executesql存储过程以字符串形式执行SELECT查询。 您还看到了如何将参数传递给sp_executesql存储过程,以便执行在运行时传递值的查询。

翻译自: https://www.sqlshack.com/using-sp_executesql-stored-procedure-for-executing-dynamic-sql-queries/

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/143296.html原文链接:https://javaforall.net

(0)
上一篇 2022年5月21日 下午11:00
下一篇 2022年5月21日 下午11:00


相关推荐

  • 计算机初级基础知识教程,计算机基础知识教程 适合初学者的计算机入门知识…

    计算机初级基础知识教程,计算机基础知识教程 适合初学者的计算机入门知识…初学者在接触计算机时认为计算机非常的难 但事实上计算机有简单有困难 而对于初学者 自然就要从简单的开始学起 所以今天小编就来说一说适合初学者的一些入门知识 希望对大家能够有所帮助 计算机基础知识教程 适合初学者的入门知识 1 在记事本中自动记录文件的打开时间在记事本中 我们可以记录每次打开某个文本文件的时间 方法为 在该文件的第一行输入 LOG 注意 必须大写 然后换行开始正文 这样在每次

    2026年3月26日
    1
  • 不可错过的手机APP常见8种界面导航样式

    不可错过的手机APP常见8种界面导航样式

    2022年2月1日
    50
  • document cookie用法[通俗易懂]

    document cookie用法[通俗易懂]cookie概述曾经利用一个不变的框架来存储购物栏数据,而商品显示页面是不断变化的,尽管这样能达到一个模拟全局变量的功能,但并不严谨。例如在导航框架页面内右击,单击快捷菜单中的【刷新】命令,则所有的JavaScript变量都会丢失。因此,要实现严格的跨页面全局变量,这种方式是不行的,JavaScript中的另一个机制:cookie,则可以达到真正全局变量的要求。 cookie是浏

    2022年7月11日
    18
  • Navicat 连接MySQL数据库出现错误:2059

    Navicat 连接MySQL数据库出现错误:2059Navicat连接MySQL数据库出现错误:2059-authenticationplugin’caching_sha2_password’的解决方法

    2022年8月31日
    3
  • 性能测试相关书籍

    性能测试相关书籍

    2021年8月8日
    73
  • linux下crontab命令的用法,linux 定时任务crontab用法详解「建议收藏」

    linux下crontab命令的用法,linux 定时任务crontab用法详解「建议收藏」linux定时任务crontab用法详解linux中crontab命令用于设置周期性被执行的指令,该命令从标准输入设备读取指令,并将其存放于“crontab”文件中,以供之后读取和执行。cron系统调度进程。可以使用它在每天的非高峰负荷时间段运行作业,或在一周或一月中的不同时段运行。cron是系统主要的调度进程,可以在无需人工干预的情况下运行作业。crontab命令允许用户提交、编辑或删除相应…

    2022年8月24日
    7

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号