IF EXISTS (SELECT * FROM sys.procedures p WHERE p.name = 'sp_SchetPeriodGen') DROP PROCEDURE [dbo].[sp_SchetPeriodGen]
GO
CREATE PROCEDURE [dbo].[sp_SchetPeriodGen]
	@SchetID uniqueidentifier = NULL,
	@UserID uniqueidentifier = NULL
AS 
BEGIN
	INSERT INTO IES.T_SCHET_PERIOD ([SchetPeriodID], [Year], [Month], [DateCreate], [IsClosed], [User])
	SELECT NEWID(), ts.YEAR, ts.MONTH, GETDATE(), 0, @UserID
	FROM IES.T_SCHET ts
	WHERE (@SchetID IS NULL OR (@SchetID IS NOT NULL AND @SchetID = ts.SchetID))
		AND NOT EXISTS (SELECT 1 FROM IES.T_SCHET_PERIOD tsp WHERE ts.YEAR = tsp.Year AND ts.MONTH = tsp.Month)
	GROUP BY ts.YEAR, ts.MONTH
END