1

我有一个如下表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

我正在存储UserIdsFromTo...

我正在尝试创建一个存储过程来显示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)......

我怎么能在存储过程中做到这一点?在这种情况下,我如何特别使用逗号分隔值的内连接?请帮助...谢谢

4

1 回答 1

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 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 与演示

于 2013-03-17T12:11:58.240 回答