SQL函数很慢

时间:2019-05-13 06:12:30

标签: sql-server user-defined-functions

我不是功能专家。继承了以下非常慢的功能

ALTER FUNCTION [dbo].[fn_Diagnosed]
( @clientId As int)
RETURNS NVARCHAR(10)
AS
BEGIN
DECLARE @result  int;
Declare @return nvarchar(10);
set @result = (SELECT COUNT(*)
FROM  dbo.AdditionalInfo 
WHERE  dbo.AdditionalInfo.Type = 'Diagnosed' and  ClientId = @ClientId);
IF @result > 0
   set @return = 'Yes'
ELSE
   set @return = 'No';    
return @return;
END

这是编写函数的正确方法吗?

1 个答案:

答案 0 :(得分:2)

您的功能看起来不错。不会根据外键约束自动创建索引。因此,您应该像这样显式添加索引

CREATE INDEX ClientAdditionalInfo_ClientID
    ON [dbo].[ClientAdditionalInfo]
    (ClientID)
    INCLUDE ([Type])