我有一个存储过程,它创建4个临时表,然后返回带有内部连接的大选择的记录。这是返回记录的select的缩减版本。
SELECT R.*,
REC.Status_Date as [Receive Status Date],
RET.Status_Date as [Return Status Date]
FROM #Records R
INNER JOIN #Temp_Receive REC ON R.ID1 = REC.ID1
INNER JOIN #Temp_Return RET ON R.ID1 = RET.ID1
INNER JOIN #Temp_Submittal SUB ON SUB.RecID = REC.ID AND SUB.RetID = RET.ID
请注意,同一ID1可能有多个#TEMP_Receive和#TEMP_Return记录,而#TEMP_Submittal表是连接它们的记录。
我需要修改此过程,以在结果中包含的两个不同表中包含两个状态日期之间的假日数。我可以从单独的表中计算假期数。像这样:
Select count(*)
From Holiday_List
Where Holiday_Date between REC.Status_Date and RET.Status_Date
我在#Temp_Receive表中添加了一列Holiday_Count。如何使用Holiday_List表中的计数更新联接中的Holiday_Count列?我尝试过类似的东西,但从我能找到的,这不是远程有效的SQL语法。
UPDATE
( #Records R
INNER JOIN #TEMP_Receive REC ON R.ID1 = REC.ID1
INNER JOIN #TEMP_Return RET ON R.ID1 = RET.ID1
INNER JOIN #TEMP_Submittal SUB ON SUB.RecID = REC.ID AND SUB.RetID = RET.ID )
SET REC.Holiday_Count =
( SELECT COUNT(*)
FROM HOLIDAY_LIST HOL
WHERE HOL.HOLIDAY_DATE between #TEMP_Receive.Status_Date AND #TEMP_Receive.Status_Date )
我正在运行MS SQL Server 2012。
答案 0 :(得分:0)
1)尝试构建select
语句以查看将更新哪些行。在您的情况下,查询可能如下所示。
SELECT R.*,
REC.Status_Date as [Receive Status Date],
RET.Status_Date as [Return Status Date],
(Select count(*)
From Holiday_List
Where Holiday_Date between REC.Status_Date and RET.Status_Date) cnt
FROM #Records R
INNER JOIN #Temp_Receive REC ON R.ID1 = REC.ID1
INNER JOIN #Temp_Return RET ON R.ID1 = RET.ID1
INNER JOIN #Temp_Submittal SUB ON SUB.RecID = REC.ID AND SUB.RetID = RET.ID
2)如果一切正常,请用select
语句替换update
部分。
update #Temp_Receive
set Holiday_Count = (Select count(*)
From Holiday_List
Where Holiday_Date between REC.Status_Date and RET.Status_Date)
FROM #Records R
INNER JOIN #Temp_Receive REC ON R.ID1 = REC.ID1
INNER JOIN #Temp_Return RET ON R.ID1 = RET.ID1
INNER JOIN #Temp_Submittal SUB ON SUB.RecID = REC.ID AND SUB.RetID = RET.ID
另请注意,多个inner join
隐式表明所有4个表中都存在相同的ID1
。