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. JUnit5 快速指南

    JUnit5 快速指南 version: junit5 1. 安装 2. JUnit 注解 3. 编写单元测试 3.1. 基本的单元测试类和方法 3.2. 定制测试类和方法的显示名称 3.3. 断言( ...

  2. WPF touch Scroll -触摸滚动

    借鉴地址:http://matthamilton.net/touchscrolling-for-scrollviewer 改造后支持上下和左右鼠标拖动滚动: using System; using S ...

  3. Linux Namespace : Network

    Network namespace 在逻辑上是网络堆栈的一个副本,它有自己的路由.防火墙规则和网络设备.默认情况下,子进程继承其父进程的 network namespace.也就是说,如果不显式创建新 ...

  4. 十三、MUI的日期起始和结束日期设置

    MUI的日期选择器的使用 // 日期选择器 //生日选择器(不会超过今年) function fdPicker1(id) { var year=new Date().getFullYear(); va ...

  5. Python_迭代器_35

    迭代器 # l = [1,2,3]# 索引# 循环 for# for i in l:# i## for k in dic:# pass #可以被for循环的# list# dic# str# set# ...

  6. 归并排序Python 实现

    一.归并排序   -归并排序(MERGE-SORT)是利用归并的思想实现的排序方法,该算法采用经典的分合策略(将问题分(divide)成一些小的问题然后递归求解,而合的阶段则将分的阶段得到的各答案&q ...

  7. os.path 下的各方法

    一.os.path os.path.abspath(file) #拿到当前程序(文件)的绝对目录. os.path.split(pathname) # 返回一个元组,第零个元素为文件上级绝对目录,第一 ...

  8. Python_内置函数之map()

    map 会根据提供的函数对指定序列做映射. 代码如下: def square(x): return x ** 2 ret = map(square, [1, 2, 3, 4, 5]) # 计算列表各元 ...

  9. Linux kernel support docker storage driver aufs

    How to make docker use aufs in CentOS 7? - Server Faulthttps://serverfault.com/questions/650208/how- ...

  10. 分布式文件系统FastDFS

    fastdfs_百度百科https://baike.baidu.com/item/fastdfs/5609710 用FastDFS一步步搭建文件管理系统 - bojiangzhou - 博客园http ...