我有一个具有相当复杂查询的视图(见下文)。然后我使用这个视图将数据插入到另一个表中。我在数据库中有很多数据,当我运行插入查询时,它运行了 8 个小时,最后才进行实际插入。似乎它首先从视图中获取所有结果,然后才将它们插入到我的表中。是否可以让它分别插入每条记录?
这是视图:
CREATE VIEW [dbo].[Enrollment]
AS
WITH CTE AS (SELECT RN = ROW_NUMBER() OVER (PARTITION BY PRIMARYPROVIDERCODE, CLIENTNUMBER
ORDER BY PRIMARYPROVIDERCODE, CLIENTNUMBER, STARTINGDATE), ID, PRIMARYPROVIDERCODE, CLIENTNUMBER, STARTINGDATE, ENDINGDATE
FROM AUTHORIZE
WHERE DOCREVNO = 0 AND CMT = 'N'
GROUP BY PRIMARYPROVIDERCODE, CLIENTNUMBER, STARTINGDATE, ENDINGDATE, ID)
SELECT [Current Row].ID, [Current Row].RN, [Current Row].PRIMARYPROVIDERCODE, [Current Row].CLIENTNUMBER, [Current Row].STARTINGDATE,
ENDINGDATE =
(SELECT TOP 1 [Next Ending].ENDINGDATE
FROM CTE[Next Ending]
WHERE [Next Ending].RN >= [Current Row].RN AND [Next Ending].ENDINGDATE IS NOT NULL AND
[Next Ending].PRIMARYPROVIDERCODE = [Current Row].PRIMARYPROVIDERCODE AND
[Next Ending].CLIENTNUMBER = [Current Row].CLIENTNUMBER
ORDER BY [Next Ending].RN)
FROM CTE[Current Row] INNER JOIN
CTE[Previous Row] ON ([Previous Row].PRIMARYPROVIDERCODE = [Current Row].PRIMARYPROVIDERCODE AND
[Previous Row].CLIENTNUMBER = [Current Row].CLIENTNUMBER) AND (([Previous Row].RN = [Current Row].RN AND [Current Row].RN = 1) OR
([Previous Row].RN = [Current Row].RN - 1 AND [Previous Row].ENDINGDATE IS NOT NULL))
这是插入查询:
INSERT INTO [dbo].[clientenrollment]
([DOCSERNO]
,[DOCREVNO]
,[USERID]
,[SIGNED]
,[TIMESTAMP]
,[ClientNumber]
,[enrollmentdate]
,[terminationdate]
,[PrimaryProviderCode]
,[Action]
,[Providername]
,[SERVICEMAPCODE])
SELECT REPLACE(STR(6620100322000000 + row_number() over (order by ev.ID asc), 17, 0), ' ', '0')
,0
, NULL
, 0
, GETDATE()
,ev.CLIENTNUMBER
,ev.STARTINGDATE
,ev.ENDINGDATE
,ev.PRIMARYPROVIDERCODE
,auth.ACTION
,p.PROVIDERNAME
,ms.MapCode
FROM [dbo].[Enrollment] AS ev
JOIN AUTHORIZE auth ON auth.ID = ev.ID
LEFT JOIN MasterService ms ON ms.Code = auth.SERVICECODE
LEFT JOIN PROVIDER p ON p.PROVIDERCODE = ev.PRIMARYPROVIDERCODE
WHERE p.DOCREVNO = 0