Introduction to Dynamic SQL
The idea of using dynamic SQL is to execute SQL that will potentially generate and execute another SQL statement. While querying data, you might want to dynamically set columns you would like to query. On the other hand, you might want to parametrize tables on which you want to operate.
The first idea one might come up with is to use variables and set them as required column names or table names. However, such an approach is not supported by T-SQL.
DECLARE @tablename AS NVARCHAR(255) = N'dbo.Table';
SELECT *
FROM @tablename
-- this code will fail
T-SQL does not permit replacing many parts of code with variables. For example:
- Table name (
FROM
clause). - Database name (
USE
clause). - Column names (
SELECT
,WHERE
,GROUP BY
,HAVING
, andORDER BY
clauses). - Lists (
IN
,PIVOT
clauses).
Dynamic SQL Examples
The solution is to use dynamic SQL. But what it is in practice? In short, it is all about executing queries as strings.
An example of putting the query to the string:
DECLARE @query AS NVARCHAR(255) = N'SELECT * FROM dbo.Table';
SELECT @query AS query;
An example of executing the query, which is in the string (dynamic SQL):
DECLARE @query AS NVARCHAR(255) = N'SELECT * FROM dbo.Table';
EXEC(@query);
So as we can see, the EXEC
statement is used to dynamically execute the query that is stored in the nvarchar
variable. Let’s go back to the example with dynamically choosing which columns from which table we would like to query. The solution for this might look like this procedure:
IF OBJECT_ID('dbo.queryData', 'P') IS NOT NULL
DROP PROC dbo.queryData;
GO
CREATE PROC dbo.queryData
@tablename AS NVARCHAR(255)
,@columnnames AS NVARCHAR(255)
AS
BEGIN
DECLARE @SQLString AS NVARCHAR(MAX);
SET @SQLString = N'SELECT ' +@columnnames+N' FROM ' + @tablename;
EXEC(@SQLString);
END
...which you can execute like every other T-SQL procedure:
EXEC dbo.queryData 'dbo.Table', 'id, firstname, lastname, age'
As the last example, let’s create a procedure that will allow the user to query all data from the selected table with the selected predicate in the WHERE
clause.
USE TSQL2012;
GO
IF OBJECT_ID('dbo.queryData', 'P') IS NOT NULL
DROP PROC dbo.queryData;
GO
CREATE PROC dbo.queryData
@tablename AS NVARCHAR(255)
,@column AS NVARCHAR(255)
,@predicateOperator AS NVARCHAR(255)
,@predicateValue AS NVARCHAR(255)
AS
BEGIN
DECLARE @SQLString AS NVARCHAR(MAX);
SET @SQLString = N'SELECT * FROM ' + @tablename + N' WHERE ' + @column + @predicateOperator+@predicateValue ;
EXEC(@SQLString);
END
EXEC dbo.queryData 'dbo.Table', 'age','>=','18'
Dynamic SQL Gives You More Possibilities
In T-SQL, you might also execute dynamic SQL with the sp_executesql
stored procedure, which is an alternative to EXEC
. It allows you to use parameters: both input and output. It is generally better than EXEC
when it comes to performance because SQL Server might reuse cached execution plans.
Introduction to Dynamic SQL的更多相关文章
- [转]Dynamic SQL & Stored Procedure Usage in T-SQL
转自:http://www.sqlusa.com/bestpractices/training/scripts/dynamicsql/ Dynamic SQL & Stored Procedu ...
- MyBatis(3.2.3) - Dynamic SQL
Sometimes, static SQL queries may not be sufficient for application requirements. We may have to bui ...
- Can I use MyBatis to generate Dynamic SQL without executing it?
Although MyBatis was designed to execute the query after it builds it, you can make use of it's conf ...
- Get WMS Static GoodLocation By Dynamic SQL
Dynamic SQL Store Procedure: Note: use variable,you need convert varchar and as a variable,not direc ...
- mybatis Dynamic SQL
reference: http://www.mybatis.org/mybatis-3/dynamic-sql.html Dynamic SQL One of the most powerful fe ...
- mybatis-3 Dynamic SQL
Dynamic SQL One of the most powerful features of MyBatis has always been its Dynamic SQL capabilitie ...
- ABAP动态生成经典应用之Dynamic SQL Excute 程序
[转自http://blog.csdn.net/mysingle/article/details/678598]开发说明:在SAP的系统维护过程中,有时我们需要修改一些Table中的数据,可是很多Ta ...
- MySQL execute dynamic sql script.
SET @sql = (SELECT IF( (SELECT COUNT(*) FROM usher_network_log ) > 1000000, "SELECT 0", ...
- Spring mybatis源码篇章-NodeHandler实现类具体解析保存Dynamic sql节点信息
前言:通过阅读源码对实现机制进行了解有利于陶冶情操,承接前文Spring mybatis源码篇章-XMLLanguageDriver解析sql包装为SqlSource SqlNode接口类 publi ...
随机推荐
- java 变量 final 小结
通过查看hashCode发现,变量声明final后,不能修改,上级修改时候,重新获得对象hashCode变化 public static void main(String[] args) { // T ...
- Gulp压缩前端CS,JS,图片文件
Gulp 基于Node.js的前端构建工具,Gulp有许多插件(这里是插件),使用Gulp可以实现前端代码的编译(sass.less).压缩.图片的压缩等,当然主要是前端工程化,不过我目前只是需要压缩 ...
- ASP.NET Core MVC四种枚举绑定方式
前言 本节我们来讲讲在ASP.NET Core MVC又为我们提供了哪些方便,之前我们探讨过在ASP.NET MVC中下拉框绑定方式,这节我们来再来重点看看枚举绑定的方式,充分实现你所能想到的场景,满 ...
- 在vue2.0中引用element-ui组件库
element-ui是由饿了么团队开发的一套基于 Vue 2.0 的桌面端组件库. 官网:http://element.eleme.io/ 安装 npm i element-ui -S 引用完整的el ...
- 【中文版 | 论文原文】BERT:语言理解的深度双向变换器预训练
BERT:Pre-training of Deep Bidirectional Transformers for Language Understanding 谷歌AI语言组论文<BERT:语言 ...
- TCP/IP 协议 OSI七层协议
------------------你来自何处并不重要,重要的是你要去往何方,人生最重要的不是所站的位置,而是所去的方向.人只要不失去方向,就永远不会失去自己! day 27 # # -------- ...
- PHP开发web应用安全总结
XSS跨站脚本 概念:恶意攻击者往Web页面里插入恶意html代码,当用户浏览该页之时,嵌入其中Web里面的html代码会被执行,从而达到恶意用户的特殊目的. 危害: 盗取用户COOKIE信息. 跳转 ...
- Spring LocalVariableTableParameterNameDiscoverer获取方法的参数名
Spring LocalVariableTableParameterNameDiscoverer获取方法的参数名 问题:Java.lang.reflect 包中提供了很多方法,获取所有的方法,获取所有 ...
- Centos下启动和关闭MySQL
https://blog.csdn.net/gghh2015/article/details/78281585
- 关于Fatal error: Paletter image not supported by webp 报错
报错提示 Fatal error: Paletter image not supported by webp 原因是由于图片被非法编辑过(相对PHP来说)造成, 有可能是某些编辑图片的软件的格式与PH ...