﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[CCInsertChangeControl]    Script Date: 11/21/2024 11:29:04 AM ******/
SET
	ANSI_NULLS ON
GO
SET
	QUOTED_IDENTIFIER ON
GO
	-- =============================================
	-- Author:		<Author,,Name>
	-- Create date: <Create Date,,>
	-- Description:	<Description,,>
	-- =============================================
	CREATE PROCEDURE [dbo].[CCInsertChangeControl] -- Add the parameters for the stored procedure here
	@OwnerID INT,
	@PlanNumber INT OUT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET
	NOCOUNT ON;

-- Insert statements for procedure here
BEGIN DECLARE @CurrentYear INT DECLARE @CurrentYearlyIdentifier INT DECLARE @NextYearlyIdentifier INT DECLARE @MesaPlanNo VARCHAR(20)
SET
	@CurrentYear = YEAR(GETDATE()) IF EXISTS (
		Select
			*
		FROM
			CCCurrentSequence
		WHERE
			year = @CurrentYear
	) BEGIN
SET
	@CurrentYearlyIdentifier = (
		SELECT
			currentSequence
		FROM
			CCCurrentSequence
		WHERE
			year = @CurrentYear
	) + 1
UPDATE
	CCCurrentSequence
SET
	currentSequence = @CurrentYearlyIdentifier
WHERE
	year = @CurrentYear
END
ELSE BEGIN
SET
	@CurrentYearlyIdentifier = 1
INSERT INTO
	CCCurrentSequence (year, currentSequence)
VALUES
	(@CurrentYear, @CurrentYearlyIdentifier)
END
END
SET
	@MesaPlanNo = CONCAT(
		'M-',
		@CurrentYear,
		'-',
		REPLICATE('0', 4 - LEN(RTRIM(@CurrentYearlyIdentifier))) + RTRIM(@CurrentYearlyIdentifier)
	)
INSERT INTO
	CCChangeControl (OwnerID, PlanYearlyIdentifier, MesaPlanNo)
VALUES
	(@OwnerID, @CurrentYearlyIdentifier, @MesaPlanNo)
SET
	@PlanNumber = CAST(SCOPE_IDENTITY() AS INT)
INSERT INTO
	CCAttachment (PlanNumber, Title, RequirementsNotes)
SELECT
	@PlanNumber,
	CCAttachmentTitle,
	CCAttachmentRequirementNotes
FROM
	CCAttachmentDefaults -- Add the three PCRB's automatically
	-- PCR 1
INSERT INTO
	CCPCRB (PlanNumber, PCRB)
VALUES
	(@PlanNumber, 'PCR1')
UPDATE
	CCChangeControl
set
	PCR1ID = CAST(SCOPE_IDENTITY() AS INT)
WHERE
	PlanNumber = @PlanNumber
INSERT INTO
	CCPCRBAttendee (PCRBID, AttendeeName, JobTitle, Location)
SELECT
	CAST(SCOPE_IDENTITY() AS INT),
	AttendeeName,
	PCRBAttendeeJobTtile,
	Location
FROM
	CCPCRBAttendeeJobTitle
INSERT INTO
	CCPCRB (PlanNumber, PCRB)
VALUES
	(@PlanNumber, 'PCR2')
UPDATE
	CCChangeControl
set
	PCR2ID = CAST(SCOPE_IDENTITY() AS INT)
WHERE
	PlanNumber = @PlanNumber
INSERT INTO
	CCPCRBAttendee (PCRBID, AttendeeName, JobTitle, Location)
SELECT
	CAST(SCOPE_IDENTITY() AS INT),
	AttendeeName,
	PCRBAttendeeJobTtile,
	Location
FROM
	CCPCRBAttendeeJobTitle
INSERT INTO
	CCPCRB (PlanNumber, PCRB)
VALUES
	(@PlanNumber, 'PCR3')
UPDATE
	CCChangeControl
set
	PCR3ID = CAST(SCOPE_IDENTITY() AS INT)
WHERE
	PlanNumber = @PlanNumber
INSERT INTO
	CCPCRBAttendee (PCRBID, AttendeeName, JobTitle, Location)
SELECT
	CAST(SCOPE_IDENTITY() AS INT),
	AttendeeName,
	PCRBAttendeeJobTtile,
	Location
FROM
	CCPCRBAttendeeJobTitle
END
GO