在存储过程中使用内部连接逗号分隔值

时间:2013-03-17 09:09:24

标签: sql-server database sql-server-2008 stored-procedures inner-join

我有一个表UserMaster,如下所示......(只显示所需的列)

UserID UserName EmailID
---------------------------------
1000   amol     amol@gmail.com
1001   mahesh   mahesh@gmail.com
1002   saurabh  saurabh@gmail.com
1003   nitesh   nitesh@gmail.com

另一个表MessageHistory(仅显示必需的列)

MsgCode From  To
-----------------------------
MSG001  1000  1001,1002,1003
MSG002  1001  1000,1002,1003

我将UserIds存储在FromTo列中......

我正在尝试创建一个存储过程来显示特定消息代码的Email History

Create Procedure proc_GetMessageHistory
        @MsgCode varchar(50)
        as
        Begin
           Select * From MessageHistory Where MsgCode=@MsgCode 
        End

结果如上所示MessageHistory表...但我想显示相应的UserEmailIDs而不是UserID(例如'amol@gmail.com'而不是1000 )...

我怎样才能在存储过程中执行此操作?在这种情况下,我如何使用内部连接特别使用逗号分隔值?请帮忙......谢谢

1 个答案:

答案 0 :(得分:1)

正如大家已经注意到的那样,这绝不应该是任何永久的解决方案,因为它无法以有效的方式执行。此外,这种非规范化结构可能会有许多问题。那说......

每封邮件的电子邮件地址列表,即每行一位收件人:

select m.MsgCode
  , sender = s.EmailID
  , recipient = u.EmailID
from MessageHistory m
  inner join UserMaster s on m.[From] = s.UserID
  inner join UserMaster u on charindex(cast(u.UserID as varchar), m.[To]) > 0

SQL Fiddle with demo

邮件列表,逗号分隔的电子邮件地址列表,每行一封邮件:

with emails as
(
  select m.MsgCode
    , recipient = u.EmailID
  from MessageHistory m
    inner join UserMaster u on charindex(cast(u.UserID as varchar), m.[To]) > 0
)
select m.MsgCode
  , [From] = u.EmailID
  , [To] = stuff
    (
      (
        select ',' + recipient
        from emails e
        where m.MsgCode = e.MsgCode
        for xml path('')
      )
      , 1
      , 1
      , ''
    )
from MessageHistory m
  inner join UserMaster u on m.[From] = u.UserID

SQL Fiddle with demo