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 (SELECTWHEREGROUP BYHAVING, and ORDER BY clauses).
  • Lists (INPIVOT 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的更多相关文章

  1. [转]Dynamic SQL & Stored Procedure Usage in T-SQL

    转自:http://www.sqlusa.com/bestpractices/training/scripts/dynamicsql/ Dynamic SQL & Stored Procedu ...

  2. MyBatis(3.2.3) - Dynamic SQL

    Sometimes, static SQL queries may not be sufficient for application requirements. We may have to bui ...

  3. 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 ...

  4. Get WMS Static GoodLocation By Dynamic SQL

    Dynamic SQL Store Procedure: Note: use variable,you need convert varchar and as a variable,not direc ...

  5. mybatis Dynamic SQL

    reference: http://www.mybatis.org/mybatis-3/dynamic-sql.html Dynamic SQL One of the most powerful fe ...

  6. mybatis-3 Dynamic SQL

    Dynamic SQL One of the most powerful features of MyBatis has always been its Dynamic SQL capabilitie ...

  7. ABAP动态生成经典应用之Dynamic SQL Excute 程序

    [转自http://blog.csdn.net/mysingle/article/details/678598]开发说明:在SAP的系统维护过程中,有时我们需要修改一些Table中的数据,可是很多Ta ...

  8. MySQL execute dynamic sql script.

    SET @sql = (SELECT IF( (SELECT COUNT(*) FROM usher_network_log ) > 1000000, "SELECT 0", ...

  9. Spring mybatis源码篇章-NodeHandler实现类具体解析保存Dynamic sql节点信息

    前言:通过阅读源码对实现机制进行了解有利于陶冶情操,承接前文Spring mybatis源码篇章-XMLLanguageDriver解析sql包装为SqlSource SqlNode接口类 publi ...

随机推荐

  1. num2cell

    num2cell的作用是把数值数组转换为cell数组. 最基本的用法是把数值数组的每个元素作为cell数组的元素,得到一个和原数组维度完全相同的cell数组,例如 >> A=magic(3 ...

  2. web 项目:解决插入 MySQL 数据库时中文乱码问题

    背景:在做 javaweb 项目的时,前台传递的中文最后插入数据库的时候总是出现乱码现象. 解决方案 ​ A.不管是使用 Idea.eclipse,确定自己的项目所使用的字符集是 UTF-8. ​ B ...

  3. JavaScript输入表单数据正则验证规则

    emailNameReg: /^(([a-zA-Z0-9]+\w*((\.\w+)|(-\w+))*[\.-]?[a-zA-Z0-9]+)|([a-zA-Z0-9]))$/, //匹配邮箱名称 ema ...

  4. Postman的Tests标签测试

    接口测试最重要的就是返回数据的检查,一个简单的接口,我们可以肉眼检查返回数据,但接口一旦多起来且复杂,每次的检查都会很费劲,此时我们就需要postman 的tests模块来代替 postman面板: ...

  5. Java之所有输入流输出流的分类

    (1)字节输入流        基类:InputStream        FileInputStream.ByteArrayInputStream.PipedInputStream.Buffered ...

  6. 插入排序专题 直接插入 折半 希尔shell

    1.直接插入排序 分析:a[n]有n个元素 a[0...n-1]  从 i=1...n-1  a[i]依次与   a[0...n-2]数字进行比较 发现后面的数字大于前面的数字交换位置,每一次比较,与 ...

  7. Day13 Python基础之time/datetime/random模块一(十一)

    time模块 import time print(help(time)) time.time() #return current time in seconds since the Epoch as ...

  8. java web石家庄铁道大学课程管理系统

    package kecheng Kc.java package kecheng; public class Kc { private int id; private String classname; ...

  9. Django之路由分发反向解析

    Django路由分发|反向解析 当一个Django中有多个app时,路由会有很多,将这些路由都写在与项目同名的文件夹下就会显得很多,很乱.并且在协同开发的时候容易出现相同的命名,当项目合并后就会出现路 ...

  10. 多线程系列之五:Balking 模式

    一,什么是Balking模式 如果现在不合适执行这个操作,或者没必要执行这个操作,就停止处理,直接返回.在Balking模式中,如果守护条件不成立,就立即中断处理. 二,例子: 定期将当前数据内容写入 ...