2014-09-03 80 views
0

我已經寫了這是工作的罰款與最值的,但一些價值它給我的錯誤作爲SQL Server過程:錯誤與SQL Server過程動態

必須聲明標量變量「@CourseID 」。

我沒有太多的程序經驗,請幫忙,另請參閱參數定義和參數順序。

ALTER PROCEDURE [dbo].[prStudentLoadByStudentAtt] 86 
    @StID int 
AS 
    DECLARE @SemID int 
    DECLARE @CourseID int 

    DECLARE @SQLQuery as nvarchar(4000) 
    DECLARE @ParamDefinition as nvarchar(4000) 

BEGIN 
    -- SET NOCOUNT ON added to prevent extra result sets from 
    -- interfering with SELECT statements. 
    SET NOCOUNT ON; 

    -- Insert statements for procedure here 
    set @SQLQuery = 'SELECT distinct dbo.tbSubjects.SubjectName,dbo.tbSubjects.SubCode, dbo.tbSubjects.SemID, dbo.tbStudent.StudentID, dbo.tbStudent.Name, dbo.tbStudent.RollNo, dbo.tbStudent.RegNo, dbo.tbAttendanceMaster.SubID, dbo.fnTotalDays(dbo.tbAttendanceMaster.SubID, dbo.tbStudent.StudentID) AS Total, 
         dbo.fnNoOfDays(dbo.tbAttendanceMaster.SubID, dbo.tbStudent.StudentID) AS Present, dbo.fnPerDays(dbo.tbAttendanceMaster.SubID, dbo.tbStudent.StudentID) 
         AS Percentage, ISNULL(dbo.tbSemester.SemName, ''Not Available'') AS SemName 
FROM dbo.tbAttendance INNER JOIN dbo.tbAttendanceMaster ON dbo.tbAttendance.MasterAID = dbo.tbAttendanceMaster.AtdID INNER JOIN dbo.tbStudent ON dbo.tbAttendance.StID = dbo.tbStudent.StudentID INNER JOIN dbo.tbSubjects ON dbo.tbAttendanceMaster.SubID = dbo.tbSubjects.SubID LEFT OUTER JOIN dbo.tbSemester ON dbo.tbSubjects.SemID = dbo.tbSemester.SemID 
    WHERE [email protected] ' 

    SELECT @CourseID = CourseID FROM tbStudent WHERE StudentID = @StID 
    SELECT @SemID = SemID FROM tbStudent WHERE StudentID = @StID 

    IF (ISNULL(@SemID, 0) = 0) 
    BEGIN 
     set @[email protected]+' and [email protected] ' 
    end 
    else 
    begin 
     set @[email protected]+' and [email protected] ' 
    end 

    set @ParamDefinition = '@SemID int, @StID int' 

    Execute sp_Executesql @SQLQuery, @ParamDefinition, @SemID, @StID 

    return 
END 

回答

0

改變這兩條線的CourseId傳遞到動態創建的SQL

set @ParamDefinition='@SemID int, @StID int, @CourseId int' 

Execute sp_executesql @SQLQuery, @ParamDefinition, @SemID, @StID, @CourseId 
+0

是參數的這兩行重要與否 – 2014-09-03 19:30:20

+0

是的,你的第一個語句定義它們的順序必須是一樣的,你通過他們在第二順序的順序。 – Laurence 2014-09-03 19:43:52

+0

但是在過程中,StID在semid之前定義,但在paramdefinition中,semid在stid之前出現,在sp_excutesql – 2014-09-03 20:17:12

1

真的不知道爲什麼你必須擺在首位在這裏所有這些動態SQL。很確定你的整個過程可以簡化爲一個選擇語句。像這樣的東西。

select * 
from dbo.tbAttendance a 
INNER JOIN dbo.tbAttendanceMaster am ON a.MasterAID = am.AtdID 
INNER JOIN dbo.tbStudent s ON a.StID = s.StudentID 
INNER JOIN dbo.tbSubjects su ON am.SubID = su.SubID 
LEFT OUTER JOIN dbo.tbSemester sem ON su.SemID = sem.SemID 
WHERE s.StudentID = @StID 
    AND s.CourseID = isnull(su.CourseID, s.CourseID) 
    AND s.SemID = ISNULL(su.SemID, s.SemID) 
+0

動態SQL生成的查詢可能更有效。 – Laurence 2014-09-03 19:46:31

+0

這是一個很大的假設。原始方法至少需要三個查詢,並且是一種非標準方法。是的,這是可能的,因爲上述內容是nonSARGable,但我會在開始使用動態sql方法之前做一些性能測試。 – 2014-09-03 20:21:26