求助,游标 declare @sqlstrselect varchar(8000)
declare @sqlstrFrom varchar(8000)
declare @sqlstr varchar(8000)
set @sqlstr =''
declare @d int
set @d = 2
declare @count int
set @count =1
set @sqlstrselect ='select a,b,c'
set @sqlstrFrom = ' from test1.dbo.tb1 where 1=1'
if(isnull(@d,'')<>'')
begin
set @sqlstr=@sqlstr+' and test1.dbo.tb1.d >= @d'
end
--print @sqlstrselect+@sqlstrFrom+@sqlstr
--出来的结果 select a,b,c from test1.dbo.tb1 where 1=1 and test1.dbo.tb1.d >= @d
declare @a nvarchar(50),@b nvarchar(50),@c nvarchar(50)
Declare Purchase_cursor Cursor For
--select a,b,c from test1.dbo.tb1 where 1=1 and test1.dbo.tb1.d >= @d 用这个不会错
execute (@sqlstrselect+@sqlstrFrom+@sqlstr) --这个时候是报错的
Open Purchase_cursor
DECLARE @id VARCHAR(100)
EXEC('declare cur cursor for select id from test')
OPEN cur
FETCH NEXT FROM cur INTO @id
WHILE @@FETCH_STATUS=0
BEGIN
PRINT @id
FETCH NEXT FROM cur INTO @id
END
CLOSE cur
DEALLOCATE cur
------解决方案-------------------- set @sqlstr=@sqlstrselect+@sqlstrFrom+@sqlstr
EXEC sp_executesql @sqlstr,N'@d int',@d ------解决方案--------------------
把 EXEC sp_executesql @sqlstr改成
set @s='
Declare Purchase_cursor Cursor For '+@sqlstr
exec(@s)
不知道这样有没有达到你要的目的