Here is my select statement with the innerjoin of two tables,
if not exists(select EmpId from SalaryDetails
where EmpId in (select Emp_Id
from Employee where Desig_Id=@CategoryId))
begin
// some statements here
end
else
begin
SELECT e.Emp_Id, e.Identity_No, e.Emp_Name,
case WHEN e.SalaryBasis=1 THEN 'Weekly'
ELSE 'Monthly' end as SalaryBasis,e.FixedSalary,
(SELECT TOP 1 RemainingAdvance
FROM SalaryDetails
ORDER BY CreatedDate DESC) as Advance
FROM Employee as e inner join Designation as d on e.Desig_Id=d.Desig_Id
INNER JOIN SalaryDetails as S on e.Emp_Id=S.EmpId
End
My results pane,
alt text http://img220.imageshack.us/img220/7774/resultpane.jpg
And My SalaryDetails Table,
alt text http://img28.imageshack.us/img28/770/salarydettable.jpg
EDIT:
My Output must be,
16 CR14 Natarajan Weekly 150.00
354.00
17 cr12333 Pandian Weekly 122.00 0.00
It looks like your join to Designation isn’t even used and you’re also missing your WHERE clause that you used in the IF statement at the top. I’d also move the subquery down into the join like Andy pointed out. Without having the DB to test against this probably won’t be exact but I’d rewrite it to something like;
Andy’s suggestion to move the subquery into a view is a good one, much easier to read and probably a lot more efficient if the DB is large.
EDIT: (ANSWER)
I edited jay’s answer because he came close to my output…