SqlServer 函数Declare通过传变量查询超慢解决办法

from

参考:

1,Declare传参查询速度慢,直接放入参数执行sql却快,求大牛给原因

2,OPTION(RECOMPILE)提高带参数执行SQL语句的索引效率

 

遇到的问题:通过参数执行sql函数查询速度超慢

示例示例代码:

class="lang:tsql decode:true">declare @prefix nvarchar(10) = '095-0021-' ;
declare @serialLength int  = 4  ;
declare @remainedLength int = 1;

--1,直接传值,速度很快 
select * from  [dbo].[f_getPartSerialNo]('095-0021-',4,1)
--2,传变量,速度超慢
select * from  [dbo].[f_getPartSerialNo]( @prefix , @serialLength  , @remainedLength  )
--3,使用OPTION(RECOMPILE)解决2速度慢问题。执行速度同1
select  * from dbo.[f_getPartSerialNo]( @prefix , @serialLength  , @remainedLength  ) OPTION(RECOMPILE)

--:f_getPartSerialNo
CREATE FUNCTION [dbo].[f_getPartSerialNo]
(	
	-- Add the parameters for the function here
	@prefix varchar(40),
	@serialLength int, 
	@remainedLength int
)
RETURNS TABLE 
AS
RETURN 
(
	SELECT MIN(LX_IMA01) AS LX_IMA01
	FROM (
		SELECT PART_POOL.LX_IMA01, PART.LX_IMA01 AS IMA001
		FROM (
			SELECT @prefix + NUM AS LX_IMA01
			FROM NUMPOOL
			WHERE SerialLength = @serialLength
		) PART_POOL
		LEFT JOIN (
			SELECT lx_ima01
			FROM innovator.PART
			WHERE PART.LX_IMA01 LIKE @prefix+'%'
				AND IS_CURRENT = '1'
		) Part
		ON PART_POOL.LX_IMA01 = SUBSTRING(PART.LX_IMA01, 1, LEN(PART.LX_IMA01) - @remainedLength)
) X
WHERE IMA001 IS NULL
)
GO

3种查询执行计划:

1,传值: SqlServer 函数Declare通过传变量查询超慢解决办法_第1张图片

2,传参

SqlServer 函数Declare通过传变量查询超慢解决办法_第2张图片

3,使用OPTION(RECOMPILE),执行计划与传值一致。SqlServer 函数Declare通过传变量查询超慢解决办法_第3张图片

你可能感兴趣的:(SQL笔记)