SQL Server ->> WITH RESULT SETS子句

SQL Server 2012对EXECUTE子句引入了WITH RESULT SETS选项,用于对EXECUTE语句执行的存储过程或者动态语句结果进行一个指定数据类型的转换,这样可以避免一种情况就是需要用临时表存储后再转换成目标表的数据字段类型,或者需要用OPENQUERY去转换。

用法:

IF EXISTS(SELECT * FROM sys.procedures WHERE name = 'usp_TestWithResultSets' AND schema_id = schema_id('dbo'))
    DROP PROCEDURE dbo.usp_TestWithResultSets
GO

CREATE PROCEDURE dbo.usp_TestWithResultSets
AS
BEGIN

SET NOCOUNT ON

SELECT Num AS INT_COL, CHAR(NUM+64) AS STR_COL
FROM dbo.Numbers
WHERE NUM<=26

END
GO

EXEC dbo.usp_TestWithResultSets
WITH RESULT SETS
(
    (
        COL1 INT NOT NULL,
        COL2 INT NOT NULL
    )
)

上面结果会报错,因为类型无法转换成功

Msg 8114, Level 16, State 2, Procedure usp_TestWithResultSets, Line 25
Error converting data type char(1) to int.

 

执行计划并没有多出类型转换多出的操作符/步骤

SQL Server ->> WITH RESULT SETS子句_第1张图片

 

那么这种转换会不会多出很多CPU时间呢,毕竟要转换。那我们把行数调整为10000行来观察下

没有加上WITH RESULT SETS

SQL Server parse and compile time: 
   CPU time = 0 ms, elapsed time = 0 ms.
SQL Server parse and compile time: 
   CPU time = 0 ms, elapsed time = 0 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 173 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 173 ms.

 

加上WITH RESULT SETS

SQL Server parse and compile time: 
   CPU time = 0 ms, elapsed time = 0 ms.
SQL Server parse and compile time: 
   CPU time = 0 ms, elapsed time = 0 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

 SQL Server Execution Times:
   CPU time = 125 ms,  elapsed time = 384 ms.

 SQL Server Execution Times:
   CPU time = 125 ms,  elapsed time = 384 ms.

 

你可能感兴趣的:(SQL Server ->> WITH RESULT SETS子句)