-- dbo.ep_Vyroba_InsertEvidRozpracOper
CREATE PROCEDURE dbo.ep_Vyroba_InsertEvidRozpracOper
     @IDZamestnance INT=NULL,
     @IDPracoviste INT=NULL,
     @IDStroje INT=NULL,
     @CasZahajeni DATETIME=NULL,
     @ErrMsg NVARCHAR(500)=N'' OUT
AS

-- !! proceduru neupravujte, bude stejne pregenerovana pri startu Windows sluzby HDCDZApi !!

SET NOCOUNT ON

DECLARE
 @tranPred INT

DECLARE
 @idEROp INT=NULL


IF EXISTS(SELECT 1 FROM dbo.TabEvidRozpracOper)
  BEGIN
   SELECT @idEROp=MAX(ID) FROM dbo.TabEvidRozpracOper
   DBCC CHECKIDENT(TabEvidRozpracOper, RESEED, @idEROp)
  END
 ELSE
  DBCC CHECKIDENT(TabEvidRozpracOper, RESEED, 1)
SET @idEROp=NULL





IF (@IDPracoviste IS NULL) AND (@IDStroje IS NOT NULL)
 SELECT @IDPracoviste=IDPrac FROM dbo.TabCisStroju WHERE ID=@IDStroje

IF (@IDZamestnance IS NULL) OR (@IDPracoviste IS NULL)
 BEGIN
  SET @ErrMsg = N'Neni zadan zamestnanec nebo pracoviste'
  RETURN NULL
 END

IF OBJECT_ID(N'tempdb..#TabExtKom', N'U') IS NULL
 CREATE TABLE #TabExtKom (Typ TINYINT, Poznamka NVARCHAR(255) NOT NULL DEFAULT N'')



SET @CasZahajeni = ISNULL(@CasZahajeni, GETDATE())


BEGIN TRY
 SET @tranPred = @@TRANCOUNT
 IF (@tranPred=0) BEGIN TRAN

 INSERT dbo.TabEvidRozpracOper (IDZamestnance, CasZahajeni, IDPracoviste, IDStroje)
  SELECT @IDZamestnance, @CasZahajeni, @IDPracoviste, @IDStroje
 SET @idEROp = SCOPE_IDENTITY()

-- slepice
 IF OBJECT_ID(N'dbo.ep_Vyroba_InsertEvidRozpracOper_Po', N'P') IS NOT NULL
  EXEC dbo.ep_Vyroba_InsertEvidRozpracOper_Po @idEROp


 IF (@tranPred=0) ANd (@@TRANCOUNT>0)
  COMMIT TRAN
END TRY
BEGIN CATCH
 IF (@tranPred=0) ANd (@@TRANCOUNT>0)
  ROLLBACK TRAN
 SET @ErrMsg = ERROR_MESSAGE()
 INSERT #TabExtKom (Typ, Poznamka) SELECT 3, @ErrMsg
 SET @idEROp = NULL
END CATCH

RETURN @idEROp
