SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE PROCEDURE dbo.cs_Post_GetRandomPostID
	@SettingsID int,
	@CategoryID int=-1,
	@SectionID int
AS
SET Transaction Isolation Level Read UNCOMMITTED

if @CategoryID = -1
begin
	select top 1 PostID
		from cs_Posts
		where PostID = ParentID
			and SettingsID = @SettingsID
			and SectionID = @SectionID
			order by newid()
end
else
begin
	select P.PostID
		from cs_Posts P
		join cs_Posts_InCategories C on C.PostID = P.PostID
		where P.PostID = P.ParentID
			and P.SettingsID = @SettingsID
			and P.SectionID = @SectionID
			and C.CategoryID = @CategoryID
			order by newid()
end
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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