
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		marek
-- Create date: 22/07/2009
-- Description:	Dodaje lub uaktualnia rekord zmiany emisji w tabeli ZmianyEmisji
-- =============================================
ALTER PROCEDURE [dbo].[sp_AddUpdateIssueChange]
	-- Add the parameters for the stored procedure here
	@issueId DECIMAL(18,0),
	@currentIssueNumer INT,
	@newIssueNumber INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DECLARE @rows INT

	SELECT @rows = COUNT(Id) FROM zmianyEmisji WHERE idEmisji=@issueId AND YEAR(dataZmiany)=YEAR(GETDATE()) AND MONTH(dataZmiany)=MONTH(GETDATE())

	IF @rows>0
		BEGIN
			UPDATE zmianyEmisji 
			SET nastNrWyd=@newIssueNumber, dataZmiany=GETDATE()
			WHERE idEmisji=@issueId AND YEAR(dataZmiany)=YEAR(GETDATE()) AND MONTH(dataZmiany)=MONTH(GETDATE())

			--sprawdz czy nowy numer emisji nie jest taki sam jak stary numer, jesli tak to usun zmiane emisji
			DECLARE @issueNumber INT
			SELECT @issueNumber=popNrWyd FROM zmianyEmisji WHERE idEmisji=@issueId AND YEAR(dataZmiany)=YEAR(GETDATE()) AND MONTH(dataZmiany)=MONTH(GETDATE())
			IF @issueNumber=@newIssueNumber
				DELETE FROM zmianyEmisji WHERE idEmisji=@issueId AND YEAR(dataZmiany)=YEAR(GETDATE()) AND MONTH(dataZmiany)=MONTH(GETDATE())
		END
	ELSE 
		BEGIN
			INSERT INTO zmianyEmisji(idEmisji, popNrWyd, nastNrWyd, dataZmiany)
			VALUES(@issueId, @currentIssueNumer, @newIssueNumber, GETDATE())
		END

END
GO

SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

