2

I need some T-SQL help. We have an application which tracks Training Requirements assigned to each employee (such as CPR, First Aid, etc.). There are certain minimum Training Requirements which all employees must be assigned and my HR department wants me to give them the ability to assign those minimum Training Requirements to all personnel with the click of a button. So I have created a table called TrainingRequirementsForAllEmployees which has the TrainingRequirementID's of those identified minimum TrainingRequirements.

I want to insert rows into table Employee_X_TrainingRequirements for every employee in the Employees table joined with every row from TrainingRequirementsForAllEmployees. I will add abbreviated table schema for clarity.

First table is Employees:

EmployeeNumber  PK  char(6)
EmployeeName        varchar(50)

Second Table is TrainingRequirementsForAllEmployees:

TrainingRequirementID     PK  int

Third table (the one I need to Insert Into) is Employee_X_TrainingRequirements:

TrainingRequirementID  PK  int
EmployeeNumber         PK  char(6)

I don't know what the Stored Procedure should look like to achieve the results I need. Thanks for any help.

4

1 回答 1

2

cross join运算符适用于需要两组数据的笛卡尔积。因此,在存储过程的主体中,您应该具有以下内容:

insert into Employee_X_TrainingRequirements (TrainingRequirementID, EmployeeNumber)
select r.TrainingRequirementID, e.EmployeeNumber
from Employees e
    cross join TrainingRequirementsForAllEmployees r
where not exists (
    select 1 from Employee_X_TrainingRequirements
    where TrainingRequirementID = r.TrainingRequirementID
        and EmployeeNumber = e.EmployeeNumber
    )
于 2013-10-17T22:05:48.307 回答