从&更新选择“进入”以忽略“复制”

时间:2013-10-06 12:20:39

标签: sql-server

我写了这个Sp来插入/更新UserExams表,其中包含(UserID,ExamID,studentMark) 我需要为没有分数的学生添加新标记 并更新学生标记(如果已存在) 我使用Split Function返回表包含(ID,vItem)

我现在不知道错误在哪里,任何人都可以帮助我,拜托 我得到的错误是:无法绑定多部分标识符“UserExams.UserID”。

    ALTER PROC [dbo].[InsertUserMarks]
(    
@pSemesterID int,    
@pCourseID int,    
@pExamID int,    
@pClassID int,     
@pUserID varchar(8000),
@pMarks varchar(8000)     
)    
as    
--save the values of MaxMark To check if there is any Mark higher than the full mark if so then stop execution    
DECLARE @vTestMaxMark decimal(5,2)    
SET @vTestMaxMark = (select ExamMark from Exams where ExamID=@pExamID)    


IF EXISTS (select 'true' from Split(@pMarks,',') WHERE vItem>@vTestMaxMark)    
begin    
print('Operation cannot complete; there are one or more Mark ABOVE the Max value')    
return
end    


            update UserExams 
            Set StudentMark=MA.vItem
            from split(@pUserID,',') us
            inner join split(@pMarks,',') ma on us.ID = ma.id
            where UserExams.UserID=US.vItem
            and UserExams.ExamID=@pExamID


            --Insert
            insert into UserExams   
            select us.vItem,1,ma.vItem,system_user,getdate(),null,null from
            split(@pUserID,',') us
            inner join split(@pMarks,',') ma on us.ID = ma.id
            WHERE NOT EXISTS (
            SELECT 'True'
            FROM split(@pUserID,',') us
            inner join split(@pMarks,',') ma on us.ID = ma.id
            where UserExams.UserID=US.vItem
            and UserExams.ExamID=@pExamID

            )

2 个答案:

答案 0 :(得分:0)

问题似乎位于查询的最底层。您有一个插入到引用UserExams表的子查询,但该子查询在其FROM子句中不包含UserExams,它需要它。

答案 1 :(得分:0)

在你的情况下,我将在此proc中使用合并语句,All for record在大表中存在可能非常昂贵。
合并声明将检查记录是否存在并使用匹配然后更新当不匹配时插入将使您的代码更简单,更容易理解和维护。