I am doing a SQL select query. Under the [E] field , there is a stored function called "[defaultDB].[dbo].HighFirst" it is to judge "high" or "low" happen first.
Unfortunately, this judgment function makes the query super slow. It takes only 2 sec to complete the query if I skip the function (replace the function with 1). However, it takes over 30 mins if I use the function. Is it possible not to use the store function and directly embed the judgment into the query?
USE defaultDB;
IF OBJECT_ID (N'[defaultDB].[dbo].[HighFirst]', N'FN') IS NOT NULL
DROP FUNCTION HighFirst;
GO
CREATE FUNCTION HighFirst(@Date INT, @Stime INT, @ETime INT, @High Float, @Low Float)
RETURNS BIT
AS
BEGIN
Declare @result Bit
IF
(SELECT min([time]) FROM [defaultDB].[dbo].[Table2] WHERE [date] = @Date AND [Start] >= @Stime AND [Time]<= @etime and [H] > @high) <= (SELECT min([time]) FROM [defaultDB].[dbo].[Table2] WHERE [date] = @Date AND [Start] >= @Stime AND [Time]<= @etime and [L] < @Low)
Set @result = 1
ELSE
Set @result = 0;
Return @result
END;
Select
[Stime],
[Etime],
[target],
[CL],
[WinRate] = count(CASE WHEN [Max] > [target] THEN 1 END) / cast( count(*) as float),
[E] = AVG( Case
WHEN [Max] >= [target] AND [Min]< [CL] THEN IIF ([defaultDB].[dbo].HighFirst([date], [Stime], [Etime], [Target], [CL]) =1 , [Target] ,[CL])
WHEN [Max] >= [target] AND [Min] > [CL] THEN [target] /*HIT*/
WHEN [Max] < [target] AND [Min] < [CL] THEN [CL] /*CL*/
WHEN [Max] < [target] AND [Min] > [CL] THEN [EndReturn] /*both not */
END ) ,
[count] = count(*)
FROM [defaultDB].[dbo].[Table1] M
JOIN (values (0.003), (0.0035), (0.004), (0.0045), (0.005), (0.0055), (0.006), (0.0065), (0.007), (0.0075), (0.008) ) as T([target])
on 1 =1
JOIN (values (-0.003), (-0.0035), (-0.004), (-0.0045), (-0.005), (-0.0055), (-0.006), (-0.0065), (-0.007), (-0.0075), (-0.008), (-0.0085), (-0.009), (-0.0095), (-0.01), (-0.0105), (-0.011), (-0.0115) ) as C([CL])
on [M].[date] in ( 20120307,20120601,20121109,20130826,20131002,20140117,20140122,20140311,20140529,20140718,20150619,20151014,20151022,20160411,20160516,20160721,20160818,20160909,20170127,20170213,20170921,20171025,20171229,20180116,20180315,20180926,20181022,20181128,20181211,20190104,20190329,20190502,20190521,20190528,20190611,20190627,20190823,20190930,20191104,20191211,20200214,20200318,20200529,20200706,20200828,20201230,20210112,20210305,20210318,20210408,20210525,20210617,20210625)
AND [Stime] >= 133000
Group By [Stime], [Etime], [Target], [CL]