SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE PROC [dbo].cs_Feed_AddFeed
	@FolderId INT = NULL,
	@UserId INT,
	@Url NVARCHAR(255),
	@SettingsID INT,
	@FeedId INT OUTPUT
AS


DECLARE @NewFeedId INT


-- First, let's see if the feed is already registered.
SELECT @NewFeedId = FeedId
FROM cs_Feed
WHERE Url = @Url and SettingsID = @SettingsID


-- If it's not, let's insert it and grab the FeedId.
IF (@NewFeedId IS NULL)
  BEGIN
	
	-- Insert it.
	INSERT INTO cs_Feed
	(
		Url,
		SettingsID
	) 
	VALUES
	(
		@Url,
		@SettingsID
	)

	-- Grab the identity generated.
	SELECT @NewFeedId = @@IDENTITY

  END

-- Add the feed to the user's folder.
INSERT INTO cs_FolderFeed
(
	UserId,
	FolderId,
	FeedId,
	SettingsID
)
VALUES
(
	@UserId,
	@FolderId,
	@NewFeedId,
	@SettingsID
)

SELECT @FeedId = @NewFeedId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_AddFeed  TO PUBLIC
GO
