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


CREATE PROCEDURE [dbo].cs_Thread_Status_Update 
(
	@ThreadID int,
	@Status int = null,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

IF @Status IS NOT NULL
BEGIN

	UPDATE
		cs_Threads
	SET
		ThreadStatus = @Status
	WHERE
		ThreadID = @ThreadID AND SettingsID = @SettingsID

END
ELSE
BEGIN

	IF EXISTS (SELECT * FROM cs_Posts WHERE ThreadID = @ThreadID AND (PostStatus & 64) = 64)
		SET @Status = 1	-- if at least one reply is marked as an answer, mark the thread as answered
	ELSE
		SET @Status = 2	-- otherwise, mark the thread as unanswered

	UPDATE
		cs_Threads
	SET
		ThreadStatus = @Status
	WHERE
		ThreadID = @ThreadID AND SettingsID = @SettingsID

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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