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 ...
随机推荐
- 2018-2019-3《Java程序设计》第二周学习总结
学号20175329 2018-2019-3<Java程序设计>第二周学习总结 教材学习内容总结 第二三章与我们所学习的C语言有很多的相似点,在这里我想主要就以我所学习的效果来讨 ...
- Item 25: 对右值引用使用std::move,对universal引用则使用std::forward
本文翻译自<effective modern C++>,由于水平有限,故无法保证翻译完全正确,欢迎指出错误.谢谢! 博客已经迁移到这里啦 右值引用只能绑定那些有资格被move的对象上去.如 ...
- 【开源】Westore Cloud 发布- 没后端没SQL没DBA,只需 javascript 开发云端小程序
Westore Cloud - 隐形云,NoBackEnd,NoSql,HiddenDB 好的设计便是感觉不到设计的存在 开发小程序,但是:没有后端!没有运维!没有 DBA!没有域名!没有证书!没有钱 ...
- spark 2.3 导致driver OOM的一个SparkPlanGraphWrapper源码的bug
背景 长话短说,我们部门一个同事找到我,说他的spark 2.3 structured streaming程序频繁报OOM,从来没有坚持过超过三四天的,叫帮看一下. 这种事情一般我是不愿意看的,因为大 ...
- 配置linux-Fedora系统下iptables防火墙
参考地址:https://blog.csdn.net/zhangjingyi111/article/details/78902820 本篇文章为实验课过程记录,较为简略. 1.查看系统是否安装ipta ...
- 学习用Node.js和Elasticsearch构建搜索引擎(3):使用curl命令操作elasticsearch
使用Elasticsearch不免要提到curl工具,curl是利用URL语法在命令行方式下工作的开源文件传输工具.官网地址:https://curl.haxx.se/ 因为elasticsearch ...
- codeforces#1090 D. New Year and the Permutation Concatenation(打表找规律)
题意:给出一个n,生成n的所有全排列,将他们按顺序前后拼接在一起组成一个新的序列,问有多少个长度为n的连续的子序列和为(n+1)*n/2 题解:由于只有一个输入,第一感觉就是打表找规律,虽然表打出来了 ...
- openstack-KVM-存储配置
一.块存储设备 1.存储设备类型 IDE SCSI 软盘 U盘 virtio磁盘(KVM使用类型) 2.查看存储设备 lspci | grep IDE lspci | grep SCSI lspci ...
- WCF上传下载文件
思路:上传时将要上传的文件流提交给服务器端 下载时只需要将服务器上的流返回给客户端即可 1.契约,当需要传递的数量多于一个时就需要通过messagecontract来封装起来 这里分别实现了上传和下载 ...
- CMD管道命令使用
Windows netstat 查看端口.进程占用 开始--运行--cmd 进入命令提示符 输入netstat -ano 即可看到所有连接的PID 之后在任务管理器中找到这个PID所对应的程序如果任务 ...