SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE procedure [dbo].[cs_User_Rename]
(
	@UserID					int,
	@DesiredUserName		nvarchar(256),
	@IgnoreDisallowedNames	bit = 0
)
AS
	-- do we care about disallowed names?
	IF (@IgnoreDisallowedNames = 0)
		-- is username allowed?
		IF EXISTS (SELECT * FROM cs_DisallowedNames WHERE @DesiredUserName LIKE REPLACE(DisallowedName, '*', '%'))
		BEGIN
			SELECT 3 -- DisallowedUserName
			RETURN
		END


	-- is the desired username available?
	IF EXISTS (SELECT * FROM aspnet_Users WHERE LoweredUserName = LOWER(@DesiredUserName) AND ApplicationId = (SELECT ApplicationId FROM aspnet_Users ASP INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID WHERE CS.UserID = @UserID) AND UserId <> (SELECT CS2.MembershipID FROM cs_Users CS2 WHERE CS2.UserID = @UserID)) -- username is taken
	BEGIN
		SELECT 2 -- DuplicateUserName
		RETURN
	END


	-- username is available, begin update
	BEGIN TRANSACTION


	-- handle ASP.NET membership system
	UPDATE	aspnet_Users
	SET	UserName = @DesiredUserName, LoweredUserName = LOWER(@DesiredUserName)
	FROM	aspnet_Users ASP INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID
	WHERE	CS.UserID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle posts
	UPDATE	cs_Posts
	SET	PostAuthor = @DesiredUserName
	WHERE	UserID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle post archive
	UPDATE	cs_PostsArchive
	SET	UserName = @DesiredUserName
	FROM	cs_PostsArchive PA INNER JOIN aspnet_Users ASP ON PA.UserName = ASP.UserName INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID
	WHERE	CS.UserID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle sections
	UPDATE	cs_Sections
	SET	MostRecentPostAuthor = @DesiredUserName
	WHERE	MostRecentPostAuthorID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle threads
	UPDATE	cs_Threads
	SET	MostRecentPostAuthor = @DesiredUserName
	WHERE	MostRecentPostAuthorID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	UPDATE	cs_Threads
	SET	PostAuthor = @DesiredUserName
	WHERE	UserID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle blogs
	UPDATE	cs_weblog_Weblogs
	SET	MostRecentArticleAuthor = @DesiredUserName
	WHERE	MostRecentArticleAuthorID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	UPDATE	cs_weblog_Weblogs
	SET	MostRecentPostAuthor = @DesiredUserName
	WHERE	MostRecentPostAuthorID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- be sure posts are reindexed
	EXECUTE cs_Posts_ReindexByUser @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- no problems occurred
	COMMIT TRANSACTION
	SELECT 1 -- Success
	RETURN


Failure:
	-- something went wrong
	ROLLBACK TRANSACTION
	SELECT 0 -- UnknownFailure
	RETURN


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_User_Rename] TO PUBLIC
GO