Home All Groups Group Topic Archive Search About

Dynamic SQL Statement for Cursor

Author
26 Aug 2005 1:58 PM
Ben
Hi

I have a cursor that I need to pass a dynamic sql statement to that is in a
variable, is this possible?

e.g. DECLARE curOneRecord CURSOR FOR @SQL

Thanks
B

Author
26 Aug 2005 2:19 PM
Tibor Karaszi
Both cursors and dynamic SQL are considered bad practices. Anyhow, if you still want to do this:

EXEC('DECLARE curOneRecord CURSOR FOR ' + SQL)


Show quote
"Ben" <B**@Newsgroups.microsoft.com> wrote in message news:u8pL9ZkqFHA.904@TK2MSFTNGP10.phx.gbl...
> Hi
>
> I have a cursor that I need to pass a dynamic sql statement to that is in a
> variable, is this possible?
>
> e.g. DECLARE curOneRecord CURSOR FOR @SQL
>
> Thanks
> B
>
>
Author
26 Aug 2005 2:31 PM
Alejandro Mesa
Ben,

Do the contrary, open the cursor inside the dynamic sql statement.

Example:

declare @c cursor
declare @sql nvarchar(4000)

set @sql = N'
set @c = cursor for
select
    orderid, customerid, orderdate
from
    dbo.orders
where
    customerid = @customerid; open @c'

exec sp_executesql @sql, N'@c cursor output, @customerid nchar(5)', @c
output, 'alfki'

if cursor_status('variable', '@c') = 1
    begin
    while 1 = 1
        begin
        fetch next from @c

        if @@error != 0 or @@fetch_status != 0 break
        end
    end

if cursor_status('variable', '@c') >= 0
    close @c

deallocate @c
go

The Curse and Blessings of Dynamic SQL
http://www.sommarskog.se/dynamic_sql.html

Did you try to find a set-based solution before using cursors?


AMB

Show quote
"Ben" wrote:

> Hi
>
> I have a cursor that I need to pass a dynamic sql statement to that is in a
> variable, is this possible?
>
> e.g. DECLARE curOneRecord CURSOR FOR @SQL
>
> Thanks
> B
>
>
>
Author
26 Aug 2005 2:32 PM
Jose G. de Jesus Jr MCP, MCDBA
an example ofr dynamic
sql statement. It might help


use northwind
declare @test nvarchar(4000)
declare @values nvarchar (200)
set @values='1,2,3,4'
set @test='select * from employees where employeeid in ('+ (@values)+')'
EXEC(@test)



--


Jose de Jesus Jr. Mcp,Mcdba
Data Architect
Sykes Asia (Manila philippines)
MCP #2324787


Show quote
"Ben" wrote:

> Hi
>
> I have a cursor that I need to pass a dynamic sql statement to that is in a
> variable, is this possible?
>
> e.g. DECLARE curOneRecord CURSOR FOR @SQL
>
> Thanks
> B
>
>
>

AddThis Social Bookmark Button