在光标中调用PROC

时间:2011-08-24 23:11:48

标签: sql-server cursor procedure

我有一个名为my_table的表格,其格式为:

+----+--------------------------+-----------------------------+--------------------+
| ID | name (4 possible values) |  action (2 possible values) | sequence (1,2...n) |
+----+--------------------------+-----------------------------+--------------------+

我想创建一个存储过程,可以根据sequence列中的序列处理数据。此存储过程应查看sequence中的值,然后执行相应的存储过程。目前我有8个独立的存储过程。

例如,如果seq = 1则应执行存储过程#1。 如果seq = 2,它会转到存储过程#4,具体取决于nameaction的值。有8种可能的匹配。

这是我的尝试:

SET NOCOUNT ON
DECLARE @name varchar(20), @action varchar(20), @ID int, @Seq varchar(20)
DECLARE ILOOP CURSOR FOR SELECT ID, Name, Action, Seq FROM my_table
OPEN ILOOP
FETCH NEXT FROM iloop INTO @ID, @name, @Action, @Seq
WHILE @@Fetch_Status = 0 BEGIN
    SELECT * From my_table WHERE Name = case Name when 'provider'
    then EXEC sp1
END
CLOSE ILOOP
DEALLOCATE ILOOP 
RETURN

1 个答案:

答案 0 :(得分:1)

您忽略了告诉我们用于选择存储过程的具体逻辑或者他们采用的参数,但似乎您需要这些内容。

SET NOCOUNT ON

DECLARE @Name VARCHAR(20) ,
    @Action VARCHAR(20) ,
    @ID INT ,
    @Seq VARCHAR(20)

DECLARE ILOOP CURSOR
FOR
    SELECT  ID ,
            Name ,
            Action ,
            Seq
    FROM    my_table
    ORDER BY Seq

OPEN ILOOP
FETCH NEXT FROM ILOOP INTO @ID, @Name, @Action, @Seq
WHILE @@Fetch_Status = 0 
    BEGIN
        IF @Name = 'A'
            AND @Action = 'X' 
            EXEC sp1 @Action, @ID, @Name
        ELSE 
            IF @Name = 'C'
                AND @Action = 'Y' 
                EXEC sp2 @Action, @ID, @Name

        FETCH NEXT FROM ILOOP INTO @ID, @Name, @Action, @Seq    
    END
CLOSE ILOOP
DEALLOCATE ILOOP