Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Sql Server, how do you put value from cursor into temp table?

I am trying to create a function which has a cursor in it. I want to get the Quanatity value from that cursor and put it in the temp table. But I havent succeeded to get the value and put it into the temp table.

I put comment where I couldnt get it done...

here is my code

alter FUNCTION test(@input VARCHAR(250)) RETURNS Decimal(8, 2) AS BEGIN

DECLARE @rst Decimal(8, 2) SET @rst=0
DECLARE @Temp TABLE (Quantity Decimal(8,2), Price Decimal(8,2))
DECLARE @amount Decimal(8,2)
DECLARE @price Decimal(8,2)

DECLARE CrsOrfLine CURSOR FOR
SELECT AMOUNT FROM LG_001_01_ORFLINE 
 WHERE LINETYPE    = 0 
 AND ORDFICHEREF = (SELECT TOP 1 LOGICALREF FROM LG_001_01_ORFICHE WHERE GUID='EEB44E72-3717-4F5B-8F7E-6A36EB38EA22')
 ORDER BY LINENO_ ASC;

FETCH NEXT FROM CrsOrfLine INTO  @amount
WHILE (@@FETCH_STATUS = 0) 
BEGIN
     INSERT INTO @Temp (Quantity)

     /* HOW AM I SUPPOSED TO ADD IT INTO THE TEMP?????? */
     /* I COULDNT FIGURE THIS PART OUT                  */

FETCH NEXT FROM CrsOrfLine INTO @amount
END /*WHILE*/
CLOSE CrsOrfLine
DEALLOCATE CrsOrfLine
like image 277
Arif YILMAZ Avatar asked Jul 23 '14 15:07

Arif YILMAZ


2 Answers

You can do the following. Note that it only inserts the quantity so it needs to be modified if you intend to include the price.

DECLARE @Temp TABLE 
(
  Quantity Decimal(8,2), 
  Price Decimal(8,2)
)


INSERT INTO @temp (Quantity)
SELECT AMOUNT FROM LG_001_01_ORFLINE 
WHERE LINETYPE = 0 
AND ORDFICHEREF = (SELECT TOP 1 LOGICALREF FROM LG_001_01_ORFICHE WHERE GUID='EEB44E72-3717-4F5B-8F7E-6A36EB38EA22 ORDER BY LINENO_ ASC')
like image 50
SQLChao Avatar answered Sep 16 '22 16:09

SQLChao


CREATE PROCEDURE [dbo].[usp_demo_cursor_with_temp_table]              
AS              
BEGIN  
DECLARE @temp TABLE  (value1 varchar(5),value2 varchar(5),value3 INT,value4 varchar(1))

DECLARE @value1 varchar(5)
DECLARE @value2 varchar(5) 
DECLARE @value3 INT
DECLARE @value4 varchar(5)

DECLARE check_data_cursor CURSOR FOR 

select distinct value1,value2,value3,value4 from table_name where status = 'A'

OPEN check_data_cursor

FETCH NEXT FROM check_data_cursor INTO @value1,@value2,@value3,@value4

WHILE (@@FETCH_STATUS <> -1)

BEGIN
-- any business logic + temp inseration 

insert into @temp values (@tickerCode,@quarter,@financial_year,@status)
 END 

 FETCH NEXT FROM check_data_cursor  INTO @value1,@value2,@value3,@value4
 END

 CLOSE check_data_cursor

 DEALLOCATE check_data_cursor

 -- to view temp data

 select * from @temp          

END
like image 37
Mohit Jariwal Avatar answered Sep 18 '22 16:09

Mohit Jariwal