这是我使用的程序........
CREATE procedure AcademicDetailsInsert
@CandidateId int,
@DegreeIDs varchar(25),
@Board_Universities varchar(200),
@YearsOfPassing varchar(50),
@Percentages varchar(50)
As
set NOCOUNT ON
DECLARE @ReturnValue INT
BEGIN
BEGIN TRY
select @ReturnValue = 0
IF EXISTS (SELECT ITEM AS DegID
FROM [SplitString](@DegreeIDs,','))
INSERT INTO [AcademicDetails] ([CandidateID], [DegreeId], [Board_University], [Year_Of_Passing], [Percentage])
SELECT
@CandidateID,
DegID.ITEM, Board_Uni.Item, YOfPass.ITEM,
Perc.ITEM
FROM
[splitString](@DegreeIDs, ',') DegID,
[splitString](@Board_Universities, ',') Board_Uni,
[splitString](@YearsOfPassing, ',') YOfPass,
[splitString](@Percentages, ',') Perc
WHERE
DegID.ITEM NOT IN (SELECT DegreeID
FROM AcademicDetails
WHERE CandidateID = @CandidateID)
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ERROR_NO,
ERROR_MESSAGE() AS ERROR_MSG,
ERROR_LINE() AS ERROR_LINE_NO
END CATCH
END
这是我用来运行程序的代码......
EXEC AcademicDetailsInsert 1,'2,3','NMU,IND','2005,2008','66.33,71.65'
这是结果..
1 2 nmu 2005 66.33
1 2 nmu 2008 66.33
1 2 nmu 2005 23.65
1 2 nmu 2008 23.65
1 2 nasik 2005 66.33
1 2 nasik 2008 66.33
1 2 nasik 2005 23.65
1 2 nasik 2008 23.65
1 3 nmu 2005 66.33
1 3 nmu 2008 66.33
1 3 nmu 2005 23.65
1 3 nmu 2008 23.65
1 3 nasik 2005 66.33
1 3 nasik 2008 66.33
1 3 nasik 2005 23.65
1 3 nasik 2008 23.65
当我为单个候选人传递两个记录的详细信息时,它会给出不同的结果
但是不是两条记录,而是重复记录插入。 SplitString
函数用于分割函数以分割degreeid,不同的大学名称以及传递年份和百分比。
我怎样才能避免......?
答案 0 :(得分:0)
您已完成Cross Join
,因此结果就像那样
尝试使用以下代码,希望它能正常工作
ALTER procedure AcademicDetailsInsert
@CandidateId int,
@DegreeIDs varchar(25),
@Board_Universities varchar(200),
@YearsOfPassing varchar(50),
@Percentages varchar(50)
As
set NOCOUNT ON
DECLARE @ReturnValue INT
BEGIN
BEGIN TRY
select @ReturnValue = 0
IF EXISTS
(
SELECT ITEM AS DegID
FROM [SplitString](@DegreeIDs,',')
)
INSERT INTO [AcademicDetails]
(
[CandidateID],
[DegreeId],
[Board_University],
[Year_Of_Passing],
[Percentage]
)
SELECT CandidateID,DegID,Board_Uni,YOfPass,Perc FROM
(
SELECT
@CandidateID AS CandidateID,
SUBSTRING(@DegreeIDs,0,CHARINDEX(',',@DegreeIDs)-1) AS DegID ,
SUBSTRING(@Board_Universities,0,CHARINDEX(',',@Board_Universities)-1) AS Board_Uni ,
SUBSTRING(@YearsOfPassing,0,CHARINDEX(',',@YearsOfPassing)-1) AS YOfPass,
SUBSTRING(@Percentages,0,CHARINDEX(',',@Percentages)-1) AS Perc
UNION
SELECT @CandidateID AS CandidateID,
SUBSTRING(@DegreeIDs,CHARINDEX(',',@DegreeIDs),Len(@DegreeIDs)) AS DegID,
SUBSTRING(@Board_Universities,CHARINDEX(',',@Board_Universities),Len(@DegreeIDs)) AS Board_Uni,
SUBSTRING(@YearsOfPassing,CHARINDEX(',',@YearsOfPassing),Len(@DegreeIDs)) AS YOfPass ,
SUBSTRING(@Percentages,CHARINDEX(',',@Percentages),Len(@DegreeIDs)) AS Perc
) AS RandomTable
where DegID not IN ( SELECT DegreeID
FROM AcademicDetails
WHERE CandidateID = @CandidateID
)
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ERROR_NO,
ERROR_MESSAGE() AS ERROR_MSG,
ERROR_LINE() AS ERROR_LINE_NO
END CATCH
END