SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

--exec dbo.cs_LinkCategory_CreateUpdateDelete @LinkCategoryID = 3, @DeleteLinkCategory = 1

CREATE PROCEDURE dbo.cs_LinkCategory_CreateUpdateDelete
	@DeleteLinkCategory bit=0,
	@SectionID int,
	@Name nvarchar(256)='',
	@Description nvarchar(2000)=null,
	@IsEnabled bit=1,
	@SortOrder int=0,
	@SettingsID int,
	@LinkCategoryID int=0 out
AS
SET Transaction Isolation Level Read UNCOMMITTED

-- Are we deleting?
if @DeleteLinkCategory = 1
begin
	DELETE FROM cs_Links WHERE LinkCategoryID = @LinkCategoryID and SettingsID = @SettingsID
	DELETE FROM cs_LinkCategories WHERE LinkCategoryID = @LinkCategoryID and SectionID = @SectionID and SettingsID = @SettingsID
	RETURN
end

-- Are we updating?
if @LinkCategoryID > 0
begin
	UPDATE cs_LinkCategories SET
		[Name] = @Name,
		[Description] = @Description,
		IsEnabled = @IsEnabled,
		SortOrder = @SortOrder
	WHERE LinkCategoryID = @LinkCategoryID and SectionID = @SectionID and SettingsID = @SettingsID
end
else
begin
	If( @SortOrder = 0 )
	Begin
		Select @SortOrder = max(SortOrder) + 1 from cs_LinkCategories where SectionID = @SectionID and SettingsID = @SettingsID

		if(@SortOrder is null)
			Select	@SortOrder = 0
	End
	INSERT INTO cs_LinkCategories (SectionID, [Name], [Description], IsEnabled, SortOrder, SettingsID)
		VALUES (@SectionID, @Name, @Description, @IsEnabled, @SortOrder, @SettingsID)
	set @LinkCategoryID = @@IDENTITY
end


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_LinkCategory_CreateUpdateDelete] to public
go