1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70:
CREATE PROCEDURE [dbo].[prc_Messages_Response_Select_All] @FromProfileID INT AS BEGIN SET NOCOUNT ON; ;WITH msgs AS ( -- get the first message SELECT 0 as MessageLevel, a.[MessageID], a.[ProfileID], a.[FromProfileID], a.[FromUsername], b.[UserName] AS SentToUserName, a.[Subject], a.[Body], convert(varchar, a.[MsgDate], 107) AS zdate, a.[MsgDate], a.[MsgRead], a.[MsgReplied], a.[MsgNew], a.[ReplyOfMessageID], a.[InitialMessageID] FROM [tbl_Messages] a INNER JOIN [tbl_Profile] b ON a.[ProfileID] = b.[ProfileID] WHERE a.[FromProfileID] = @FromProfileID -- recursive CTE portion UNION ALL SELECT m.MessageLevel + 1, a.[MessageID], a.[ProfileID], a.[FromProfileID], a.[FromUsername], b.[UserName] AS SentToUserName, a.[Subject], a.[Body], convert(varchar, a.[MsgDate], 107) AS zdate, a.[MsgDate], a.[MsgRead], a.[MsgReplied], a.[MsgNew], a.[ReplyOfMessageID], a.[InitialMessageID] FROM [tbl_Messages] a INNER JOIN [tbl_Profile] b ON a.[ProfileID] = b.[ProfileID] INNER JOIN msgs m ON a.[ReplyOfMessageID] = m.[MessageID] OR a.[InitialMessageID] = m.[MessageID] -- may not need this ) SELECT * FROM msgs ORDER BY MessageLevel, [MsgDate] DESC ; END