在循环上需要T-SQL帮助

时间:2017-02-21 19:18:09

标签: sql sql-server tsql

我有一个票务数据库,我正在编写一个存储过程来提醒我的团队中的每个成员是否有任何打开的票证。

我有选择查询来查找当天的打开门票。我必须按用户名对门票进行分组,并向每个人发送电子邮件。 (例如,如果我在队列中打开3张票,我想构建一个表并向我发送3行而不是3封电子邮件。)

请指导我为了循环每个团队成员而应该考虑哪些功能/关键字。我正在研究While循环,但看不出它对我有什么帮助。

到目前为止,我的想法是创建一个表变量来填充必要的数据。

在循环中,

Select blah blah WHERE user = @user

TSQL - 构建HTML表格发送电子邮件至@user

我遇到了如何遍历每个用户!任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

declare @user as table (username varchar(10)  , email varchar (20))
declare @ticket as table (username varchar(10)  , ticketnumber varchar (20))
insert into @user values('A','a.com')
insert into @user values('b','b.com')

insert into @ticket values('A','t1')
insert into @ticket values('A','t2')
insert into @ticket values('b','t3')

 declare @ticketNumber as varchar(100) 
 declare @userName as varchar(100)
 declare @user_cursor cursor
 declare @inner_cursor cursor
 declare @fetch_user_cursor int
 declare @fetch_inner_cursor int

 declare user_cursor cursor static local for 
 SELECT 
       username
  FROM @user

  /*loop through top level cursor*/
  open user_cursor
  fetch next from user_cursor into @userName
  select @fetch_user_cursor = @@FETCH_STATUS

  while @fetch_user_cursor = 0
  begin
    print @userName

     /*loop through second level cursor*/
     set @inner_cursor  = cursor static local for 
     select ticketnumber from @ticket where username = @userName


     open @inner_cursor
     fetch next from @inner_cursor into @ticketNumber
     set @fetch_inner_cursor = @@FETCH_STATUS
     while @fetch_inner_cursor = 0
     begin

      print @ticketNumber

      fetch next from @inner_cursor into @ticketNumber
      set @fetch_inner_cursor = @@FETCH_STATUS
     end
     close @inner_cursor
     deallocate @inner_cursor

     fetch next from user_cursor into @userName
     set @fetch_user_cursor = @@FETCH_STATUS


  end