Call Procedure for each Row without using a cursor and set the row with the result of the procedure

前端 未结 2 772
说谎
说谎 2021-01-25 00:59

I have this procedure :

CREATE PROC dbo.##HTMLtoMARKDOWN @text nvarchar(500),
                                 @returnText nvarchar(500) output

AS
BEGIN
    DEC         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-25 01:37

    To update rows using a stored procedure, you need cursor:

        DEClARE @akey int, @text NVARCHAR(500),@retText NVARCHAR(500);
        DECLARE  c CURSOR LOCAL FAST_FORWARD FOR SELECT aid, MarkdownMini 
        FROM CloseAsOffTopicReasonTypes;
        OPEN c;
        FETCH NEXT FROM c into @akey, @text;
        WHILE @@FETCH_STATUS=0 BEGIN
            EXEC dbo.##HTMLtoMARKDOWN @TEXT, @retText output;
            UPDATE CloseAsOffTopicReasonTypes 
               SET MarkDown = @retText WHERE aid = @akey;
            FETCH NEXT FROM c into @akey, @text;
        END;
        DEALLOCATE c;
    

    If you intent to return a record set (like select), you need a temp table or in-memory table:

        DECLARE @TMP TABLE (akey int, MarkDown nvarchar(800) );
        SET NOCOUNT ON;
        DEClARE @akey int, @text NVARCHAR(500),@retText NVARCHAR(500);
        DECLARE  c CURSOR LOCAL FAST_FORWARD FOR SELECT aid, MarkdownMini 
               FROM CloseAsOffTopicReasonTypes;
        OPEN c;
        FETCH NEXT FROM c into @akey, @text;
        WHILE @@FETCH_STATUS=0 BEGIN
            EXEC dbo.##HTMLtoMARKDOWN @TEXT, @retText output;
            --UPDATE CloseAsOffTopicReasonTypes SET MarkDown = @retText WHERE aid = @akey;
            INSERT INTO @TMP (akey, MarkDown) values(@akey, @retText);
            FETCH NEXT FROM c into @akey, @text;
        END;
        DEALLOCATE c;
        SET NOCOUNT OFF;
        SELECT * FROM @TMP;
    

    The SET NOCOUNT ON/OFF are required if you want to return the row to a caller such as C#, PHP, where you also want to make above lines into one stored procedure.

提交回复
热议问题