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 (
FROMclause). - Database name (
USEclause). - Column names (
SELECT,WHERE,GROUP BY,HAVING, andORDER BYclauses). - Lists (
IN,PIVOTclauses).
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函数式编程和lambda表达式
为什么要使用函数式编程 函数式编程更多时候是一种编程的思维方式,是种方法论.函数式与命令式编程的区别主要在于:函数式编程是告诉代码你要做什么,而命令式编程则是告诉代码要怎么做.说白了,函数式编程是基于 ...
- Vue.js 系列教程 1:渲染,指令,事件
原文:intro-to-vue-1-rendering-directives-events 译者:nzbin 如果要我用一句话描述使用 Vue 的经历,我可能会说“它如此合乎常理”或者“它提供给我需要 ...
- mybatis源码- 反射模块一(跟着MyBatis学反射):类级别信息的封装
目录 1 JavaBean 规范 2 Reflector和ReflectorFactory 2.1 Reflector 属性 2.1.1 属性 2.1.2 Invoker 接口 2.2 Reflect ...
- 如何解决 Windows 实例出现身份验证错误及更正 CredSSP
阿里云上的ESC赠送1核2G服务器,安装windows server 2016 Datacenter 3389远程登录时提示错误信息,参考阿里文档:https://help.aliyun.com/kn ...
- Oracle 一个用户将表权限赋给另一个用户
原文地址:https://blog.csdn.net/u012129031/article/details/76218764 1.将用户user1的表权限赋给用户user2 select 'gra ...
- Sparse Principal Component Analysis
目录 背景: 部分符号 创新点 文章梗概 The LASSO AND THE ELASTIC NET 将PCA改造为回归问题 定理二 单个向量(无需进行SVD版本) 定理三 多个向量(无需进行SVD, ...
- Python 内置库 sys用法
sys模块功能众多,这边先学习几个常用的方法sys常见函数列表① sys.argv: 实现从程序外部向程序传递参数.其实sys.argv[]就是一个列表,里面的项为用户输入的参数,但是sys.argv ...
- PHP开发web应用安全总结
XSS跨站脚本 概念:恶意攻击者往Web页面里插入恶意html代码,当用户浏览该页之时,嵌入其中Web里面的html代码会被执行,从而达到恶意用户的特殊目的. 危害: 盗取用户COOKIE信息. 跳转 ...
- python 中的re模块,正则表达式
一.re模块 re模块中常用的方法. match: 默认从字符串开头开始匹配,re.match('fun', 'funny') 可以匹配出来 'fun' match(pattern, string, ...
- 接口工具之postman
在我们日常开发中,经常会对功能接口进行相应的测试.那么postman是一款不错的测试工具,因为平常使用的比较多,因此在这里简单记录一下,经常使用到的一些地方 简单的使用就不错介绍了, 基本流程: 新建 ...