﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[CCReassignOwner]    Script Date: 11/21/2024 11:29:04 AM ******/
SET
	ANSI_NULLS ON
GO
SET
	QUOTED_IDENTIFIER ON
GO
	CREATE PROCEDURE [dbo].[CCReassignOwner] @PlanNumber int,
	@NewOwnerID int,
	@Comments varchar(500),
	@UserID int AS BEGIN
SET
	NOCOUNT ON;

SET
	XACT_ABORT ON;

BEGIN TRANSACTION
INSERT INTO
	EventLog(
		[IssueID],
		[SysDocumentID],
		[UserID],
		[DocumentType],
		[OperationType],
		[Comments],
		[InsertTimeStamp]
	)
SELECT
	@PlanNumber,
	NULL,
	@UserID,
	'ChangeControl',
	'Reassign Owner',
	LEFT(
		'Owner changed from ' + ISNULL(
			old.LoginID,
			CONVERT(varchar(20), CCChangeControl.OwnerID)
		) + ' to ' + ISNULL(new.LoginID, CONVERT(varchar(20), @NewOwnerID)) + ' by ' + ISNULL(me.LoginID, CONVERT(varchar(20), @UserID)) + ' comments: ' + @Comments,
		500
	),
	GETDATE()
FROM
	CCChangeControl
	LEFT OUTER JOIN Users old ON old.UserID = CCChangeControl.OwnerID
	LEFT OUTER JOIN Users new ON new.UserID = @NewOwnerID
	LEFT OUTER JOIN Users me ON me.UserID = @UserID
WHERE
	CCChangeControl.PlanNumber = @PlanNumber
UPDATE
	CCChangeControl
SET
	OwnerID = @NewOwnerID
WHERE
	PlanNumber = @PlanNumber COMMIT TRANSACTION
END
GO