我需要帮助更新日历表。我有2个表,一个事务表(表T)和一个日历表(表C)。我试图在日期可用时用应用程序ID(app_id
)和emp_Id
更新日历表,如果日期重叠则不应更新。例如
表T
app_id emp_id stdate eddate priority
-----------------------------------------------
1 15 2015-01-03 2015-01-05 1
2 18 2015-01-04 2015-01-06 2
表C
dates app_id empid
----------------------------
2015-01-03 null null
2015-01-04 null null
2015-01-05 null null
运行更新后,结果应为
表C
dates app_id empid
----------------------------
2015-01-03 1 15
2015-01-04 1 15
2015-01-05 1 15
答案 0 :(得分:1)
我倾向于使用apply
执行此操作:
update c
set app_id = t.app_id,
empid = t.empid
from table_c c apply
(select top 1 t.*
from table_t t
where tc.dates >= t.stdate and
tc.dates <= t.eddate
order by t.priority
) t;
答案 1 :(得分:0)
我把它写在了我的头顶,我希望它适合你:
UPDATE TC
SET app_id = (SELECT TOP 1 app_id FROM TABLE_T TT WHERE TC.dates BETWEEN TT.stdate AND tt.eddate ORDER BY TT.priority ASC),
empid = (SELECT TOP 1 emp_id FROM TABLE_T TT WHERE TC.dates BETWEEN TT.stdate AND tt.eddate ORDER BY TT.priority ASC)
FROM TABLE_C TC
您可以先使用此查询进行调试:
SELECT TC.*,
new_app_id = (SELECT TOP 1 app_id FROM TABLE_T TT WHERE TC.dates BETWEEN TT.stdate AND tt.eddate ORDER BY TT.priority ASC),
new_empid = (SELECT TOP 1 emp_id FROM TABLE_T TT WHERE TC.dates BETWEEN TT.stdate AND tt.eddate ORDER BY TT.priority ASC)
FROM TABLE_C TC
我在您的示例中使用了emp_id
和empid
。