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. KNN-笔记(2)

    1 - kd Tree KD树是一种对K维空间中的实例点进行存储以便对其进行快速检索的树形数据结构.KD树其实就是二叉树,表现为对K维空间的一个划分,构造kd树相当于不断的用垂直于坐标轴的超平面将k维 ...

  2. java 基础04 重写

  3. 分布式系统消息中间件——RabbitMQ的使用基础篇

    分布式系统消息中间件——RabbitMQ的使用基础篇

  4. 【原创】自己动手写一个能操作redis的客户端

    引言 redis大家在项目中经常会使用到.官网也提供了多语言的客户端供大家操作redis,如下图所示 但是,大家有思考过,这些语言操作redis背后的原理么?其实,某些大神会说 只要按照redis的协 ...

  5. springcloud(十三):Eureka 2.X 停止开发,但注册中心还有更多选择:Consul 使用详解

    在上个月我们知道 Eureka 2.X 遇到困难停止开发了,但其实对国内的用户影响甚小,一方面国内大都使用的是 Eureka 1.X 系列,另一方面 Spring Cloud 支持很多服务发现的软件, ...

  6. SQL Server 分析函数和排名函数

    分析函数基于分组,计算分组内数据的聚合值,经常会和窗口函数OVER()一起使用,使用分析函数可以很方便地计算同比和环比,获得中位数,获得分组的最大值和最小值.分析函数和聚合函数不同,不需要GROUP ...

  7. Westore 1.0 正式发布 - 小程序框架一个就够

    世界上最小却强大的小程序框架 - 100多行代码搞定全局状态管理和跨页通讯 Github: https://github.com/dntzhang/westore 众所周知,小程序通过页面或组件各自的 ...

  8. 爬虫(三)之scrapy核心组件

    01-核心组件 ·五大核心组件的工作流程: 引擎(Scrapy) 用来处理整个系统的数据流处理, 触发事务(框架核心) 调度器(Scheduler) 用来接受引擎发过来的请求, 压入队列中, 并在引擎 ...

  9. [LeetCode] Department Highest Salary -- 数据库知识(mysql)

    184. Department Highest Salary The Employee table holds all employees. Every employee has an Id, a s ...

  10. H5 CSS的格式

    02-CSS的格式 标签名称{ 属性名称: 属性对应的值; ... } 2.注意点: 1.style标签必须写在head标签的开始标签和结束标签之间(也就是必须和title标签是兄弟关系) 2.sty ...