我需要审查/重构针对表(10+ 百万行)的现有存储过程。存储过程签名不能轻易更改,如下所示。
存储过程接受两个由管道分隔的字符串,并使用 SQL 函数 ( SplitDelimitedVarChar
) 将字符串拆分为临时表,然后在实际选择中使用该临时表。数组字符串中的字符串数量范围从 1 到数千。
DateValue
和TimeValue
列包含行中时间戳的int
表示。
我的问题是,如果这是一个好的(最好的?)解决方案,或者是否可以做得更好,是否有人有任何想法。主要问题是它是否可以针对速度进行优化?
由于只能通过此存储过程访问表,因此索引与WHERE
列不聚集,并包括所有SELECT
列。
感谢您的任何建议或指点。
CREATE PROCEDURE [dbo].[spdata_Get_Ana]
@beginTime INT,
@endTime INT,
@subscribers VARCHAR(MAX),
@exchanges VARCHAR(MAX) = '1:',
@beginDateValue int,
@endDateValue int,
@target int = 1
AS
BEGIN
SET NOCOUNT ON;
CREATE TABLE #exch (Item Varchar(20) COLLATE database_default)
INSERT INTO #exch
SELECT Item FROM [SplitDelimitedVarChar] (@exchanges, '|') ORDER BY Item
CREATE CLUSTERED INDEX idx ON #exch (Item)
CREATE TABLE #subs (Item Varchar(20) COLLATE database_default)
INSERT INTO #subs
SELECT Item FROM [SplitDelimitedVarChar] (@subscribers, '|') ORDER BY Item
CREATE CLUSTERED INDEX idx ON #subs (Item)
SELECT
[Id]
,'' AS 'Name'
,[NameId]
,[Level]
,[Ne]
,[CallId]
,[Bg]
,[DateTime]
,[TimeStamp]
,[LogOwnerSnb]
,[TypeOfLog]
,[AbsenceCode]
,[AnswerTime]
,[CallForwardingReason]
,[CallForwardingToNumber]
,[CallTransferTime]
,[CallTransferReason]
,[SeizedSubscriberType]
,[SeizedSubscriberTime]
,[SeizedSubscriberNumber]
,[CalledSubscriberService]
,[InSubscriberType]
,[InSubscriberNumber]
,[CallDirection]
,[SubscriberService]
,[ClearingCause]
,[ClearingCauseTime]
,[OnHookTime]
,[OutAnswerSubType]
,[OutAnswerTime]
,[OutAnswerSubNum]
,[RingingStartedTime]
,[ReroutedToNumber]
,[InitiatedService]
,[B26]
FROM [dbo].[data_centrex_Ana] AS A
WHERE
(A.[DateValue] BETWEEN @beginDateValue AND @endDateValue)
AND
EXISTS(SELECT [Item] FROM #exch WHERE [Item] = A.[Level])
AND
(A.[TimeValue] BETWEEN @beginTime AND @endTime)
AND
(
(@target = 1 AND EXISTS(SELECT [Item] FROM #subs WHERE [Item] = A.[LogOwnerSnb]))
OR
(@target = 2 AND EXISTS(SELECT [Item] FROM #subs WHERE [Item] = A.[Bg]))
)
END