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. ASCII,unicode, utf8 ,big5 ,gb2312,gbk,gb18030等几种常用编码区别(转载)

    原文出处:http://www.blogjava.net/xcp/archive/2009/10/29/coding2.html 最近老为编码问题而烦燥,下定决心一定要将其弄明白!本文主要总结网上一些 ...

  2. BottomNavigationBar

    重点: bottomNavigationBar: BottomAppBar( shape: CircularNotchedRectangle(),//这个就是设置floatingactionbutto ...

  3. Java多线程学习(三)---线程的生命周期

    线程生命周期 摘要: 当线程被创建并启动以后,它既不是一启动就进入了执行状态,也不是一直处于执行状态.在线程的生命周期中,它要经过新建(New).就绪(Runnable).运行(Running).阻塞 ...

  4. 牛客网 Python 编程输入规范

    import sys try: while True: line = sys.stdin.readline().strip() if line == '': break lines = line.sp ...

  5. Python_每日习题_0005_三数排序

    # 题目: # 输入三个整数x,y,z,请把这三个数由大到小输出. # 程序分析: 练练手就随便找个排序算法实现一下,偷懒就直接调用函数. #方法一:排序 raw = [] for i in rang ...

  6. Python Revisited Day 03 (组合数据类型)

    目录 第三章 组合数据类型 3.1 序列类型 3.1.1 元组 3.1.2 命名的元组 (collections.nametuple()) 3.1.3 列表 (查询有关函数点这) 3.1.4 列表内涵 ...

  7. Unique Snowflakes UVA - 11572 (离散化+尺取法)

    Emily the entrepreneur has a cool business idea: packaging and selling snowflakes. She has devised a ...

  8. sql定时备份

    老规矩,直接上代码: ) set @name='C:\Backup\MyStudy_'+ ),)+'.bak' BACKUP DATABASE[MyStudy]TO DISK=@name WITH N ...

  9. 使用JavaScript动态刷新页面局部内容

    html页面: <%@page contentType="text/html; charset=Shift_JIS"%><html>    <head ...

  10. 百度地图支持https

    百度地图SDK,  支持https <script src="http://api.map.baidu.com/api?v=3.0&ak=nbnttGGI6lilllgy2zn ...