Click to See Complete Forum and Search --> : store procedure with parameter passed to query string


arg03
03-14-2008, 01:10 PM
I am trying to write a store Procedure, which need to pass parameters and I need to build my query string on the base of if ans else condition and need to use cursor.
When I try to declare cursor part of sql string it is not being recognized I am getting an server message Server
Message: Number 557, Severity 16
Server 'DOHPROD1', Procedure 'sp_list2yr_letr', Line 54:
The cursor 'cur_list' can not be used as it could not be found. It is possible that either it was not declared or it is not available in the current context.

How and where I should declare cursor ?

Thanks

e.g.
DROP PROCEDURE sp_list2yr_letr
go

CREATE PROCEDURE sp_list2yr_letr @dt1 varchar(10),@cntyid char(3),
@ndate varchar(7),@age char(1) AS

/* Define the general variables */

declare
@pid numeric(9),
@today VARCHAR(20),
@sql VARCHAR(3000),
@cnt int,
@msg varchar(255)

begin
create TABLE #TwoyearLetr (id numeric(9))

--declare cur_list cursor for





SET @sql = ' '
SET @sql = @sql + ' declare cur_list cursor for '
SET @sql = @sql + 'SELECT p.pat_id FROM Patient p, PatCounty pc ' + " WHERE cnty_status = 'A' " + " AND pat_status = 'I' "

if (@age = '1')
SET @sql = @sql + ' AND p.pat_id = pc.pat_id '

print @sql

exec (@sql)

open cur_list

set @cnt = 0
while (@@sqlstatus !=2)
BEGIN --while
fetch cur_list into @pid

if (@cnt % 100 = 0)
begin
set @msg = "processed 100 records. Current Pat id = " + convert(varchar(9),@pid)
print @msg
if (@pid = null)
return 1
end


END
/* Get todays date */

set @today = convert(varchar(20), getdate(), 110)
--print "Processing Lab records for date: %1!", @today
print "pat id: %1!", @pid

close cur_list
deallocate cursor cur_list
drop Table #TwoyearLetr

end -- Store Procedure

chazzy
03-14-2008, 01:36 PM
Take a look here: http://www.sommarskog.se/dynamic_sql.html#cursor0

But just as a comment: do you really need a cursor in this case?

mattyblah
03-15-2008, 04:39 AM
It'd probably be easier to tell us what you are doing instead of telling us what you need to do (as in you need to use a cursor). I have found no situation where I have ever _needed_ to use a cursor and have read very few situations where cursors are beneficial (The book "Sql Server 2005: T-SQL Programming" lists one or two, and the book is written by a very knowledgeable writer).