从临时表传递参数到存储过程

时间:2013-03-11 18:12:35

标签: sql-server-2008 tsql

我有一个senario,我必须将参数从temptable

传递给存储过程
#student(table)
StudentID  Class
10008        A
10009        A
10010        C

sproc接受2个参数StudentID和Class。

Student_Fail @StudentID,@Class

我想为所有studentID执行此存储过程(3次)。

如何做到这一点?使用while循环?

3 个答案:

答案 0 :(得分:1)

理想情况下,您应该重新编写存储过程,以便它可以直接使用#temp表,或者创建不同的存储过程,或者只是在此代码中复制存储过程尝试为单行执行的操作。 (基于集合的操作几乎总是比一次处理一行更好。)

除此之外,你必须使用游标或while循环(and no they aren't really different)。

DECLARE @StudentID INT, @Class CHAR(1);

DECLARE c CURSOR LOCAL FAST_FORWARD
  FOR SELECT StudentID, Class FROM #student;

OPEN c;

FETCH c INTO @StudentID, @Class;

WHILE @@FETCH_STATUS = 0
BEGIN
    EXEC dbo.Student_Fail @StudentID, Class;
    FETCH c INTO @StudentID, @Class;
END

CLOSE c;
DEALLOCATE c;

答案 1 :(得分:1)

正如您所指出的,while循环将执行:

declare @StudentID int
declare @Class char(1)

while exists (select 1 from #student)
begin

  select top 1 @StudentID = StudentID
    , @Class = Class
  from #student

  exec Student_Fail @StudentID, @Class

  delete from #student where @StudentID = StudentID

end

答案 2 :(得分:1)

是的,这可以作为WHILE循环或CURSOR来实现,因为在这种情况下,它们将基本上执行相同的操作,即逐行操作。

然而,理想的解决方案是重新实现Student_Fail失败存储过程,使其基于集合而不是程序化。

例如,您可以更改存储过程以接受table-valued parameter

首先,创建表类型:

CREATE TYPE dbo.StudentClassTableType AS TABLE
( StudentID int, Class varchar(50) )

接下来,更改存储过程(或创建新的存储过程)以接受表类型:

CREATE PROCEDURE dbo.usp_FailStudents
(@tvpStudentsToFail dbo.StudentClassTableType READONLY)
-- Perform set-based logic using your table parameter.
UPDATE sc
SET Fail = 1
FROM dbo.StudentClass sc
JOIN @tvpStudentsToFail fail 
  ON fail.StudentID = sc.StudentID 
  AND fail.Class = sc.Class