在sql server中使用游标的函数

时间:2015-01-30 16:04:20

标签: sql-server sql-server-2008

我编写了一个带有游标的SQL标量函数,用逗号分隔值检索项目名称。这是我的功能,但它给了我一个错误。

SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO

ALTER FUNCTION [dbo].[GET_ITEM_NAME]
    (
      @PRINT_RECEIPT_MST_ID INT
    )
RETURNS VARCHAR(1000)
AS
    BEGIN
        DECLARE @ITEM_TITLE VARCHAR(1000)
        DECLARE @ITEM VARCHAR(100)
        SET @ITEM_TITLE = '';
        DECLARE ItemTitleCursor CURSOR FAST_FORWARD
        FOR
            SELECT ISNULL(IMT.ITEM_TITLE,'')
            FROM PRINT_RECEIPT_DET_T PDT 
            LEFT OUTER JOIN ITEM_MST_T IMT ON IMT.ITEM_ID=PDT.ITEM_ID
            WHERE PDT.PRINT_RECEIPT_MST_ID = @PRINT_RECEIPT_MST_ID

        OPEN ItemTitleCursor

        FETCH NEXT FROM ItemTitleCursor INTO @ITEM

        WHILE @@FETCH_STATUS = 0
            BEGIN
                IF ( @ITEM_TITLE = '' )
                    BEGIN
                        SET @ITEM_TITLE = CAST(@ITEM AS VARCHAR(100));
                    END
                ELSE
                    BEGIN
                        SET @ITEM_TITLE = CAST(@ITEM_TITLE AS VARCHAR(1000))
                            + ' , ' + CAST(@ITEM AS VARCHAR(100));
                    END
                FETCH NEXT FROM ItemTitleCursor INTO @ITEM
            END


        CLOSE ItemTitleCursor
        DEALLOCATE ItemTitleCursor 

        RETURN @ITEM_TITLE

    END

2 个答案:

答案 0 :(得分:3)

如果我没错,这应该取代你的cursor

DECLARE @ITEM_TITLE           VARCHAR(1000)='',
        @PRINT_RECEIPT_MST_ID INT

SELECT @ITEM_TITLE = + Isnull(IMT.ITEM_TITLE, '') + ','
FROM   PRINT_RECEIPT_DET_T PDT
       LEFT OUTER JOIN ITEM_MST_T IMT
                    ON IMT.ITEM_ID = PDT.ITEM_ID
WHERE  PDT.PRINT_RECEIPT_MST_ID = @PRINT_RECEIPT_MST_ID

SELECT @Left(@ITEM_TITLE, Len(@ITEM_TITLE) - 1) 

或使用For xml path将所有行转换为csv

DECLARE @ITEM_TITLE           VARCHAR(1000)='',
        @PRINT_RECEIPT_MST_ID INT

SET @ITEM_TITLE=(SELECT Isnull(IMT.ITEM_TITLE, '') + ','
                 FROM   PRINT_RECEIPT_DET_T PDT
                        LEFT OUTER JOIN ITEM_MST_T IMT
                                     ON IMT.ITEM_ID = PDT.ITEM_ID
                 WHERE  PDT.PRINT_RECEIPT_MST_ID = @PRINT_RECEIPT_MST_ID
                 FOR XML PATH(''))

SELECT Left(@ITEM_TITLE, Len(@ITEM_TITLE) - 1) 

答案 1 :(得分:-1)

谢谢大家的快速回复! 我已经解决了它。我的游标返回的长度比我提到的要长。应该是

RETURNS VARCHAR(4000)