我试图为先决条件单元创建一个祖先表。我不确定如何使用SQL脚本针对级别2、3插入数据,依此类推...
我有三个表:
能力单位表具有以下数据:
先决条件表具有以下数据:
在加入Unit_Of_Competency和Prerequisite时,我们得到以下输出:
我需要填充Prerequisite_Ancestor表;我只填充到第1级
我需要填充2、3、4级的祖先表 例如,
我在Prerequisite_Ancestor表中输入Ancestor_Level 1的方式是使用以下脚本:
INSERT INTO Prerequisite_Ancestor (Prerequisite_Ancestor_ID, UoC_ID, Prerequisite_ID, Ancestor_Level)
select newID(), U.Unit_Of_Competency_ID as UoC, P.Prerequisite_ID as Prerequisite, 1 from Prerequisite P
join Unit_Of_Competency U on P.Unit_Of_Competency_ID=U.Unit_Of_Competency_ID
join Unit_Of_Competency U2 on U2.Unit_Of_Competency_ID=P.Prerequisite_ID
如何使用脚本输入2、3,...级别?
预先感谢您:)
答案 0 :(得分:1)
您需要创建另一个用于暂存目的的表,该表将从您设计的Web表单中收集数据。并每次都截断以提交新表单。登台表将包含您要填充所有三个表所需的所有列。查看您现有的列,登台表将具有以下几列:
CREATE TABLE LoadUnitsStg(
StagingID UNIQUEIDENTIFIER NOT NULL PRIMARY KEY DEFAULT NEWID(),
UoC_Code VARCHAR(50),
UoC_Title VARCHAR(200),
UoC_Descriptor VARCHAR(500),
Pre_UoC_Code VARCHAR(50),
Pre_UoC_PreReq VARCHAR(50),
Pre_Pathway VARCHAR(50),
Anc_UoC_Code VARCHAR(50),
Anc_UoC_PreReq VARCHAR(50),
Ancestor_level INT
)
现在将数据从Web表单加载到登台表,并使用此查询将数据填充到所需的表中。
INSERT INTO Unit_Of_Competency ([UoC_Code],[UoC_Title],[Descriptor])
SELECT DISTINCT(UoC_Code),UoC_Title,UoC_Descriptor FROM LoadUnitsStg stg
WHERE UoC_Code IS NOT NULL AND NOT EXISTS (
SELECT 1 FROM Unit_Of_Competency UoC
WHERE UoC.UoC_Code=stg.UoC_Code);
INSERT INTO Prerequisite ([Pathway],[Unit_Of_Competency_ID],[Prerequisite_ID])
SELECT DISTINCT(Pre_Pathway),(Select Unit_Of_Competency_ID from Unit_Of_Competency where UoC_Code like stg.Pre_UoC_Code),(Select Unit_Of_Competency_ID as Prerequisite_ID from Unit_Of_Competency where UoC_Code like stg.Pre_UoC_PreReq) FROM LoadUnitsStg stg
WHERE Pre_Pathway IS NOT NULL AND NOT EXISTS (
SELECT 1 FROM Prerequisite Pre
WHERE Pre.Pathway=stg.Pre_Pathway);
INSERT INTO Prerequisite_Ancestor ([Ancestor_Level],[UoC_ID],[Prerequisite_ID])
SELECT DISTINCT(Ancestor_level),(Select Unit_Of_Competency_ID as UoC_ID from Unit_Of_Competency where UoC_Code like stg.Anc_UoC_Code),(Select Unit_Of_Competency_ID as Prerequisite_ID from Unit_Of_Competency where UoC_Code like stg.Anc_UoC_PreReq) FROM LoadUnitsStg stg
WHERE Ancestor_level IS NOT NULL AND NOT EXISTS (
SELECT 1 FROM Prerequisite_Ancestor Anc
WHERE Anc.Ancestor_level=stg.Ancestor_level);
加载数据后,只需截断暂存表中的下一组条目即可。
希望这对您有所帮助。