SSRS Pivot Expression Inside Stored Procedure with HashTemp Not Running - reporting-services

While Working With SSRS, Today, i got 2 Problems 1 is Still remain Unsolved and Im going to Post Another Freaking Problem :) Well, Problem is : I've an Stored Procedure, Which Create an #Temp and Finally Use that data with PIVOT Expression. And, Stored Procedure itself runs Fine inside SSMS and From Visual Basic 6.0 too, but While Using that Procedure from SSRS report it shows an error at the Pivot Expression. Following are the Screen Shots, Please Review and Suggest me an Idea.
Here is an Stored Procedure :
ALTER PROCEDURE [dbo].[S_NRB_9_8_REPORT](#SCRCODE AS VARCHAR(20),
#CUREDATE VARCHAR(10),
#DTNAME VARCHAR(50),
#BR_CODE VARCHAR(50),
#CENTRALIZED VARCHAR(3))
WITH RECOMPILE
AS BEGIN
SET NOCOUNT ON;
DECLARE #BRCODE VARCHAR(3)
DECLARE #DTBASE VARCHAR(50)
DECLARE #CAT_TYPE_CODE VARCHAR(50)
DECLARE #AC_TYPE_SUB_TYPE_NAME VARCHAR(200)
DECLARE #CODESTR VARCHAR (1000)
DECLARE #CODESTR1 VARCHAR (1000)
SET #BRCODE=''
SET #DTBASE=''
SET #AC_TYPE_SUB_TYPE_NAME=''
SET #CODESTR=''
SET #CODESTR1=''
SELECT TOP 1 #CAT_TYPE_CODE=CAT_TYPE_CODE FROM REPORT_CAT_TYPE_CODE WHERE SCREEN_CODE =#SCRCODE
IF #CAT_TYPE_CODE='' OR #CAT_TYPE_CODE IS NULL
RETURN
CREATE TABLE [dbo].[#TEMPACTYPE](
[BR_CODE] [varchar](3) NULL,
[CN] [varchar](50) NULL,
[CS] [varchar](50) NULL,
[BAL] decimal(18, 2) NULL,
[AC_TYPE_SUB_TYPE_NAME] [varchar](50) NULL
) ON [PRIMARY]
IF LEN(#BR_CODE)>0
EXEC('DECLARE CUR INSENSITIVE CURSOR FOR SELECT BR_CODE FROM '+#DTBASE+'.DBO.BRANCH B (NOLOCK) WHERE BR_CODE='''+#BR_CODE+''' AND INTEGRATED=''YES'' AND APPROVED=''YES'' ORDER BY BR_CODE')
ELSE
EXEC('DECLARE CUR INSENSITIVE CURSOR FOR SELECT BR_CODE FROM '+#DTBASE+'.DBO.BRANCH B (NOLOCK) WHERE INTEGRATED=''YES'' AND APPROVED=''YES'' ORDER BY BR_CODE')
OPEN CUR
FETCH NEXT FROM CUR INTO #BRCODE
While ##FETCH_STATUS = 0
Begin
IF #CENTRALIZED='YES'
SET #DTBASE = #DTNAME
ELSE
SET #DTBASE = Left(#DTNAME, 13) + #BRCODE
EXEC('INSERT INTO #TEMPACTYPE
SELECT '''+#BRCODE+''' AS BR_CODE,T1.CAT_NAME AS CN,T1.CODES AS CS,SUM(T1.C_BAL)AS BAL,T1.AC_TYPE_SUB_TYPE_NAME FROM
(SELECT C_BAL,ATST.AC_TYPE_SUB_TYPE_NAME,CD.CAT_NAME,CD.CODE_STRING AS CODES
FROM
(SELECT AC_GROUP_CODE,CUR_CODE,GL_CODE FROM '+#DTBASE+'.dbo.AC_GROUP_GL_MAP WHERE NAMED_AC_CODE =''0301'') MAP,
(SELECT AC_GROUP_CODE,CUR_CODE,AC_NO FROM '+#DTBASE+'.dbo.DEPOSIT_AC_MAST WHERE BR_CODE='''+#BRCODE+''') DAM,
(SELECT TRAN_DATE,AC_NO,GL_CODE,PRODUCT_CODE,SUM(CLS_BAL) AS C_BAL FROM '+#DTBASE+'.dbo.AC_BAL WHERE BR_CODE='''+#BRCODE+''' GROUP BY TRAN_DATE,AC_NO,GL_CODE,PRODUCT_CODE) WD,
(SELECT * FROM '+#DTBASE+'.dbo.CAT_CODING where BR_CODE='''+#BRCODE+''' AND CAT_TYPE_CODE ='''+#CAT_TYPE_CODE+''') AS CC,
(SELECT * FROM '+#DTBASE+'.dbo.AC_TYPE_SUB_TYPE) AS ATST,
(SELECT * FROM '+#DTBASE+'.dbo.AC_GROUP) AS AG,
(SELECT * FROM '+#DTBASE+'.dbo.CAT_DETL) AS CD
WHERE
DAM.AC_GROUP_CODE =MAP.AC_GROUP_CODE
AND DAM.CUR_CODE =MAP.CUR_CODE
AND WD.GL_CODE =MAP.GL_CODE
AND CC.ENTITY_NO=DAM.AC_NO
AND ATST.AC_TYPE_CODE=AG.AC_TYPE_CODE
AND ATST.AC_TYPE_SUB_TYPE_CODE=AG.AC_TYPE_SUB_TYPE_CODE
AND AG.AC_GROUP_CODE=DAM.AC_GROUP_CODE
AND CD.CAT_TYPE_CODE=CC.CAT_TYPE_CODE
AND CD.CAT_CODE=CC.CAT_CODE
AND CD.CAT_TYPE_CODE='''+#CAT_TYPE_CODE+'''
AND WD.TRAN_DATE = (SELECT MAX(TRAN_DATE) FROM '+#DTBASE+'.dbo.AC_BAL WHERE BR_CODE ='''+#BRCODE+''' AND AC_NO = DAM.AC_NO AND TRAN_DATE <='''+#CUREDATE+''' AND GL_CODE=MAP.GL_CODE)
AND DAM.AC_NO=WD.AC_NO
UNION ALL
SELECT 0,ATST.AC_TYPE_SUB_TYPE_NAME,CAT_NAME,CODE_STRING AS CODES FROM '+#DTBASE+'.dbo.CAT_DETL AS CD,'+#DTBASE+'.dbo.AC_TYPE_SUB_TYPE AS ATST
WHERE CAT_TYPE_CODE='''+#CAT_TYPE_CODE+''' AND CAT_CODE NOT IN (SELECT CAT_CODE FROM '+#DTBASE+'.dbo.CAT_CODING WHERE BR_CODE='''+#BRCODE+''' AND CAT_TYPE_CODE='''+#CAT_TYPE_CODE+''')
AND ATST.AC_TYPE_CODE=''03''
) T1
GROUP BY T1.AC_TYPE_SUB_TYPE_NAME,CAT_NAME,CODES
ORDER BY CODES
')
FETCH NEXT FROM CUR INTO #BRCODE
END
DEALLOCATE CUR
DECLARE CUR INSENSITIVE CURSOR FOR SELECT DISTINCT AC_TYPE_SUB_TYPE_NAME FROM #TEMPACTYPE
OPEN CUR
Fetch Next from CUR Into #AC_TYPE_SUB_TYPE_NAME
While ##FETCH_STATUS = 0
Begin
IF #CODESTR =''
BEGIN
SET #CODESTR = 'ISNULL(['+#AC_TYPE_SUB_TYPE_NAME+'],0) AS ['+#AC_TYPE_SUB_TYPE_NAME+']'
SET #CODESTR1 = '['+#AC_TYPE_SUB_TYPE_NAME+']'
END
ELSE
BEGIN
SET #CODESTR = #CODESTR+',ISNULL(['+#AC_TYPE_SUB_TYPE_NAME+'],0) AS ['+#AC_TYPE_SUB_TYPE_NAME+']'
SET #CODESTR1 = #CODESTR1+',['+#AC_TYPE_SUB_TYPE_NAME+']'
END
Fetch Next from CUR Into #AC_TYPE_SUB_TYPE_NAME
END
DEALLOCATE CUR
EXEC ('Select CS,CN,'+#CODESTR+',TOTAL
from (Select CN,CS,BAL,[AC_TYPE_SUB_TYPE_NAME] from #TEMPACTYPE) ps pivot (SUM([BAL])
for [AC_TYPE_SUB_TYPE_NAME] in ('+#CODESTR1+',TOTAL)) pvt
Order by CS')
DROP TABLE #TEMPACTYPE
END
GO
And, the Dataset Design Panel :
But, Stored Procedure Runs Well inside SSMS :
Im Using SSRS 2008 R2.
Please Help me out.
And, Thanks In Advance.

Try validating that you are passing the same parameter values between the report and SSMS. You can do this by clicking Edit Query and inputting the actual parameter values. If the Edit Query window returns proper results, then you are probably passing different values to the stored procedure.

Related

MySQL stored procedure if statement not working

I have the following stored procedure in MySQL
CREATE DEFINER=`test_db`#`%` PROCEDURE `ADD_ATTENDANCE`(IN `programID` INT, IN `clientID` INT, IN `insDate` DATETIME, IN `updDate` DATETIME, IN `insUser` INT, IN `updUser` INT, IN `lessonDate` DATE, IN `lessonTime` TIME)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'Add attedance to my calendar'
BEGIN
DECLARE max_sub, availability INT;
DECLARE cursor_max_sub CURSOR FOR SELECT max_sub FROM app_lesson WHERE id = programID;
DECLARE cursor_availability CURSOR FOR SELECT count(*) FROM attendance WHERE program_id = programID AND lesson_date = lessonDate AND lesson_time = lessonTime;
OPEN cursor_max_sub;
OPEN cursor_availability;
read_loop: LOOP
FETCH cursor_max_sub INTO max_sub;
FETCH cursor_availability INTO availability;
IF (availability < max_sub) THEN
insert into attendance (program_id, client_id, ins_date, upd_date, ins_user, upd_user, lesson_date, lesson_time)
values (programID, clientID, insDate, updDate, insUser, updUser, lessonDate, lessonTime);
LEAVE read_loop;
ELSE
insert into attendance_hold (program_id, client_id, ins_date, upd_date, ins_user, upd_user, lesson_date, lesson_time)
values (programID, clientID, insDate, updDate, insUser, updUser, lessonDate, lessonTime);
END IF;
END LOOP;
CLOSE cursor_max_sub;
CLOSE cursor_availability;
END;
Even though the cursor_max_sub is equal to 6 and the cursor_availability is equal to 4 my procedure always executes the else insert statement. Can you please help me out?
Thanks!!!
OK that was tricky... For some reason when i change the max_sub variable into maxNumberOfSubscription everything worked perfectly... Is max_sub some kind of reserved key word for MySQL or there was a complication because my variable had the same name with the returned field of select statement?

MySQL stored procedure pass select as parameter

could you please give me an advice how to CALL prcd with SELECT results? Or advice me pls better solution.. I am open minded to all working solution
I have a procedure to control inserting data ...
CREATE PROCEDURE control_insert (
)
And I need to pass data from SELECT results to procedure ...
SELECT t.c1, t.c2
FROM table t1
LEFT JOIN other_table t2
ON t1.id = t2.id
WHERE 1=1
The point is, I need to get some data via SELECT (around 6 tables joined to the base table) and I need to do control for each row before insert.. each row should meet some conditions .. if it doesn't meet them, it should just skip it and process next one ...
The procedure should look like:
CREATE PROCEDURE control_insert (
IN v_c1 INT,
IN v_c2 INT
)
BEGIN
IF v_c1 > 1 THEN
INSERT INTO controlled_table (id, type) VALUES (v_c1, v_c2);
ELSE
/* do nothing */
END IF;
END;
CALL control_insert ( SELECT .... );
Could you help me with that? Is there any possibility to do this via MySQL? I can write a PERL skript, but I want to avoid this type of solution ... I just one to do it only in MySQL way
Thank you
EDIT1: I need to check if ID of the SELECT result and LABEL is already in this table for specific date ... this code above is only an example to demonstrate the situation
SOLUTION
I've found the solution ... so for the other visitors:
calling procedure:
CALL controlInsert();
procedure body:
CREATE PROCEDURE controlInsert()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE v_id INT;
DECLARE v_id_dupl INT;
DECLARE v_label INT;
DECLARE v_date DATE;
DECLARE v_type VARCHAR(100);
DECLARE v_category VARCHAR(255);
DECLARE v_user VARCHAR(255);
DECLARE v_country VARCHAR(255);
DECLARE c1 CURSOR FOR SELECT id, label, date, type, category, user, country FROM t1 LEFT JOIN ... /* whole select with 6 joins ended by ; */
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
## open cursor
OPEN c1;
## loop through the cursor
read_loop: LOOP
## fetch cursor into variables
FETCH c1 INTO v_id , v_label, v_date, v_type, v_category, v_user, v_country;
## check if there is any record
IF done THEN
LEAVE read_loop;
END IF;
## get count of existing records
SELECT count(*) INTO v_id_dupl
FROM
WHERE 1=1
AND id = v_id
AND label= v_label
AND date = v_date;
## if v_id_dupl = 0 => no rows found (ok to load)
IF (v_id_dupl = 0) THEN
INSERT INTO target_table (id, label, date, type, category, user, country)
VALUES (v_id , v_label, v_date, v_type, v_category, v_user, v_country);
END IF;
END LOOP;
CLOSE c1;
END
If that is all your stored procedure is doing, then you don't actually need it. You can do the whole thing in a single statement:
INSERT INTO controlled_table (id, type)
SELECT t.c1, t.c2
FROM table t1
LEFT JOIN other_table t2 ON t1.id = t2.id
WHERE something = somethingElse
AND t.c1 > 1
Essentially, I've just combined your original query with the INSERT statement in your procedure.
If your procedure is more complex and needs to do multiple operations on each row, then you should look into using a cursor.

T-SQL function with dynamic SELECT (not possible) - solved with procedure instead

I've managed to use EXEC sp_executesql in a one off statement to do a dynamic lookup, but am unable to adjust the code to create a function since EXEC is not allowed in functions. It works in procedures and I've managed to get output via PRINT for a single lookup by using a temporary table, but really that was just me struggling to find a workaround. Ideally I'd like to be able to create a scalar-value function.
The reason that I need a dynamic lookup is because the column name is stored in another table.
Here's a quick breakdown of the tables:
Questions:
Columns: Q_Group, Q_Nbr, Question_Desc, Data_Field
Sample data: 'R3', 5, 'Do you have any allergies?', 'TXT_04'
Responses:
Columns: Order_Nbr, Q_Group, TXT_01, TXT_02, TXT_03, TXT_04, etc.
Data: 999, 'R3', 'blah', 'blah', 'blah', 'NO'
Orders will be assigned a particular set of questions 'Q_Group' and often a particular question will be the same across various different sets of questions. The problem is that when the set/groups of questions were set up, the questions may not have been added in the same order, and thus the responses go into different columns.
So here's where I'm at...
I can get 'TXT_04' from the Data_Field column in Questions and use EXEC sp_executesql to do a lookup for a single order, but am struggling to find a way to accomplish this as a function of some sort.
DECLARE #col_name VARCHAR(6)
DECLARE #sql VARCHAR(100)
SET #col_name = SELECT Data_Field FROM QUESTIONS WHERE Q_Group = 'R3'
AND Question_Desc = 'Do you have any allergies?'
SET #sql = 'SELECT ' + #col_name + ' FROM RESPONSES WHERE Order_Nbr = 999'
EXEC sp_executesql #sql
I'm just at a loss as to how this could be incorporated into a function so that I could get responses for several orders in a result set. Any workarounds possible? Maybe I'm totally off base using EXEC sp_executesql?
Thanks.
Edit...
Okay, I've changed the title to reflect that I'm going to consider this solved with a procedure instead of a function, as it ended up getting the output that I wanted. Which was a table with all of the corresponding responses.
Here's the code that I settled on. I decided to use LIKE to match the Question_Desc instead of equals, and then included the Question_Desc in the results, so that it could be used a bit more broadly. Thankfully it's pretty quick to run currently. Although that could always change as the database grows!
CREATE PROCEDURE get_all_responses (#question_txt VARCHAR(255))
AS
DECLARE #response_col VARCHAR(35)
DECLARE #t TABLE (order_nbr int, question_txt VARCHAR(255), response_col VARCHAR(35), response VARCHAR(255))
DECLARE #i TABLE (id INT PRIMARY KEY IDENTITY(1,1), response_col VARCHAR(35))
DECLARE #u TABLE (order_nbr int, response VARCHAR(255))
DECLARE #sql VARCHAR(200)
INSERT #t
SELECT Order_Nbr, Question_Desc, Data_Field, NULL
FROM Responses
JOIN (
SELECT Q_Group, Question_Desc, Data_Field
FROM Questions
WHERE Question_Desc LIKE #question_txt
) #Q ON Q_Group = #Q.Q_Group
WHERE Q_Group <> '0'
ORDER BY Data_Field, Order_Nbr
-- Stop if no results found and return empty result set
IF (SELECT COUNT(*) FROM #t) = 0
BEGIN
SELECT order_nbr, question_txt, response FROM #t
RETURN
END
INSERT #i SELECT response_col FROM #t GROUP BY response_col
DECLARE #row_nbr int
DECLARE #last_row int
SET #row_nbr = 1
SET #last_row = (SELECT COUNT(*) FROM #i)
-- Iterate through each Data_Field found
WHILE #row_nbr <= #last_row
BEGIN
SET #response_col = (SELECT response_col FROM #i WHERE id = #row_nbr)
SET #sql = 'SELECT Order_Nbr, ' + #response_col + ' FROM Responses WHERE NullIf(' + #response_col + ','''') IS NOT NULL'
INSERT INTO #u
EXEC (#sql)
UPDATE #t
SET response = y.response
FROM #t AS x
INNER JOIN #u AS y ON x.order_nbr = y.order_nbr
SET #row_nbr = #row_nbr + 1
END
-- Remove results with no responses
DELETE FROM #t WHERE response IS NULL
SELECT order_nbr, question_txt, response FROM #t
RETURN
You will not be able to execute dynamic SQL from within a function but you could do this with a stored procedure and capture the output.
DECLARE #col_name VARCHAR(6), #param NVARCHAR(50), #myReturnValue VARCHAR(50)
SET #param = N'#result VARCHAR(50) OUTPUT'
DECLARE #sql VARCHAR(100)
SET #col_name = SELECT Data_Field FROM QUESTIONS WHERE Q_Group = 'R3'
AND Question_Desc = 'Do you have any allergies?'
SET #sql = 'SELECT #result = ' + #col_name + ' FROM RESPONSES WHERE Order_Nbr = 999'
EXEC sp_executesql #sql, #param, #result = #myReturnValue output
--manipulate value here
print #myReturnValue
You could also create a temp table and do an insert into from exec sp_executesql.

Mysql FETCH CURSOR result ununderstood

I've been Googleing around for a while and I am sure that the problem is that I don't understand clearly how CURSORs in MySQL work.
A short explanation of the problem: I'm writing such function (simplified):
CREATE DEFINER=`me`#`localhost` FUNCTION `product_move`(prID INT, tr_type VARCHAR(2), clID INT, am INT, dnID INT, usrID INT, price FLOAT(10,2), ti DATETIME, barc TINYTEXT, cmt TINYTEXT, lnID INT)
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE cur_id INT;
DECLARE net_pr FLOAT(10,2);
DECLARE cur_r INT;
DECLARE remaind INT DEFAULT 0;
DECLARE avg_price FLOAT(10,2) DEFAULT 0;
DECLARE curs CURSOR FOR SELECT `products_transactionsID`,
`price`,
`remains`
FROM `products_transactions`
WHERE `productID`=prID AND `remains`>0 AND `type`='V'
ORDER BY `products_transactionsID` ASC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN curs;
SET remaind=am;
read_loop:LOOP
FETCH curs INTO cur_id,net_pr,cur_r;
IF done THEN
LEAVE read_loop;
END IF;
IF (cur_r>=remaind) THEN
SET avg_price = avg_price + (net_pr * remaind);
UPDATE `products_transactions` SET `remains`=`remains`-remaind WHERE products_transactionsID=cur_id;
LEAVE read_loop;
ELSE
SET avg_price = avg_price + (net_pr * cur_r);
SET remaind=remaind-cur_r;
UPDATE `products_transactions` SET `remains`=0 WHERE products_transactionsID=cur_id;
END IF;
END LOOP;
CLOSE curs;
SET avg_price=avg_price/am;
INSERT INTO products_transactions
(`products_transactionsID`,`clientID`,`date_created`,`delivery_notesID`,`type`,`productID`,`amountIN`,`amountOUT`,`barcodes`,`in_stock`,`out_stock`,`out_repair`,`out_loss`,`booked`,`ordered`,`userID`,`price`,`comments`,`fifo_buy_price`)
SELECT NULL, clID, ti, dnID , tr_type, prID, 0, am, barc, products_transactions.in_stock-am, products_transactions.out_stock,
products_transactions.out_repair, products_transactions.out_loss, products_transactions.booked, products_transactions.ordered,usrID,price,cmt,avg_price
FROM
products_transactions WHERE productID=prID ORDER BY products_transactionsID DESC LIMIT 1;
So, we insert a new row in this table, based upon some calculations from the previously selected rows and updating these rows meanwhile.
The problem is with the avg_price variable, which should be calculated based on the net_pr variable which is FETCH'ed from the cursor. But somehow, instead of being FETCH'ed from the SELECT, the net_pr variable takes the value of the price input parameter of my function! How is that possible?
My guesses have been so far:
a variable name conflict? Searched through the code but I can't find any.
updating the table within the LOOP could make the CURSOR loose its position? It would make sense, but that wouldn't result in this, either...
I'd apreciate any ideas.
Two things that I can see:
1) Don't update the table that you're using in the cursor. MySQL says the cursor is read only but I wouldn't trust this. Set your value, exit the cursor, and then update the table.
2) Using the same name for a variable in the proc definition and a column in a select gives a conflict: http://dev.mysql.com/doc/refman/5.0/en/local-variable-scope.html
"A local variable should not have the same name as a table column. If an SQL statement, such as a SELECT ... INTO statement, contains a reference to a column and a declared local variable with the same name, MySQL currently interprets the reference as the name of a variable. "

cursor logic in ssis

i have been strugling to convert the following t sql task into an automated ssis package.
i tried implementing using for loop conntainer but while creating the looping logic i am stucking off. i really appreciate of some one could help me out with logic
here is the t- sql code
-- SCRIPT TO BULK IMPORT MATERNAL HLA & INSERT CORD NIMA
IF OBJECT_ID('tempdb..#maternal_hla_from_solar') IS NOT NULL
BEGIN
drop table #maternal_hla_from_solar
END
CREATE TABLE #maternal_hla_from_solar(
[donor_id] [int] NOT NULL,
[antigen_id] [int] NOT NULL
)
-- bulk upload maternal HLA from file
BULK
INSERT #maternal_hla_from_solar
FROM 'C:\Users\zabeenp\Documents\SQL\populate_db\data\20111212_maternal_hla.txt'
WITH
(
FIRSTROW = 2,
MAXERRORS = 0,
FIELDTERMINATOR = '\t',
ROWTERMINATOR = '\n'
)
-- declare variables
DECLARE #donor_id int
DECLARE #maternal_hla varchar(5000)
DECLARE #definitive_type_date date = GETDATE()
DECLARE #modified_on datetime2(7) = GETDATE()
-- Cursor to process each row from #maternal_hla_from_solar
DECLARE c_insertCordNima CURSOR FAST_FORWARD
FOR select DISTINCT donor_id from #maternal_hla_from_solar -- important to use DISTINCT here
OPEN c_insertCordNima
FETCH NEXT FROM c_insertCordNima INTO #donor_id
WHILE ##FETCH_STATUS = 0
BEGIN
SET #maternal_hla = '' -- important to wipe string each time
-- concatenare maternal antigen_ids into one string
SELECT #maternal_hla = COALESCE(#maternal_hla + ',', '') + CONVERT(VARCHAR(10),antigen_id)
FROM #maternal_hla_from_solar
where donor_id = #donor_id
-- remove first comma
SET #maternal_hla = (select right(#maternal_hla,len(#maternal_hla)-1))
-- exec insertCordNIMA SP
EXECUTE insertCordNIMA
#donor_id
,#maternal_hla
,#definitive_type_date
,#modified_on
FETCH NEXT FROM c_insertCordNima INTO #donor_id
END
CLOSE c_insertCordNima
DEALLOCATE c_insertCordNima
maybe try to rewrite the cursor using a Recursive CTE?
http://msdn.microsoft.com/en-us/library/ms186243.aspx