﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[InsertTrainingAssignment]    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].[InsertTrainingAssignment] -- Add the parameters for the stored procedure here
	@TrainingID INT,
	@UserID INT,
	@AssignmentID INT OUTPUT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET
	NOCOUNT ON;

Declare @ecnNumber INT Declare @AttachmentID INT Declare @FullName VARCHAR(100) --Get ECN Number
select
	@ecnNumber = [Training].ECN
from
	Training
where
	TrainingID = @TrainingID
select
	@FullName = ISNULL(FirstName, '') + ' ' + ISNULL(LastName, '')
FROM
	Users
WHERE
	UserID = @UserID --Get All Documents attached to ECN
	create table #tempDocAttachments
	(
		AttachmentID int,
		FileName varchar(300)
	)
set
	rowcount 0
INSERT INTO
	#tempDocAttachments SELECT AttachmentID, FileName FROM ECNAttachment WHERE ECNNumber = @ecnNumber
	-- Create the training assignments
INSERT INTO
	TrainingAssignments (UserID, DateAssigned, TrainingID, FullName)
VALUES
	(@UserID, GETDATE(), @TrainingID, @FullName)
SET
	@AssignmentID = CAST(SCOPE_IDENTITY() AS INT) Declare @getid CURSOR Declare @FileName varchar(300)
SET
	@getid = CURSOR FOR
SELECT
	AttachmentID
FROM
	#tempDocAttachments
	OPEN @getid FETCH NEXT
FROM
	@getid INTO @AttachmentID WHILE @ @FETCH_STATUS = 0 BEGIN
SELECT
	@FileName = FileName
From
	#tempDocAttachments where AttachmentID = @AttachmentID
INSERT INTO
	TrainingDocAcks (
		TrainingAssignmentID,
		ECNNumber,
		AttachmentID,
		FileName
	)
VALUES
	(
		@AssignmentID,
		@ecnNumber,
		@AttachmentID,
		@FileName
	) FETCH NEXT
FROM
	@getid INTO @AttachmentID
END CLOSE @getid DEALLOCATE @getid Drop Table #tempDocAttachments
END
GO