Home Database Mysql Tutorial SQL Server执行动态SQL正确方式

SQL Server执行动态SQL正确方式

Jun 07, 2016 pm 04:17 PM
server dynamic implement Way correct

SQL Server执行动态SQL的话,应该如何实现呢?下面就为您介绍SQL Server执行动态SQL两种正确方式,希望可以让您对SQL Server执行动态SQL有更深的了解. 动态SQL:code that is executed dynamically.它一般是根据用户输入或外部条件动态组合的SQL语句块.动态SQL能

  SQL Server执行动态SQL的话,应该如何实现呢?下面就为您介绍SQL Server执行动态SQL两种正确方式,希望可以让您对SQL Server执行动态SQL有更深的了解.

  动态SQL:code that is executed dynamically.它一般是根据用户输入或外部条件动态组合的SQL语句块.动态SQL能灵活的发挥SQL强大的功能、方便的解决一些其它方法难以解决的问题.相信使用过动态SQL的人都能体会到它带来的便利,然而动态SQL有时候在执行性能(效率)上面不如静态SQL,而且使用不恰当,往往会在安全方面存在隐患(SQL 注入式攻击).

  动态SQL可以通过EXECUTE 或SP_EXECUTESQL这两种方式来执行.

  EXECUTE

  执行 Transact-SQL 批中的命令字符串、字符串或执行下列模块之一:系统存储过程、用户定义存储过程、标量值用户定义函数或扩展存储过程.SQL Server 2005 扩展了 EXECUTE 语句,以使其可用于向链接服务器发送传递命令.此外,还可以显式设置执行字符串或命令的上下文

  SP_EXECUTESQL

  执行可以多次重复使用或动态生成的 Transact-SQL 语句或批处理.Transact-SQL 语句或批处理可以包含嵌入参数.在批处理、名称作用域和数据库上下文方面,SP_EXECUTESQL 与 EXECUTE 的行为相同.SP_EXECUTESQL stmt 参数中的 Transact-SQL 语句或批处理在执行 SP_EXECUTESQL 语句时才编译.随后,将编译 stmt 中的内容,并将其作为执行计划运行.该执行计划独立于名为 SP_EXECUTESQL 的批处理的执行计划.SP_EXECUTESQL 批处理不能引用调用 SP_EXECUTESQL 的批处理中声明的变量.SP_EXECUTESQL 批处理中的本地游标或变量对调用 SP_EXECUTESQL 的批处理是不可见的.对数据库上下文所作的更改只在 SP_EXECUTESQL 语句结束前有效.

  如果只更改了语句中的参数值,则 sp_executesql 可用来代替存储过程多次执行 Transact-SQL 语句.因为 Transact-SQL 语句本身保持不变,仅参数值发生变化,所以 SQL Server 查询优化器可能重复使用首次执行时所生成的执行计划.

  一般来说,我们推荐、优先使用SP_EXECUTESQL来执行动态SQL,一方面它更加灵活、可以有输入输出参数、另外一方面,查询优化器更有可能重复使用执行计划,提高执行效率.还有就是使用SP_EXECUTESQL能提高安全性;当然也不是说要完全摈弃EXECUTE,在特定场合下,EXECUTE比SP_EXECUTESQL更方便些,比如动态SQL字符串是VARCHAR类型、不是NVARCHAR类型.SP_EXECUTESQL 只能执行是Unicode的字符串或是可以隐式转换为ntext的常量或变量、而EXECUTE则两种类型的字符串都能执行.

  下面我们来对比看看EXECUTE 和SP_EXECUTESQL的一些细节地方.

  EXECUTE(N'SELECT * FROM Groups') --执行成功

  EXECUTE('SELECT * FROM Groups') --执行成功

  SP_EXECUTESQL N'SELECT * FROM Groups'; --执行成功

  SP_EXECUTESQL 'SELECT * FROM Groups' --执行出错

  Summary:EXECUTE 可以执行非Unicode或Unicode类型的字符串常量、变量.而SP_EXECUTESQL只能执行Unicode或可以隐式转换为ntext的字符串常量、变量.

  DECLARE @GroupName VARCHAR(50);SET@GroupName ='SuperAdmin';

  EXECUTE('SELECT * FROM Groups WHERE GroupName=''' + SUBSTRING(@GroupName, 1,5) + ''''); --'SUBSTRING' 附近有语法错误.

  DECLARE @Sql VARCHAR(200);

  DECLARE @GroupName VARCHAR(50);SET@GroupName ='SuperAdmin';

  SET@Sql='SELECT * FROM Groups WHERE GroupName=''' + SUBSTRING(@GroupName, 1,5) + ''''

  --PRINT @Sql;EXECUTE(@Sql);

  Summary:EXECUTE 括号里面只能是字符串变量、字符串常量、或它们的连接组合,不能调用其它一些函数、存储过程等. 如果要使用,则使用变量组合,如上所示.

  DECLARE @Sql VARCHAR(200);

  DECLARE @GroupName VARCHAR(50);SET@GroupName ='SuperAdmin';

  SET@Sql='SELECT * FROM Groups WHEREGroupName=@GroupName'

  --PRINT @Sql;EXECUTE(@Sql); --出错:必须声明标量变量 “@GroupName”.SET@Sql='SELECT * FROM Groups WHERE GroupName=' + QUOTENAME(@GroupName, '''')

  EXECUTE(@Sql); --正确:

  DECLARE @Sql NVARCHAR(200);

  DECLARE @GroupName NVARCHAR(50);SET@GroupName ='SuperAdmin';

  SET@Sql='SELECT * FROM Groups WHEREGroupName=@GroupName'

  PRINT @Sql;

  EXEC SP_EXECUTESQL @Sql,N'@GroupNameNVARCHAR',@GroupName

  查询出来没有结果,没有声明参数长度.

  DECLARE @Sql NVARCHAR(200);

  DECLARE @GroupName NVARCHAR(50);SET@GroupName ='SuperAdmin';

  SET@Sql ='SELECT * FROM Groups WHERE GroupName=@GroupName'

  PRINT @Sql;

  EXEC SP_EXECUTESQL @Sql, N'@GroupName NVARCHAR(50)',@GroupName

  Summary:动态批处理不能访问定义在批处理里的局部变量 . SP_EXECUTESQL 可以有输入输出参数,比EXECUTE灵活.

  下面我们来看看EXECUTE , SP_EXECUTESQL的执行效率,首先把缓存清除执行计划,然后改变用@GroupName值SuperAdmin、CommonUser、CommonAdmin分别执行三次.然后看看其使用缓存的信息

  DBCC FREEPROCCACHE;

  DECLARE @Sql VARCHAR(200);

  DECLARE @GroupName VARCHAR(50);SET@GroupName ='SuperAdmin'; --'CommonUser', 'CommonAdmin'

  SET@Sql ='SELECT * FROM Groups WHERE GroupName=' + QUOTENAME(@GroupName, '''')

  EXECUTE(@Sql); SELECTcacheobjtype, objtype, usecounts, sql

  FROM sys.syscacheobjects

  WHERE sql NOTLIKE '%cache%'

  ANDsql NOTLIKE '%sys.%';

  依葫芦画瓢,接着我们看看SP_EXECUTESQL的执行效率

  DBCC FREEPROCCACHE;

  DECLARE @Sql NVARCHAR(200);

  DECLARE @GroupName NVARCHAR(50);SET@GroupName ='SuperAdmin'; --'CommonUser', 'CommonAdmin'

  SET@Sql ='SELECT * FROM Groups WHERE GroupName=@GroupName'

  EXECUTESP_EXECUTESQL @Sql, N'@GroupName NVARCHAR(50)', @GroupName;

  SELECTcacheobjtype, objtype, usecounts, sql

  FROM sys.syscacheobjects

  WHERE sql NOTLIKE '%cache%'

  ANDsql NOTLIKE '%sys.%';

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Python script to be executed every 5 minutes Python script to be executed every 5 minutes Sep 10, 2023 pm 03:33 PM

Automation and task scheduling play a vital role in streamlining repetitive tasks in software development. Imagine there is a Python script that needs to be executed every 5 minutes, such as getting data from an API, performing data processing, or sending periodic updates. Running scripts manually so frequently can be time-consuming and error-prone. This is where task scheduling comes in. In this blog post, we will explore how to schedule a Python script to execute every 5 minutes, ensuring it runs automatically without manual intervention. We will discuss different methods and libraries that can be used to achieve this goal, allowing you to automate tasks efficiently. An easy way to run a Python script every 5 minutes using the time.sleep() function is to utilize tim

Convert VirtualBox fixed disk to dynamic disk and vice versa Convert VirtualBox fixed disk to dynamic disk and vice versa Mar 25, 2024 am 09:36 AM

When creating a virtual machine, you will be asked to select a disk type, you can select fixed disk or dynamic disk. What if you choose fixed disks and later realize you need dynamic disks, or vice versa? Good! You can convert one to the other. In this post, we will see how to convert VirtualBox fixed disk to dynamic disk and vice versa. A dynamic disk is a virtual hard disk that initially has a small size and grows in size as you store data in the virtual machine. Dynamic disks are very efficient at saving storage space because they only take up as much host storage space as needed. However, as disk capacity expands, your computer's performance may be slightly affected. Fixed disks and dynamic disks are commonly used in virtual machines

How to convert dynamic disk to basic disk on Windows 11 How to convert dynamic disk to basic disk on Windows 11 Sep 23, 2023 pm 11:33 PM

If you want to convert a dynamic disk to a basic disk in Windows 11, you should create a backup first as the process will erase all data in it. Why should you convert dynamic disk to basic disk in Windows 11? According to Microsoft, dynamic disks have been deprecated from Windows and their use is no longer recommended. Additionally, Windows Home Edition does not support dynamic disks, so you will not be able to access these logical drives. If you want to combine more disks into a larger volume, it is recommended to use Basic Disks or Storage Spaces. In this article, we will show you how to convert dynamic disk to basic disk on Windows 11 How to convert dynamic disk to basic disk in Windows 11? In the beginning

How to Get Live Tiles on the Desktop and Start Menu in Windows 11 How to Get Live Tiles on the Desktop and Start Menu in Windows 11 Apr 14, 2023 pm 05:07 PM

Imagine you are looking for something on your system but are not sure which application to open or select. This is where the Live Tiles feature comes into play. A live tile for any supported application can be added to the desktop or Windows system's Start menu, with its tiles changing frequently. LiveTiles make application widgets come alive in a very pleasing way. Not just for its appearance, but even for convenience. Suppose you are using whatsapp or facebook application on your system, wouldn't it be convenient if the number of notifications is displayed on the application icon? This is possible if any such supported app is added as a live tile. Let’s see how to do it in Windows

How to use Python for scripting and execution in Linux How to use Python for scripting and execution in Linux Oct 05, 2023 am 11:45 AM

How to use Python to write and execute scripts in Linux In the Linux operating system, we can use Python to write and execute various scripts. Python is a concise and powerful programming language that provides a wealth of libraries and tools to make scripting easier and more efficient. Below we will introduce the basic steps of how to use Python for script writing and execution in Linux, and provide some specific code examples to help you better understand and use it. Install Python

How to install, uninstall, and reset Windows server backup How to install, uninstall, and reset Windows server backup Mar 06, 2024 am 10:37 AM

WindowsServerBackup is a function that comes with the WindowsServer operating system, designed to help users protect important data and system configurations, and provide complete backup and recovery solutions for small, medium and enterprise-level enterprises. Only users running Server2022 and higher can use this feature. In this article, we will explain how to install, uninstall or reset WindowsServerBackup. How to Reset Windows Server Backup If you are experiencing problems with your server backup, the backup is taking too long, or you are unable to access stored files, then you may consider resetting your Windows Server backup settings. To reset Windows

How to disable dynamic display of folders and files to prevent quick access in Windows 10 and 11? How to disable dynamic display of folders and files to prevent quick access in Windows 10 and 11? May 06, 2023 pm 04:58 PM

Microsoft introduced Quick Access in Windows 10 and retained the feature in the recently released Windows 11 operating system. Quick Access replaces the Favorites system in File Explorer. One of the core differences between the two features is that Quick Access adds a dynamic component to its list. Some folders appear permanently, while others appear based on usage. Fixed folders are displayed with a pin icon, while dynamic folders do not have such an icon. You can see a comparison between My Favorites and Quick Access here for more details. Quick Access is more powerful than Favorites, but dynamic folder lists add an element of clutter to it. Files that are useless or should not be highlighted in File Explorer may be displayed

How to create a dynamic image carousel using HTML, CSS and jQuery How to create a dynamic image carousel using HTML, CSS and jQuery Oct 25, 2023 am 10:09 AM

How to use HTML, CSS and jQuery to create a dynamic image carousel. In website design and development, image carousel is a frequently used function for displaying multiple images or advertising banners. Through the combination of HTML, CSS and jQuery, we can achieve a dynamic image carousel effect, adding vitality and appeal to the website. This article will introduce how to use HTML, CSS and jQuery to create a simple dynamic image carousel, and provide specific code examples. Step 1: Set up HTML junction

See all articles