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. __attribute__ 机制详解(一)

    GNU C 的一大特色就是__attribute__ 机制.__attribute__ 可以设置函数属性(Function Attribute).变量属性(Variable Attribute)和类型 ...

  2. BZOJ1064 NOI2008 假面舞会 图论

    传送门 将一组关系\((A,B)\)之间连一条边,那么显然如果图中存在环长为\(len\)的环,那么面具的种数一定是\(len\)的因数. 值得注意的是这里环的关系除了\(A \rightarrow ...

  3. Java8-1-新特性_Lambda表达式

    最近实在是闲的蛋疼, 突然想起前一段时间使用Lambda表达式觉得惊为天人, 所以就去仔细的学习了一下, 整理出一份博客出来供大家观赏. 一. 什么是lambda表达式. Lambda 是一个匿名函数 ...

  4. 使用Python的http.server实现一个简易的Web Api对外提供HanLP拼音转换服务

    由于采集省市区镇数据需要对地名进行拼音转换,由于第三方高准确度接口对IP进行了限制,处理大量数据变得异常缓慢. 使用了一个折中的办法,省市区 3级(3千+)用高准确度接口(几乎没有拼错的地名),镇级( ...

  5. python面向对象(封装、继承、多态)+ 面向对象小栗子

    大家好,下面我说一下我对面向对象的理解,不会讲的很详细,因为有很多人的博客都把他写的很详细了,所以,我尽可能简单的通过一些代码让初学者可以理解面向对象及他的三个要素. 摘要:1.首先介绍一下面向对象 ...

  6. Python_每日习题_0002_个税计算

    # 题目 企业发放的奖金根据利润提成.利润(I)低于或等于10万元时, # 奖金可提10%:利润高于10万元,低于20万元时,低于10万元的部分按10%提成, # 高于10万元的部分,可提成7.%:2 ...

  7. c++入门之再次探讨类属性

    精辟博文:https://blog.csdn.net/msdnwolaile/article/details/51923859(转载,仅供学习|!)

  8. 线程中的samaphore信号量及event事件

    一.信号量 samaphore: 在程序中意思为同时允许几个线程运行,比如我们去水上乐园的滑梯玩时,有四个滑梯,每一个滑梯上当没有人在中间玩滑下去时才允许上人,四个滑梯1,2,3,4,同时最多四个人, ...

  9. 学习memcache

    本文参考了菜鸟教程中的内容. 安装 安装memcache的时候,请切换为root用户 root@centos # wget http://www.memcached.org/files/memcach ...

  10. Failure to transfer org.apache.maven:maven-archiver:pom:2.5 from https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval o

    pom.xml报错: Failure to transfer org.apache.maven:maven-archiver:pom:2.5 from https://repo.maven.apach ...