[转]Dynamic SQL & Stored Procedure Usage in T-SQL
转自:http://www.sqlusa.com/bestpractices/training/scripts/dynamicsql/
| Dynamic SQL & Stored Procedure Usage in T-SQL | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
Important security article related to dynamic SQL: How To: Protect From SQL Injection in ASP.NET ------------ -- Dynamic SQL QUICK SYNTAX ------------ USE AdventureWorks2008; EXEC ('SELECT * FROM Sales.SalesOrderHeader') DECLARE @DynamicSQL varchar(256); SET @DynamicSQL='SELECT * FROM Sales.SalesOrderHeader' EXEC (@DynamicSQL) GO DECLARE @DynamicSQL varchar(256), @Table sysname; SET @DynamicSQL='SELECT * FROM'; SET @Table = 'Sales.SalesOrderHeader' SET @DynamicSQL = @DynamicSQL+' '+@Table PRINT @DynamicSQL -- for testing & debugging EXEC (@DynamicSQL) GO -- Dynamic SQL for rowcount in all tables DECLARE @DynamicSQL nvarchar(max), @Schema sysname, @Table sysname; SET @DynamicSQL = '' SELECT @DynamicSQL = @DynamicSQL + 'SELECT '''+QUOTENAME(TABLE_SCHEMA)+'.'+ QUOTENAME(TABLE_NAME)+''''+ '= COUNT(*) FROM '+ QUOTENAME(TABLE_SCHEMA)+'.'+QUOTENAME(TABLE_NAME) +';' FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' PRINT @DynamicSQL -- test & debug EXEC sp_executesql @DynamicSQL -- sql server sp_executesql -- Equivalent code using the undocumented sp_MSforeachtable EXEC sp_MSforeachtable 'select ''?'', count(*) from ?' ------------ -- Dynamic sort with collation - Dynamic ORDER BY - SQL dynamic sorting DECLARE @SQL nvarchar(max)='SELECT FullName=FirstName+'' ''+Lastname FROM AdventureWorks2008.Person.Person ORDER BY LastName ' DECLARE @Collation nvarchar(max) = 'COLLATE SQL_Latin1_General_CP1250_CS_AS' SET @SQL=@SQL + @Collation PRINT @SQL EXEC sp_executeSQL @SQL ------------ -- sp_executeSQL usage with input and output parameters DECLARE @SQL NVARCHAR(max), @ParmDefinition NVARCHAR(1024) DECLARE @Color varchar(16) = 'Blue', @LastProduct varchar(64) SET @SQL = N'SELECT @pLastProduct = max(Name) FROM AdventureWorks2008.Production.Product WHERE Color = @pColor' SET @ParmDefinition = N'@pColor varchar(16), @pLastProduct varchar(64) OUTPUT' EXECUTE sp_executeSQL @SQL, @ParmDefinition, @pColor = @Color, @pLastProduct=@LastProduct OUTPUT SELECT Color=@Color, LastProduct=@LastProduct /* Color LastProduct Blue Touring-3000 Blue, 62 */ ---------- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following dynamic SQL scripts demonstrate: 1. Dynamic SQL stored procedure 2. Dynamic SQL with OUTPUT parameter 3. Stored procedure with dynamic SQL WHILE loop 4. Dynamic SQL with using parent's #temptable 5. Dynamic SQL for dynamic PIVOT query 6. Dynamic stored procedure with output parameter 7. WHERE clause with dynamic set of predicates ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ IMPORTANT SECURITY ARTICLE: Is Dynamic SQL in Your Stored Procedures Vulnerable to SQL Injection? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- FIRST EXAMPLE - dynamic stored procedure for customer list GO -- DROP stored procedure if exists to make CREATE work IF EXISTS ( SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CustomerListByState]') AND TYPE IN (N'P',N'PC')) DROP PROCEDURE [dbo].[CustomerListByState] GO -- Sproc (stored procedure) with dynamic SQL /***** DEMO ONLY - This sproc is vulnerable to SQL Injection Attack *****/ -- List splitter and JOIN is the preferred solution CREATE PROCEDURE CustomerListByState @States VARCHAR(128) AS BEGIN SET NOCOUNT ON DECLARE @SQL NVARCHAR(MAX) -- alternate nvarchar(1024) -- Dynamic query assembly with string concatenation SET @SQL = 'select Region, CustomerID, CompanyName, ContactName, Phone from Customers where Region IN (' + @States + ')' + ' order by Region, CompanyName' PRINT @SQL -- for testing & debugging /* Assembled code select Region, CustomerID, CompanyName, ContactName, Phone from Customers where Region IN ('WA', 'OR', 'ID', 'CA') order by Region, CompanyName */ EXEC sp_executeSQL @SQL END GO -- Execute dynamic SQL stored procedure script DECLARE @States VARCHAR(100) SET @States = '''WA'', ''OR'', ''ID'', ''CA''' EXEC CustomerListByState @States GO /* Results
*/ -- SECOND EXAMPLE - search names in Person.Person table -- Dynamic SQL with input and output parameters USE AdventureWorks2008; DECLARE @ParmDefinition NVARCHAR(1024) = N'@FirstLetterOfLastName char(1), @LastFirstNameOUT nvarchar(50) OUTPUT' DECLARE @FirstLetter CHAR(1) = 'P', @LastFirstName NVARCHAR(50) DECLARE @SQL NVARCHAR(MAX) = N'SELECT @LastFirstNameOUT = max(FirstName) FROM Person.Person'+CHAR(13)+ 'WHERE left(LastName,1) = @FirstLetterOfLastName' PRINT @SQL+CHAR(13) -- test & debug PRINT @ParmDefinition -- test & debug EXECUTE sp_executeSQL @SQL, @ParmDefinition, @FirstLetterOfLastName = @FirstLetter, @LastFirstNameOUT=@LastFirstName OUTPUT SELECT [Last First Name] = @LastFirstName, Legend='of last names starting with', Letter=@FirstLetter GO /* Results Last First Name Legend Letter Zoe of last names starting with P */ -- THIRD EXAMPLE - SPROC to enumerate all objects in databases -- Return objects count in all databases on the server -- Dynamic SQL stored procedure with cursor loop -- QUOTENAME function is used to build valid identifiers USE AdventureWorks; GO IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sprocObjectCountsInAllDBs]') AND TYPE IN (N'P',N'PC')) DROP PROCEDURE [dbo].[sprocObjectCountsInAllDBs] GO CREATE PROC sprocObjectCountsInAllDBs AS BEGIN DECLARE @dbName SYSNAME, @ObjectCount INT DECLARE @SQL NVARCHAR(MAX) DECLARE @DBObjectStats TABLE( DBName SYSNAME, DBObjects INT ) DECLARE curAllDBs CURSOR FOR SELECT name FROM MASTER.dbo.sysdatabases WHERE name NOT IN ('master','tempdb','model','msdb') ORDER BY name OPEN curAllDBs FETCH curAllDBs INTO @dbName WHILE (@@FETCH_STATUS = 0) -- Loop through all db-s BEGIN -- Build valid yet hard-wired SQL statement SET @SQL = 'select @dbObjects = count(*)' + char(13) + 'from ' + QuoteName(@dbName) + '.dbo.sysobjects' PRINT @SQL -- Use it for debugging /* select @dbObjects = count(*) from [AdventureWorks].dbo.sysobjects */ -- Dynamic call for query execution with output parameter(s) EXEC sp_executesql @SQL, N'@dbObjects int output', @dbObjects = @ObjectCount output INSERT @DBObjectStats SELECT @dbName, @ObjectCount FETCH curAllDBs INTO @dbName END -- while CLOSE curAllDBs DEALLOCATE curAllDBs -- Return results SELECT * FROM @DBObjectStats ORDER BY DBName END GO -- Execute stored procedure EXEC sprocObjectCountsInAllDBs GO /* Partial results DBName DBObjects AdventureWorks 604 AdventureWorks2008 646 AdventureWorksDW 151 AdventureWorksDW2008 164 AdventureWorksLT 158 AdventureWorksLT2008 158 */ /* FOURTH EXAMPLE - automatic T-SQL code generation USE AdventureWorks2008; DECLARE @I INT = -1 DECLARE @SQLDynamic NVARCHAR(1024) -- Temporary table is used for data sharing between parent & child processes -- This is the parent process; the child process is the dynamic SQL execution CREATE TABLE #SQL ( STYLE INT, [SQL] VARCHAR(256), Result VARCHAR(32)) -- Loop on @I from 0 to 13 WHILE (@I < 14) BEGIN SET @I += 1 -- Store query and dynamic results in temporary table INSERT #SQL (STYLE, [SQL]) SELECT @I, 'SELECT ' + 'CONVERT(VARCHAR, GETDATE(), ' + CONVERT(VARCHAR,@I) + ')' -- Build dynamic sql statement SET @SQLDynamic = 'UPDATE #SQL SET Result=(SELECT CONVERT(VARCHAR, GETDATE(), ' + CONVERT(VARCHAR,@I) + ')) WHERE STYLE=' + CONVERT(VARCHAR,@I) PRINT @SQLDynamic /* UPDATE #SQL SET Result=(SELECT CONVERT(VARCHAR, GETDATE(), 0)) WHERE STYLE=0 */ EXEC sp_executeSQL @SQLDynamic END -- Return results from temporary table SELECT * FROM #SQL DROP TABLE #SQL GO /* Partial results STYLE SQL Result 0 SELECT CONVERT(VARCHAR, GETDATE(), 0) Mar 14 2009 6:10AM 1 SELECT CONVERT(VARCHAR, GETDATE(), 1) 03/14/09 2 SELECT CONVERT(VARCHAR, GETDATE(), 2) 09.03.14 */ -- FIFTH EXAMPLE - dynamic pivot crosstab query ------------ -- T-SQL Dynamic Pivot Crosstab Report - Column header YYYY is dynamically assembled ------------ USE AdventureWorks GO DECLARE @YearList AS TABLE( YYYY INT NOT NULL PRIMARY KEY ) DECLARE @DynamicSQL AS NVARCHAR(MAX) INSERT INTO @YearList SELECT DISTINCT YEAR(OrderDate) FROM Sales.SalesOrderHeader DECLARE @ReportColumnNames AS NVARCHAR(MAX), @IterationYear AS INT SET @IterationYear = (SELECT MIN(YYYY) FROM @YearList) SET @ReportColumnNames = N'' -- Assemble pivot list dynamically WHILE (@IterationYear IS NOT NULL) BEGIN SET @ReportColumnNames = @ReportColumnNames + N',' + QUOTENAME(CAST(@IterationYear AS NVARCHAR(10))) SET @IterationYear = (SELECT MIN(YYYY) FROM @YearList WHERE YYYY > @IterationYear) END SET @ReportColumnNames = SUBSTRING(@ReportColumnNames,2,LEN(@ReportColumnNames)) PRINT @ReportColumnNames -- [2001],[2002],[2003],[2004] SET @DynamicSQL = N'SELECT * FROM (SELECT [Store (Freight Summary)]=s.Name, YEAR(OrderDate) AS OrderYear, Freight = convert(money,convert(varchar, Freight)) FROM Sales.SalesOrderHeader soh INNER JOIN Sales.Store s ON soh.CustomerID = s.CustomerID) as Header PIVOT (SUM(Freight) FOR OrderYear IN(' + @ReportColumnNames + N')) AS Pvt ORDER BY 1' PRINT @DynamicSQL -- Testing & debugging /* SELECT * FROM (SELECT [Store (Freight Summary)]=s.Name, YEAR(OrderDate) AS OrderYear, Freight = convert(money,convert(varchar, Freight)) FROM Sales.SalesOrderHeader soh INNER JOIN Sales.Store s ON soh.CustomerID = s.CustomerID) as Header PIVOT (SUM(Freight) FOR OrderYear IN([2001],[2002],[2003],[2004])) AS Pvt ORDER BY 1 */ -- Execute dynamic sql EXEC sp_executesql @DynamicSQL GO -- Partial results
------------ -- SIXTH EXAMPLE - dynamic stored procedure with output -- SQL Server dynamic SQL stored procedure to find size for all databases CREATE PROC sprocSizeForAllDBs AS BEGIN DECLARE @dbName SYSNAME, @ObjectSize INT DECLARE @SQL NVARCHAR(MAX) DECLARE @DBSizes TABLE( DBName SYSNAME, DBSizeinMB MONEY ) DECLARE curAllDBs CURSOR FOR SELECT name FROM MASTER.dbo.sysdatabases WHERE name NOT IN ('master','tempdb','model','msdb') ORDER BY name OPEN curAllDBs FETCH curAllDBs INTO @dbName WHILE (@@FETCH_STATUS = 0) -- Loop through all db-s BEGIN -- Build valid yet hard-wired SQL statement SET @SQL = 'select @DBSize = 0.0078125 * sum(size) ' + char(13) + 'from ' + QuoteName(@dbName) + '.dbo.sysfiles' PRINT @SQL -- test & debug /* select @DBSize = 0.0078125 * sum(size) from [AdventureWorks].dbo.sysfiles */ -- Dynamic call for query execution with output parameter(s) EXEC sp_executesql @SQL , N'@DBSize Money output' , @DBSize = @ObjectSize OUTPUT INSERT @DBSizes SELECT @dbName, @ObjectSize FETCH curAllDBs INTO @dbName END -- while CLOSE curAllDBs DEALLOCATE curAllDBs INSERT @DBSizes -- total size SELECT 'Total Space Used', SUM(DBSizeinMB) FROM @DBSizes -- Return results SELECT * FROM @DBSizes ORDER BY DBSizeinMB DESC END -- sproc GO EXEC sprocSizeForAllDBs /* DBName DBSizeinMB .... AdventureWorks 172.00 AdventureWorks2008 182.00 AdventureWorksDW 69.00 AdventureWorksDW2008 87.00 ..... */ ------------ -- SEVENTH EXAMPLE - dynamic WHERE clause -- Dynamic SQL logic to search a set of keywords in text USE tempdb; CREATE TABLE [Text] (Line nvarchar(max)) INSERT [Text] VALUES ('microsoft.com SQL web page quote: Line-of-business applications (LOB) are the critical link between the IT department and the business. The ability to securely and reliably store, centralize, manage and distribute data out to users is key to these LOB applications. SQL Server 2008 provides businesses with a high performance database platform that’s reliable, scalable, and easy to manage. SQL Server 2008 R2 builds on the 2008 release and helps IT departments provide even more cost-effective scalability on today’s most advanced hardware platforms using familiar SQL Server administration tools.') DECLARE @Keyword TABLE ( Search varchar(32)) INSERT @Keyword VALUES ('reliable'), ('scalability'), ('centralize') -- Dynamic SQL string variable DECLARE @SQL nvarchar(max) = 'SELECT Result=''FOUND'' FROM [Text] WHERE 1 != 1' -- Cursor WHILE loop to add all search word predicates to WHERE clause /******* THIS IS THE DYNAMIC PART *********/ DECLARE @Search varchar(32) DECLARE curKeyword CURSOR FOR SELECT Search FROM @Keyword OPEN curKeyword FETCH NEXT FROM curKeyword into @Search WHILE (@@FETCH_STATUS = 0) BEGIN SET @SQL=@SQL+CHAR(13)+' OR PATINDEX(''%'+@Search+'%'', Line) > 0' FETCH NEXT FROM curKeyword into @Search END -- while PRINT @SQL /* SELECT Result='FOUND' FROM [Text] WHERE 1 != 1 OR PATINDEX('%reliable%', Line) > 0 OR PATINDEX('%scalability%', Line) > 0 OR PATINDEX('%centralize%', Line) > 0 */ EXEC sp_executeSQL @SQL -- FOUND -- Cleanup DROP TABLE [Text] ------------ SQL Server Dynamic SQL & Dynamic SQL Stored Procedure links with more examples: http://www.sqlusa.com/bestpractices/dynamicsql/ The Curse and Blessings of Dynamic SQL How to search using all or partial columns with Dynamic SQL while avoiding SQL Injection |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| The Best SQL Server Training in the World |
[转]Dynamic SQL & Stored Procedure Usage in T-SQL的更多相关文章
- Difference between Stored Procedure and Function in SQL Server
Stored Procedures are pre-compile objects which are compiled for first time and its compiled format ...
- SQL Stored Procedure and Function
Anything can be programmable with defined syntax and common lib. )) -- Add the parameters for the st ...
- SQL Server 在多个数据库中创建同一个存储过程(Create Same Stored Procedure in All Databases)
一.本文所涉及的内容(Contents) 本文所涉及的内容(Contents) 背景(Contexts) 遇到的问题(Problems) 实现代码(SQL Codes) 方法一:拼接SQL: 方法二: ...
- SQL Server——存储过程(Stored Procedure)、事物、触发器
存储过程(proc 或 procedure) 存储过程(Stored Procedure),计算机用语,是一组为了完成特定功能的SQL语句集,是利用SQL Server所提供的Transact-SQL ...
- java当中JDBC当中请给出一个sql server的stored procedure例子
3.sql server的stored procedure例子: import java.sql.*;public class StoredProc0 {public static void main ...
- Modify a Stored Procedure using SQL Server Management Studio
In Object Explorer, connect to an instance of Database Engine and then expand that instance. Expand ...
- Stored Procedure 里的 WITH RECOMPILE 到底是干麻的?
在 SQL Server 创建或修改「存储过程(stored procedure)」时,可加上 WITH RECOMPILE 选项,但多数文档或书籍都写得语焉不详,或只解释为「每次执行此存储过程时,都 ...
- JDBC连接执行 MySQL 存储过程报权限错误:User does not have access to metadata required to determine stored procedure parameter types. If rights can not be granted,
国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html 内部邀请码:C8E245J (不写邀请码,没有现金送) 国 ...
- [转]Easy Stored Procedure Output Oracle Select
本文转自:http://www.oraclealchemist.com/oracle/easy-stored-procedure-output/ I answered a question on a ...
随机推荐
- C++ 箴言
1.把C++当成一门新的语言学习: 2.看<Thinking In C++>,不要看<C++变成死相>: 3.看<The C++ Programming Language ...
- 51nod 1126 矩阵快速幂 水
有一个序列是这样定义的:f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7. 给出A,B和N,求f(n)的值. Input 输 ...
- js中排序问题总结
js的排序中通常使用到sort函数,可以用冒泡排序,插入排序,快速排序,希尔排序,系统方法等方法,本文结束后分享一个用着排序算法的链接,感兴趣可以了解了解. 1.常见的对一般数组进行排序,代码如下: ...
- 移动web开发和移动app开发的区分
1.移动web开发 这部分跟web前端开发差别不大,使用的技术都是html+css+js.区别为手机浏览器是webkit的天下,pc端是IE的天 下.手机网页可以理解成pc网页的缩小版加一些触摸特性. ...
- android aidl 进程间通信需要注意的地方(android.os.TransactionTooLargeException)
转自:http://blog.sina.com.cn/s/blog_4e1e357d0102wau9.html 1.bus工程实现通过service实现aidl实体类 2.actor工程通过发起bin ...
- equals()和hashCode()隐式调用时的约定
package com.hash; import java.util.HashMap; public class Apple { private String color; public Apple( ...
- Nutch插件原理
本文目的:讲解Nutch的插件运行时加载原理
- Validform使用ajax详解
demo.config({ showAllError:true, url:"这里指定提交地址", ajaxpost:{ //可以传入$.ajax() ...
- T-SQL - 访问远程数据库并对其数据表进行操作
一.概述 很多时候我们需要在.NET应用程序中使用一条SQL语句来访问来自不同服务器.不同数据库中的不同的表,实现方法有很多.我们可以在.NET应用程序中建立数据访问层,使用ADO.NET Entit ...
- 汇编语言基础 debug的使用
-r 查看,改变CPU寄存器的内容 -r 加上寄存器名 在:后输入要写入的数据后 完成更改 debug 随着CS IP的改变 对应的汇编指令也不同 -r ip -r cs修改 ip cs 的值 d 段 ...