我想在查询中使用两个表,tblEmployee
和tblEmpPerformance
要求是:
使用tblEmployee.EmpID, tblEmployee.ManagerID
,直到tblEmpPerformance
并查看tblEmpPerformance.SalaryRaise
和tblEmpPerformance.CommissionRaise
,并相应地更新tblEmployee
。
对于tblEmpPerformance
if tblEmployee.EmpID = tblEmpPerformance.EmpID then
If tblEmpPerformance.Salary > 0 then
update tblEmployee
Set CompensationType = 'Salary'
Where tblEmployee.EmpID = tblEmpPerformance.EmpID
AND tblEmployee.ManagerID = tblEmpPerformance.ManagerID
update tblEmployee
Set SalaryRaise = tblEmpPerformance.SalaryRaise
Where tblEmployee.EmpID = tblEmpPerformance.EmpID
AND tblEmployee.ManagerID = tblEmpPerformance.ManagerID
If tblEmpPerformance.Commission > 0 then
update tblEmployee
Set CompensationType = 'Commission'
Where tblEmployee.EmpID = tblEmpPerformance.EmpID
AND tblEmployee.ManagerID = tblEmpPerformance.ManagerID
update tblEmployee
Set CommissionRaise = tblEmpPerformance.CommissionRaise
Where tblEmployee.EmpID = tblEmpPerformance.EmpID
AND tblEmployee.ManagerID = tblEmpPerformance.ManagerID
如果找不到匹配的EmpID
,请查看tblContractorPerformance
if tblEmployee.EmpID = tblContractorPerformance.EmpID then
If tblContractorPerformance.Salary > 0 then
update tblEmployee
Set CompensationType = 'Salary'
Where tblEmployee.EmpID = tblContractorPerformance.EmpID
AND tblEmployee.ManagerID = tblContractorPerformance.ManagerID
....
....
....
....
Next tblEmployee.EmpID
更新: DOH !! 编写此SQL查询的最佳方法是什么。存储过程或光标? 任何关于如何设计查询的建议都将是一个很好的帮助
答案 0 :(得分:3)
据我所知,您可以将其封装到一个查询中:
Update tblEmployee
Set CompensationType = Case
When EP.Commission > 0 Then 'Commission'
When EP.Salary > 0 Then 'Salary'
When CP.Salary > 0 Then 'Salary'
Else E.CompensationType -- leave value as is
End
, CommissionRaise = Case
When EP.Commission > 0 Then EP.CommissionRaise
Else E.CommissionRaise -- leave value as is
End
, SalaryRaise = Case
When EP.Commission > 0 Then E.SalaryRaise
When EP.Salary > 0 Then EP.SalaryRaise
When CP.Salary > 0 Then CP.SalaryRaise
Else E.SalaryRaise -- leave value as is
End
From tblEmployee As E
Left Join tblEmployeePerformance As EP
On EP.EmpID = E.EmpID
And EP.ManagerId = E.ManagerId
Left Join tblContractorPerformance As CP
On CP.EmpID = E.EmpID
And CP.ManagerId = E.ManagerId
答案 1 :(得分:2)
请避免使用游标。在处理数据时考虑基于集合。因此,执行第一组数据,tblEmpPerformance.Salary > 0
。进行更新,然后对tblEmpPerformance.Commission > 0
的下一组数据执行第二次操作。最后,更新tblContractorPerformance.Salary > 0
。
将这些操作放在存储过程中,我相信你会看到比使用游标等效的更好的性能。