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 ...
随机推荐
- [MicroPython]TurnipBit开发板DIY自动浇水系统
1.实验目的: ?学习在PC机系统中扩展简单I/O 接口的方法 ?学习TurnipBit拼插编程 ?学习土壤传感器的工作原理以及使用方法 2.所需原器件: TurnipBit一块 TurnipBit扩 ...
- Maven入门指南⑦:Maven的生命周期和插件
一个完整的项目构建过程通常包括清理.编译.测试.打包.集成测试.验证.部署等步骤,Maven从中抽取了一套完善的.易扩展的生命周期.Maven的生命周期是抽象的,其中的具体任务都交由插件来完成.Mav ...
- face recognition[MobiFace]
本文来自<MobiFace: A Lightweight Deep Learning Face Recognition on Mobile Devices>,时间线为2018年11月.是作 ...
- ZOJ - 2423-Fractal
A fractal is an object or quantity that displays self-similarity, in a somewhat technical sense, on ...
- 基于 Django2 实现邮箱注册登录功能
1. 开发环境 Python 3.6.5 Django 2.2 2. 项目功能 用户登录 邮箱注册 图形验证码 找回密码 修改密码 用户退出 3. 项目创建 首先创建项目: django-admin ...
- SQL Server-索引故事的遥远由来,原来是这样的?(二十八)
前言 前段时间工作比较忙,每天回来也时不时去写有关ASP.NET Core的文章,无论是项目当中遇到的也好还是自学的也好都比较严谨的去叙述,喜欢分享,乐于分享这是我一直以来的态度,当然从中也会有些许错 ...
- 聊聊我是如何自学Java两年的(上)
没啥经验,说说心路历程吧~~ 过两天就9月1号了,正式成为大三生,没错,我就是如此嫩~~~ 萌芽在初中 初一的时候,电视广告结尾都会放一句,我们的网站是.....于是心里琢磨,网站是怎么建的呢?我可以 ...
- Pytest+Allure定制报告
前言: 最近在研究接口自动化的框架,好的测试报告在整个测试框架起到至关重要的部分.终于被我发现一个超好用的报告框架,不仅报告美观,而且方便CI集成. 就是它,就是它:Allure Test Repor ...
- from bs4 import BeautifulSoup 报错
一: BeautifulSoup的安装: 下载地址:https://www.crummy.com/software/BeautifulSoup/bs4/download/4.6/ 下载后,解压缩,然后 ...
- ElasticSearch聚合
前言 说完了ES的索引与检索,接着再介绍一个ES高级功能API – 聚合(Aggregations),聚合功能为ES注入了统计分析的血统,使用户在面对大数据提取统计指标时变得游刃有余.同样的工作,你在 ...