如何在变量中存储sql查询

时间:2016-03-29 11:51:39

标签: c# mysql asp.net sql-server

SELECT Staff_Teaching.TeachingID FROM   Staff_Teaching INNER JOIN
          Staff ON Staff_Teaching.StaffID = Staff.StaffID WHERE        (Staff.StaffID = @StaffID) AND (Staff_Teaching.SemesterID = @SemesterID))

我有这个查询返回工作人员TeachingID,这是工作人员教授课程的ID。

我的问题是:

  1. 如何存储这些值,因为它返回的值超过1个,我可以在sql server或c#中使用数组吗?

  2. 然后我想获取这些值并将其传递给其他查询,如下所示:

  3. (SELECT Exam.Date FROM Exam WHERE(ExamID = @GetExamID)

    `@GetExamID` is where I want to pass these values to be checked 
    

    我可以使用foreach或数组吗?我正在使用asp.net(C#)

    这就是我想要做的事情

    BEGIN TRANSACTION
    SET @GetTeachingID =(SELECT        Staff_Teaching.TeachingID
    FROM          Staff_Teaching INNER JOIN
                  Staff ON Staff_Teaching.StaffID = Staff.StaffID
    WHERE        (Staff.StaffID = @StaffID) AND (Staff_Teaching.SemesterID = @SemesterID))
    COMMIT 
    
    BEGIN TRANSACTION
    SELECT  Course_Department.CourseID
    FROM            Course_Department INNER JOIN
                             Exam ON Course_Department.CourseID = Exam.ExamID INNER JOIN
                             ExamSchedule ON Exam.ExamID = ExamSchedule.ExamID INNER JOIN
                             Staff_Teaching ON Course_Department.TeachingID = Staff_Teaching.TeachingID
    WHERE        (Staff_Teaching.TeachingID = @GetTeachingID)
    
    COMMIT 
    
    
    BEGIN TRANSACTION
    SET @GetExamDate=(SELECT Exam.Date  
    FROM Exam
    WHERE (ExamID = @GetExamID))
    COMMIT 
    
    BEGIN TRANSACTION
    SET @GetExamTime=(SELECT Exam.BegainTime  
    FROM Exam
    WHERE (ExamID = @GetExamID))
    COMMIT 
    
    BEGIN TRANSACTION
    SELECT        ExamScheduleID
    FROM          Exam INNER JOIN
                  ExamSchedule ON Exam.ExamID = ExamSchedule.ExamID
    WHERE        (ExamSchedule.ExamScheduleID = @ExamScheduleID) AND (Exam.Date LIKE @GetExamDate) AND (Exam.BegainTime<=@GetExamTime)
    COMMIT 
    
    
    
    END
    

    我有5个查询,第一个将获得teachingid(1值) 第二个将获得courseid(超过1个值) 然后接下来的两个将采用courseid并获得考试日期和时间 然后我想检查上一个查询中是否有任何结果

2 个答案:

答案 0 :(得分:0)

SQL Server中没有类似数组的东西。您可以使用#temp表暂时存储它。

SELECT Staff_Teaching.TeachingID
INTO #Temp
Staff_Teaching INNER JOIN
      Staff ON Staff_Teaching.StaffID = Staff.StaffID WHERE                    
     (Staff.StaffID = @StaffID) AND (Staff_Teaching.SemesterID = @SemesterID))

Temporary tables

将其作为

传递
SELECT Exam.Date  FROM Exam WHERE (ExamID IN SELECT * FROM #Temp)

答案 1 :(得分:0)

你可以把它写成

declare @query = '(SELECT Exam.Date  FROM Exam WHERE (ExamID IN ('+@GetExamID+') )'

exec @query 

将C#中的@GetExamID作为逗号分隔字符串1,2,4,5,......

传递

您可以使用以下

将int数组转换为逗号分隔的字符串
var result = string.Join(",", arr);