Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Sql Query across tables

Author  Topic 

Looper
Yak Posting Veteran

68 Posts

Posted - 2010-08-25 : 07:30:33
Hi i am trying to write a sql statement but am having trouble.

I have two tables PreEmployee & Employee

In the tables an employee can have multiple employers

e.g
Employee Table
Employee Id 1, Employment 6, Employer 2
EmployeeId 1, Employment 7, Employer 3

PreEmployee Table
Employee Id 1, Employment 8, EmployerCode = Two
EmployeeId 1, Employment 9, EmployerCode = Three

I want to set a bit field in the PreEmployee e.g. HasMultEmployer = 1 if the employeeId record (checking both tables) has multiple employers? Note that in the PreEmployee Table it is the description rather than the Id of the employer that is held. The description and Ids are held in a reference table Employers

eg.
Employers
Id = 2, Description = Two
Id = 3, Description = Three

I am not sure how to do this?

Kristen
Test

22859 Posts

Posted - 2010-08-25 : 08:57:21
You could use a Trigger on the EmploymentTable to adjust HasMultEmployer (in EmployeeTable) based on the number of corresponding record(s) in the EmploymentTable. Update statement for the Trigger would be something like:

CREATE TRIGGER MyTrigger
ON dbo.EmploymentTable
AFTER INSERT, UPDATE, DELETE
AS

UPDATE E
SET HasMultEmployer = X.T_HasMultEmployer
FROM EmployeeTable AS E
JOIN
(
SELECT EmployeeId, [T_HasMultEmployer] = CASE WHEN T_EmploymentCount <= 1 THEN 0 ELSE 1 END
FROM
(
SELECT EmployeeId, [T_EmploymentCount] = COUNT(*)
FROM EmploymentTable
WHERE EmployeeId IN
(
SELECT EmployeeId
FROM inserted
UNION
SELECT EmployeeId
FROM deleted
)
GROUP BY EmployeeId
) AS Y
) AS X
ON X.EmployeeId = E.EmployeeId
WHERE (X.T_HasMultEmployer <> E.HasMultEmployer OR E.HasMultEmployer IS NULL)
Go to Top of Page
   

- Advertisement -