Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Dynamic SQL

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2002-08-19 : 09:18:19
Mala writes "Hi,

I would like to know if fetch statement included in Dynamic SQL will work or not as I am getting 'Must declare variable' error.

I have to perform acion something like this:

declare @id varchar(10),@name varchar(10),@sql nvarchar(1000),@string1 varchar(100),@string2 varchar(120)


set @id=''
set @name=''
set @string1='id,name'
set @string2='@id,@name'



set @sql=''
set @sql='declare read_globe cursor for
select '+@string1+' from global'

exec sp_executesql @sql

open read_globe

set @sql=''
set @sql='fetch next from read_globe into '+@string2

exec sp_executesql @sql

At this point I am getting above said error. I have to make declaration of cursor and fecth dynamic, as @string1 and @string2 values I will be getting from another SP.

Please let me know how handle this or is there any way out.

Thanks in advance.

Bye,

Mala"

nr
SQLTeam MVY

12543 Posts

Posted - 2002-08-19 : 10:25:17
Why not put in a temp table instead of using a cursor?
As you have it the cursor is declared in a separate batch so will not be available.

select identity(int,1,1) as id, * into #a from Global where 1 = 0
need to make sure all fields are nullable.
set @sql = 'insert #a (' + @string1 + ') select ' + @string1 + ' from Global'
exec (@sql)

Now you can call another sp or dynamic sql to access the data using the id if you need row by row.

Can't help thinking you are going down a wrong path here though.


==========================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page
   

- Advertisement -