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 ...
随机推荐
- 4939-Agent2-洛谷
传送门 emm... 这次没有原题了 (因为我懒) 就是一道很简单的树状数组 真的很简单很简单 只用到了一点点的差分 注意注意: 只用树状数组,不用差分会t掉的 所以.. 我不仅t了 还wa了 emm ...
- freopen
一定要记住哇 求求你了 记住吧 freopen("balabala.in","r",stdin); freopen("balabala.out&quo ...
- Python脱产8期 Day08 2019/4/22
一.三种字符串 1.普通字符串:u'以字符作为输出单位‘ #print(u‘abc’)#用于显示 2.二进制字符串:b'以字节作为输出单位’#用于传输 3.原义字符串:r‘以字符作为输出单位,原样输 ...
- python之xml 文件的读取方法
''' xml 文件的读取方法 ''' #!/usr/bin/env python # -*- coding: utf- -*- import xml.etree.ElementTree as ET ...
- python:利用logbook模块管理日志
日志管理作为软件项目的通用部分,无论是开发还是自动化测试过程中,都显得尤为重要. 最初是打算利用python的logging模块来管理日志的,后来看了些github及其他人的自动化框架设计,做了个比对 ...
- Linux死锁检测-Lockdep
关键词:LockDep.spinlock.mutex. lockdep是内核提供协助发现死锁问题的功能. 本文首先介绍何为lockdep,然后如何在内核使能lockdep,并简单分析内核lockdep ...
- 利用世界杯,读懂 Python 装饰器
Python 装饰器是在面试过程高频被问到的问题,装饰器也是一个非常好用的特性, 熟练掌握装饰器会让你的编程思路更加宽广,程序也更加 pythonic. 今天就结合最近的世界杯带大家理解下装饰器. 德 ...
- ASP.NET Core 与支付宝开发文档
一.目录 ASP.NET Core 2.0 使用支付宝PC网站支付 ASP.NET Core 2.0 支付宝当面付之扫码支付 常见使用问题解答 已有多个公司数个项目用本组件并上线,稳定使用. 二.项目 ...
- 一看就懂的Mybatis框架入门笔记
本篇为初学Mybatis框架时的入门笔记,整理发出 Spring集成Mybatis https://www.cnblogs.com/yueshutong/p/9381590.html SpringBo ...
- 10分钟开发 GPS 应用,了解一下
1 前言 在导师公司实习了半个月,参加的是尾气遥测项目,我的任务是开发GPS 的相关事情,从零到有的开发出了 GPS 的 Winform 应用,在这里记录一下开发过程和简要的描述一下将 GPS 数据提 ...