游标使用 和sp_executesql动态sql

/****** Script for SelectTopNRows command from SSMS  ******/
declare @oid int 
declare @cid int 
declare @tb table(
oid int not null primary key,
cid int  not null

)
declare c cursor for 
SELECT TOP 100 [orderid]
      ,[custid]
    
  FROM [TSQLFundamentals2008].[Sales].[Orders] order by orderid asc
  
  open c
  fetch next from c into @oid,@cid
  while @@FETCH_STATUS=0
  begin
  print @oid
  insert into @tb values(@oid,@oid)
    fetch next from c into @oid,@cid
  end
  close c
  
  deallocate c
  
  select * from @tb
  
  -----动态sql
  select * from Sales.Orders
  
  declare @id int =10250
  declare @cid int  
  declare @sql nvarchar(1000) ='select @cid=custid from sales.orders where orderid=@id'
  exec sp_executesql @sql,N'@id int, @cid int output ',@id,@cid out 
  
 

 

posted @ 2015-11-20 13:46  甜菜波波  阅读(404)  评论(0编辑  收藏  举报