StoredProcedure返回一些记录并为表中的每一行插入一行

时间:2014-04-04 09:16:06

标签: sql tsql

我使用此Schema在带有SQLServer 2012数据库的asp.net MVC 4应用程序中执行消息系统。

Schema

现在我有2个问题。当我从线程会话中选择所有消息时,我应该在表MessageReadyState中插入一条记录。

这是我通过ThreadId获取消息的StoredProcedure

  SELECT TOP(@NumberMessage)
  Message.MessageId
, Message.CreateDate
, Message.Body,Person.Name , Person.Surname,Utente.ID,MessageThread.MessageThreadId as MessageThreadID
, [User].Username,User.[Path] , Person.Image
, (SELECT MessageReadState.ReadDate 
   FROM MessageReadState 
   WHERE MessageReadState.MessageId = Message.MessageId 
     and MessageReadState.UserId = @UserId) as ReadState
FROM (Message INNER JOIN [Utente] ON Message.SenderUserId = [Utente].ID 
       INNER JOIN MessageThread ON MessageThread.MessageThreadId = Message.MessageThreadId
              INNER JOIN Person ON Person .ID = User.Id_person) 
WHERE ([Message].MessageThreadId=@ThreadId)
ORDER BY Message.CreateDate DESC;
END

现在存储过程应该返回select,但是对于每行应该在MessageReadState中插入一行,我该怎么做?

编辑:当然,这应该仅在我第一次阅读邮件时完成。我想知道在数据库架构方面是否有更好的解决方案。 另一个问题..

我怎么知道用户是否有新闻消息? 我的意思是我应该检查一个在MessageReadState中没有行的线程中的消息?

由于

1 个答案:

答案 0 :(得分:0)

您需要做的就是将查询结果放在临时表中,然后插入UserId& MessageId进入MessageReadState,通过检查它们是否为NULL来检查组合MessageId / UserId是否已经存在。

SELECT TOP(@NumberMessage)
      Message.MessageId
    , Message.CreateDate
    , Message.Body,Person.Name , Person.Surname,Utente.ID,MessageThread.MessageThreadId as MessageThreadID
    , [User].Username,User.[Path] , Person.Image
    , (SELECT MessageReadState.ReadDate 
       FROM MessageReadState 
       WHERE MessageReadState.MessageId = Message.MessageId 
         and MessageReadState.UserId = @UserId) as ReadState
    INTO #messages
    FROM (Message INNER JOIN [Utente] ON Message.SenderUserId = [Utente].ID 
           INNER JOIN MessageThread ON MessageThread.MessageThreadId = Message.MessageThreadId
                  INNER JOIN Person ON Person .ID = User.Id_person) 
    WHERE ([Message].MessageThreadId=@ThreadId)
    ORDER BY Message.CreateDate DESC;

    INSERT INTO MessageReadState
    (
      MessageId,
      UserId,
      MessageReadData
    )
    SELECT MessageId,
           UserId,
           'read data'
    FROM #messages m
    LEFT JOIN MessageReadState mrd
      on m.MessageId = mrd.MessageId
      and m.UserId = mrd.UserId
    WHERE mrd.MessageId IS NULL AND mrd.UserId IS NULL;

    DROP TABLE #Messages;