SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserFeed_DeleteFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserFeed_DeleteFeed]
GO


CREATE PROC [dbo].cs_UserFeed_DeleteFeed
 @UserId INT,  
 @FeedId INT,
 @SettingsID INT  
AS  
  
DELETE  
FROM cs_UserReadPost  
WHERE UserId = @UserId  
  AND FeedPostId IN (SELECT FeedPostId FROM cs_FeedPost WHERE FeedId = @FeedId)  
  
DELETE  
FROM cs_FolderFeed  
WHERE FolderFeedId IN (
  SELECT FolderFeedId
  FROM cs_FolderFeed
  WHERE UserId = @UserId
    AND FeedId = @FeedId
) 



if not exists(Select FolderFeedId FROM cs_FolderFeed where FeedId = @FeedID and SettingsID = @SettingsID)
BEGIN
	Delete FROM cs_FeedPost where FeedID = @FeedID
	Delete FROM cs_Feed where FeedID = @FeedId
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_UserFeed_DeleteFeed  TO PUBLIC
GO
