title: function with cursor in sql server
body: <p>I have written a SQL scalar function with a cursor to retrieve item names with comma separated values. This is my function but it gives me an error.</p>
  
  <pre><code>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
  </code></pre>