
--BEFORE CODE 03.07.2014
--Таблица pkg_post_date
IF not exists(select * from sysobjects where id = object_id('[dbo].[PKG_POST_DATE]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[PKG_POST_DATE] (
	[LINK] INT  NOT NULL IDENTITY(1,1) ,
	[link_PKG] int NOT NULL ,
	[link_POST] int NOT NULL ,
	[date_begin] datetime NOT NULL )
GO

	GRANT SELECT, UPDATE, DELETE ON dbo.[pkg_post_date] TO PUBLIC
	
GO

--Расширенные свойства--
--Индексы
IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_PKG_POST_DATE')
CREATE UNIQUE CLUSTERED INDEX [IX_PKG_POST_DATE] ON [dbo].[PKG_POST_DATE] ([link_PKG],[link_POST],[date_begin])
GO
--Констрэйнты
IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[PK_PKG_POST_DATE]'))
ALTER TABLE [dbo].[PKG_POST_DATE] 
ADD CONSTRAINT [PK_PKG_POST_DATE] PRIMARY KEY NONCLUSTERED ([LINK])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_PKG_POST_DATE_PKG_POST]'))
ALTER TABLE [dbo].[PKG_POST_DATE] 
ADD CONSTRAINT [FK_PKG_POST_DATE_PKG_POST] FOREIGN KEY ([link_PKG]) REFERENCES [dbo].[PKG_POST] ([link]) ON DELETE CASCADE 
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_PKG_POST_DATE_POST]'))
ALTER TABLE [dbo].[PKG_POST_DATE] 
ADD CONSTRAINT [FK_PKG_POST_DATE_POST] FOREIGN KEY ([link_POST]) REFERENCES [dbo].[POST] ([link]) ON DELETE CASCADE 
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[UN_PKG_POST_DATE_UNIQ]'))
ALTER TABLE [dbo].[PKG_POST_DATE] 
ADD CONSTRAINT [UN_PKG_POST_DATE_UNIQ] UNIQUE([link_POST],[date_begin])
GO


IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[DF_PKG_POST_DATE_DATEBEGIN]'))
ALTER TABLE [dbo].[PKG_POST_DATE] 
ADD CONSTRAINT DF_PKG_POST_DATE_DATEBEGIN DEFAULT ('20000101') FOR [DATE_BEGIN]
GO



--Триггеры

GO




--------------------------------------------------

-- ЕСЛИ поля LINK_PKG уже нет в [POST] (если повторно обновляется база поставим пустое поле в POST, для выполнения проверки)
IF COLUMNPROPERTY(object_id('[dbo].[POST]'), 'LINK_PKG', 'AllowsNull') IS null
	ALTER TABLE [dbo].[POST] ADD [LINK_PKG] INT NULL
	
GO
	
	-- разовое обновление таблицы 
	IF EXISTS (SELECT * FROM dbo.PKG_POST WHERE  link not IN (select link_PKG from dbo.PKG_POST_DATE))
	INSERT INTO dbo.PKG_POST_DATE (link_PKG,link_POST, date_begin)
		SELECT link_PKG = pkg.link,
			link_POST = p.LINK,
			date_begin = '20000101'
		FROM dbo.PKG_POST pkg 
		INNER JOIN dbo.POST p  ON p.LINK_PKG = pkg.link
		WHERE pkg.link NOT IN (select link_PKG from dbo.PKG_POST_DATE)


GO

------------------------------------------------------------------

-------------- подготовка к удалению поля LINK_PKG из таблицы POST  
--- убираем индекс из таблицы 
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_POST_LINK_PKG')
drop INDEX [IX_POST_LINK_PKG] ON [dbo].[POST] 
GO

--- убираем констрейнт из таблицы 
IF  EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_POST_PKG_POST]'))
ALTER TABLE [dbo].[POST] drop CONSTRAINT [FK_POST_PKG_POST] 
GO

-- удаление поля  link_PKG из таблицы POST 
IF COLUMNPROPERTY(object_id('[dbo].[POST]'), 'LINK_PKG', 'AllowsNull') IS not null
	ALTER TABLE [dbo].[POST] DROP COLUMN LINK_PKG
GO



------------------------------------------------------------------


GO

IF  EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[PK_PAYS_EMPL]'))
ALTER TABLE [dbo].[PAYS_EMPL] DROP CONSTRAINT [PK_PAYS_EMPL]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[PK_PAYS_EMPL]'))
ALTER TABLE [dbo].[PAYS_EMPL] 
ADD CONSTRAINT [PK_PAYS_EMPL] PRIMARY KEY NONCLUSTERED ([LINK]) ON [INDEX]
GO

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_PAYS_EMPL_2')
	DROP INDEX [IX_PAYS_EMPL_2] ON [dbo].[PAYS_EMPL]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_PAYS_EMPL_2')
CREATE CLUSTERED INDEX [IX_PAYS_EMPL_2] ON [dbo].[PAYS_EMPL] ([LINK_EMPL], [LINK_SOVM], [LINK_PAYS], [DATE])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_PAYS_EMPL')
CREATE INDEX [IX_PAYS_EMPL] ON [dbo].[PAYS_EMPL] ([LINK_MP]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_PAYS_EMPL_1')
CREATE INDEX [IX_PAYS_EMPL_1] ON [dbo].[PAYS_EMPL] ([LINK_PAYS]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_PAYS_EMPL_LINK_KBK')
CREATE INDEX [IX_PAYS_EMPL_LINK_KBK] ON [dbo].[PAYS_EMPL] ([LINK_KBK]) ON [INDEX]
GO


GO
IF COLUMNPROPERTY(object_id('[dbo].[SDOC_AVAC]'), 'DATE_END', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[SDOC_AVAC] ADD [DATE_END] datetime NULL 
GO

GO
--Добавление колонки [OSOB_SPO] в таблицу SZV4_stazh
IF COLUMNPROPERTY(object_id('[dbo].[SDOC_VEDOM_DGH]'), 'LINK_EKR', 'AllowsNull') is null
	ALTER TABLE [dbo].[SDOC_VEDOM_DGH] ADD [LINK_EKR] int NULL 
GO


IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_SDOC_VEDOM_DGH_LINK_EKR')
CREATE INDEX [IX_SDOC_VEDOM_DGH_LINK_EKR] ON [dbo].[SDOC_VEDOM_DGH] ([LINK_EKR]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SDOC_VEDOM_DGH_KOSGU]'))
ALTER TABLE [dbo].[SDOC_VEDOM_DGH] 
ADD CONSTRAINT [FK_SDOC_VEDOM_DGH_KOSGU] FOREIGN KEY ([LINK_EKR]) REFERENCES [dbo].[KOSGU] ([LINK])
GO




GO
-- добавление поля  [LINK_EKR] в таблицу [SDOC_VEDOM_DGH_TABLE1] 
IF COLUMNPROPERTY(object_id('[dbo].[SDOC_VEDOM_DGH_TABLE1]'), 'LINK_EKR', 'AllowsNull') IS null
	ALTER TABLE [dbo].[SDOC_VEDOM_DGH_TABLE1] ADD [LINK_EKR] int NULL
GO


IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_SDOC_VEDOM_DGH_TABLE1_LINK_EKR')
CREATE INDEX [IX_SDOC_VEDOM_DGH_TABLE1_LINK_EKR] ON [dbo].[SDOC_VEDOM_DGH_TABLE1] ([LINK_EKR]) ON [INDEX]
GO



IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SDOC_VEDOM_DGH_TABLE1_KOSGU]'))
ALTER TABLE [dbo].[SDOC_VEDOM_DGH_TABLE1] 
ADD CONSTRAINT [FK_SDOC_VEDOM_DGH_TABLE1_KOSGU] FOREIGN KEY ([LINK_EKR]) REFERENCES [dbo].[KOSGU] ([LINK])
GO

----------
GO
-- BV_DOC_WAYBILL, Путевые листы --
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_WAYBILL', 'Путевые листы', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DOC_MAT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_WAYBILL', NAME = 'Путевые листы', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DOC_MAT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='BV_DOC_WAYBILL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_DEP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_DEP_NAME', 'Наименование организации', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_DEP_NAME', NAME = 'Наименование организации', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_DEP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_AUTO_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_AUTO_LINK', 'Ссылка на Автомобиль', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_AUTO_LINK', NAME = 'Ссылка на Автомобиль', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_AUTO_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_AUTO_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_AUTO_CODE', 'Код Автомобиля', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_AUTO_CODE', NAME = 'Код Автомобиля', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_AUTO_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_AUTO_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_AUTO_NAME', 'Наименование Автомобиля', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_AUTO_NAME', NAME = 'Наименование Автомобиля', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_AUTO_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_DRIVER_EMP_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_DRIVER_EMP_LINK', 'Ссылка на водителя', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_DRIVER_EMP_LINK', NAME = 'Ссылка на водителя', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_DRIVER_EMP_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_DRIVER_EMP_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_DRIVER_EMP_CODE', 'Код водителя', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_DRIVER_EMP_CODE', NAME = 'Код водителя', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_DRIVER_EMP_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_DRIVER_EMP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_DRIVER_EMP_NAME', 'Наименование водителя', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_DRIVER_EMP_NAME', NAME = 'Наименование водителя', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_DRIVER_EMP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_MISSION')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_MISSION', 'Задание водителю', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_MISSION', NAME = 'Задание водителю', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_MISSION'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_ADDRESS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_ADDRESS', 'Адрес подачи', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_ADDRESS', NAME = 'Адрес подачи', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_ADDRESS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TIME_OUT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_TIME_OUT', 'Время выезда', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_TIME_OUT', NAME = 'Время выезда', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_TIME_OUT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TIME_IN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_TIME_IN', 'Время заезда', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_TIME_IN', NAME = 'Время заезда', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_TIME_IN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_COMMENT_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_COMMENT_1', 'Примечание', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_COMMENT_1', NAME = 'Примечание', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_COMMENT_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_NOTE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_NOTE', 'Прочие отметки', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_NOTE', NAME = 'Прочие отметки', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_NOTE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_DISP_EMP_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_DISP_EMP_LINK', 'Ссылка на диспетчера', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_DISP_EMP_LINK', NAME = 'Ссылка на диспетчера', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_DISP_EMP_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_DISP_EMP_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_DISP_EMP_CODE', 'Код диспетчера', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_DISP_EMP_CODE', NAME = 'Код диспетчера', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_DISP_EMP_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_DISP_EMP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_DISP_EMP_NAME', 'Наименование диспетчера', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_DISP_EMP_NAME', NAME = 'Наименование диспетчера', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_DISP_EMP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_DISPLAY_B')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_DISPLAY_B', 'Показания спидометра (выезд)', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_DISPLAY_B', NAME = 'Показания спидометра (выезд)', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_DISPLAY_B'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_DISPLAY_A')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_DISPLAY_A', 'Показания спидометра (заезд)', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_DISPLAY_A', NAME = 'Показания спидометра (заезд)', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_DISPLAY_A'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_RACE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_RACE', 'Пробег', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_RACE', NAME = 'Пробег', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_RACE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_MECH_EMP_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_MECH_EMP_LINK', 'Ссылка на механика', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_MECH_EMP_LINK', NAME = 'Ссылка на механика', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_MECH_EMP_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_MECH_EMP_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_MECH_EMP_CODE', 'Код механика', 21, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_MECH_EMP_CODE', NAME = 'Код механика', ORDERS = '21', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_MECH_EMP_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_MECH_EMP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_MECH_EMP_NAME', 'Наименование механика', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_MECH_EMP_NAME', NAME = 'Наименование механика', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_MECH_EMP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_FUEL_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_FUEL_LINK', 'Ссылка на горючее', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_FUEL_LINK', NAME = 'Ссылка на горючее', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_FUEL_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_FUEL_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_FUEL_CODE', 'Код горючего', 24, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_FUEL_CODE', NAME = 'Код горючего', ORDERS = '24', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_FUEL_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_FUEL_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_FUEL_NAME', 'Наименование горючего', 25, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_FUEL_NAME', NAME = 'Наименование горючего', ORDERS = '25', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_FUEL_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_REFUELING')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_REFUELING', 'Заправлено', 26, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_REFUELING', NAME = 'Заправлено', ORDERS = '26', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_REFUELING'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_FUEL_OUT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_FUEL_OUT', 'Остаток при выезде', 27, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_FUEL_OUT', NAME = 'Остаток при выезде', ORDERS = '27', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_FUEL_OUT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_FUEL_IN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_FUEL_IN', 'Остаток при возвращении', 28, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_FUEL_IN', NAME = 'Остаток при возвращении', ORDERS = '28', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_FUEL_IN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_FUEL_NORM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_FUEL_NORM', 'Расход по норме', 29, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_FUEL_NORM', NAME = 'Расход по норме', ORDERS = '29', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_FUEL_NORM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_FUEL_FACT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_FUEL_FACT', 'Расход фактический', 30, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_FUEL_FACT', NAME = 'Расход фактический', ORDERS = '30', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_FUEL_FACT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_ECONOMY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_ECONOMY', 'Экономия', 31, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_ECONOMY', NAME = 'Экономия', ORDERS = '31', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_ECONOMY'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OVERDRAFT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_OVERDRAFT', 'Перерасход', 32, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_OVERDRAFT', NAME = 'Перерасход', ORDERS = '32', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_OVERDRAFT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_COEFF')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_TABLE_COEFF', 'Таблица с коэффициентами', 33, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_TABLE_COEFF', NAME = 'Таблица с коэффициентами', ORDERS = '33', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_TABLE_COEFF'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_TABLE_REFUEL', 'Таблица заправок', 34, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_TABLE_REFUEL', NAME = 'Таблица заправок', ORDERS = '34', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_TABLE_REFUEL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_WAYBILL_OPTIONS', 'Настройки Путевых листов', 35, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_WAYBILL_OPTIONS', NAME = 'Настройки Путевых листов', ORDERS = '35', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_WAYBILL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_WAYBILL_OPTIONS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WB_COEFF_TABLE_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WB_COEFF_TABLE_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_COEFF'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WB_COEFF_TABLE_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_COEFF'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WB_COEFF_TABLE_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WB_COEFF_TABLE_RATE_APP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WB_COEFF_TABLE_RATE_APP', 'Норма расхода', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_COEFF'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WB_COEFF_TABLE_RATE_APP', NAME = 'Норма расхода', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_COEFF'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WB_COEFF_TABLE_RATE_APP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WB_COEFF_TABLE_COEFF')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WB_COEFF_TABLE_COEFF', 'Коэффициент', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_COEFF'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WB_COEFF_TABLE_COEFF', NAME = 'Коэффициент', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_COEFF'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WB_COEFF_TABLE_COEFF'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WB_COEFF_TABLE_RACE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WB_COEFF_TABLE_RACE', 'Расстояние', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_COEFF'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WB_COEFF_TABLE_RACE', NAME = 'Расстояние', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_COEFF'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WB_COEFF_TABLE_RACE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WB_COEFF_TABLE_QTY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WB_COEFF_TABLE_QTY', 'Расход, л', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_COEFF'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WB_COEFF_TABLE_QTY', NAME = 'Расход, л', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_COEFF'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WB_COEFF_TABLE_QTY'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_TYP_LINK_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_TYP_LINK_1', 'Ссылка на операцию', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_TYP_LINK_1', NAME = 'Ссылка на операцию', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_TYP_LINK_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_TYP_NAME_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_TYP_NAME_1', 'Наим тип. опер.', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_TYP_NAME_1', NAME = 'Наим тип. опер.', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_TYP_NAME_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_TYP_LINK_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_TYP_LINK_2', 'Ссылка на операцию', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_TYP_LINK_2', NAME = 'Ссылка на операцию', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_TYP_LINK_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_TYP_NAME_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_TYP_NAME_2', 'Наим тип. опер.', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_TYP_NAME_2', NAME = 'Наим тип. опер.', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_TYP_NAME_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_TYP_LINK_21')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_TYP_LINK_21', 'Ссылка на операцию', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_TYP_LINK_21', NAME = 'Ссылка на операцию', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_TYP_LINK_21'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_TYP_NAME_21')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_TYP_NAME_21', 'Наим тип. опер.', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_TYP_NAME_21', NAME = 'Наим тип. опер.', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_TYP_NAME_21'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_LINK_VKR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_LINK_VKR', 'Ссылка на код ВКР', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_LINK_VKR', NAME = 'Ссылка на код ВКР', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_LINK_VKR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_CODE_VKR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_CODE_VKR', 'Код ВКР', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_CODE_VKR', NAME = 'Код ВКР', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_CODE_VKR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_NAME_VKR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_NAME_VKR', 'Наименование статьи ВКР', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_NAME_VKR', NAME = 'Наименование статьи ВКР', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_NAME_VKR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_LINK_EKR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_LINK_EKR', 'Ссылка на код ЭКР', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_LINK_EKR', NAME = 'Ссылка на код ЭКР', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_LINK_EKR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_CODE_EKR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_CODE_EKR', 'Код ЭКР', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_CODE_EKR', NAME = 'Код ЭКР', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_CODE_EKR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_NAME_EKR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_NAME_EKR', 'Наименование статьи ЭКР', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_NAME_EKR', NAME = 'Наименование статьи ЭКР', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_NAME_EKR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_LINK_SUB')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_LINK_SUB', 'Ссылка на код подразделения', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_LINK_SUB', NAME = 'Ссылка на код подразделения', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_LINK_SUB'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_CODE_SUB')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_CODE_SUB', 'Код подразделения', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_CODE_SUB', NAME = 'Код подразделения', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_CODE_SUB'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_NAME_SUB')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_NAME_SUB', 'Наименование подразделения', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_NAME_SUB', NAME = 'Наименование подразделения', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_NAME_SUB'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_LINK_ANL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_LINK_ANL', 'Ссылка на КАУ', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_LINK_ANL', NAME = 'Ссылка на КАУ', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_LINK_ANL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_CODE_ANL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_CODE_ANL', 'Код КАУ', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_CODE_ANL', NAME = 'Код КАУ', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_CODE_ANL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_NAME_ANL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_NAME_ANL', 'Наименование КАУ', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_NAME_ANL', NAME = 'Наименование КАУ', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_NAME_ANL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_LINK_MOL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_LINK_MOL', 'Ссылка на МОЛ', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_LINK_MOL', NAME = 'Ссылка на МОЛ', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_LINK_MOL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_CODE_MOL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_CODE_MOL', 'Код МОЛ', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_CODE_MOL', NAME = 'Код МОЛ', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_CODE_MOL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_NAME_MOL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_NAME_MOL', 'Наименование МОЛ', 21, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_NAME_MOL', NAME = 'Наименование МОЛ', ORDERS = '21', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_NAME_MOL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_LINK_DEP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_LINK_DEP', 'Ссылка на организацию', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_LINK_DEP', NAME = 'Ссылка на организацию', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_LINK_DEP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_CODE_DEP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_CODE_DEP', 'Код организации', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_CODE_DEP', NAME = 'Код организации', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_CODE_DEP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_NAME_DEP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_NAME_DEP', 'Наименование организации', 24, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_NAME_DEP', NAME = 'Наименование организации', ORDERS = '24', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_NAME_DEP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_NUM_TYPE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_NUM_TYPE', 'Нумерация документа', 25, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_NUM_TYPE', NAME = 'Нумерация документа', ORDERS = '25', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_NUM_TYPE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_NUM_FORMAT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_NUM_FORMAT', 'Формат печати', 26, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_NUM_FORMAT', NAME = 'Формат печати', ORDERS = '26', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_NUM_FORMAT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DWB_OPT_AUTODRIVER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DWB_OPT_AUTODRIVER', 'Водитель с предыдущего путевого листа', 27, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DWB_OPT_AUTODRIVER', NAME = 'Водитель с предыдущего путевого листа', ORDERS = '27', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DWB_OPT_AUTODRIVER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WB_TABLE_WR_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WB_TABLE_WR_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WB_TABLE_WR_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WB_TABLE_WR_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WB_REFUEL_TABLE_QTY_TYPE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WB_REFUEL_TABLE_QTY_TYPE', 'Тип ГСМ', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WB_REFUEL_TABLE_QTY_TYPE', NAME = 'Тип ГСМ', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WB_REFUEL_TABLE_QTY_TYPE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WB_TABLE_WR_LINK_INV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WB_TABLE_WR_LINK_INV', 'Ссылка на горючее', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WB_TABLE_WR_LINK_INV', NAME = 'Ссылка на горючее', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WB_TABLE_WR_LINK_INV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WB_TABLE_WR_CODE_INV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WB_TABLE_WR_CODE_INV', 'Код горючего', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WB_TABLE_WR_CODE_INV', NAME = 'Код горючего', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WB_TABLE_WR_CODE_INV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WB_TABLE_WR_NAME_INV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WB_TABLE_WR_NAME_INV', 'Наименование горючега', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WB_TABLE_WR_NAME_INV', NAME = 'Наименование горючега', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WB_TABLE_WR_NAME_INV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WB_TABLE_WR_LINK_SOU')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WB_TABLE_WR_LINK_SOU', 'Ссылка на источник финансирования', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WB_TABLE_WR_LINK_SOU', NAME = 'Ссылка на источник финансирования', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WB_TABLE_WR_LINK_SOU'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WB_TABLE_WR_CODE_SOU')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WB_TABLE_WR_CODE_SOU', 'Код источника финансирования', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WB_TABLE_WR_CODE_SOU', NAME = 'Код источника финансирования', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WB_TABLE_WR_CODE_SOU'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WB_TABLE_WR_NAME_SOU')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WB_TABLE_WR_NAME_SOU', 'Наименование источника финансирования', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WB_TABLE_WR_NAME_SOU', NAME = 'Наименование источника финансирования', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WB_TABLE_WR_NAME_SOU'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WB_REFUEL_TABLE_QTY_REST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WB_REFUEL_TABLE_QTY_REST', 'Входящий остаток', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WB_REFUEL_TABLE_QTY_REST', NAME = 'Входящий остаток', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WB_REFUEL_TABLE_QTY_REST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WB_TABLE_WR_PRICE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WB_TABLE_WR_PRICE', 'Цена', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WB_TABLE_WR_PRICE', NAME = 'Цена', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WB_TABLE_WR_PRICE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WB_REFUEL_TABLE_QTY_IN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WB_REFUEL_TABLE_QTY_IN', 'Заправлено', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WB_REFUEL_TABLE_QTY_IN', NAME = 'Заправлено', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WB_REFUEL_TABLE_QTY_IN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WB_REFUEL_TABLE_QTY_OUT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WB_REFUEL_TABLE_QTY_OUT', 'Списано', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WB_REFUEL_TABLE_QTY_OUT', NAME = 'Списано', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_WAYBILL_TABLE_REFUEL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WB_REFUEL_TABLE_QTY_OUT'
GO
EXEC X_SET_PROP 'BV_DOC_WAYBILL', 'TITLE', 'Путевые листы'
GO
EXEC X_SET_PROP 'BV_DOC_WAYBILL', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "BV_DOC_WAYBILL", "BV_DELETE_DOCUMENTS", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'BV_DOC_WAYBILL', 'SAVE_OBJECT_METHOD', 'bv_save_doc_waybill()'
GO
EXEC X_SET_PROP 'BV_DOC_WAYBILL', 'PRINT_OBJECT_METHOD', 'BK_print_travel_sheet_f3()'
GO
EXEC X_SET_PROP 'BV_DOC_WAYBILL', 'EDIT_OBJECT_METHOD', 'bdoc_brow(''BV_DOC_WAYBILL'')'
GO
EXEC X_SET_PROP 'BV_DOC_WAYBILL', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_LIST_ZB(''BV_DOC_WAYBILL'')'
GO
EXEC X_SET_PROP 'BV_DOC_WAYBILL', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST(''BV_DOC_WAYBILL'')'
GO
EXEC X_SET_PROP 'BV_DOC_WAYBILL', 'SNAME', 'Путевые листы'
GO
EXEC X_SET_PROP 'BV_DOC_WAYBILL', 'QUERY_REPMAKER', 'KirRepMakerMultiSheet.xls'
GO
EXEC X_SET_PROP 'BV_DOC_WAYBILL', 'QUERY_REPORT', 'TRAVEL_SHEET_F3.XLT#TRAVEL_SHEET_F3_A5.XLT'
GO
EXEC X_SET_PROP 'BV_DOC_WAYBILL', 'OPTIONS_OBJECT_CODE', 'DOC_WAYBILL_OPTIONS'
GO
EXEC X_SET_PROP 'BV_DOC_WAYBILL', 'HELP_TOPIC', '27'
GO
EXEC X_SET_PROP 'BV_DOC_WAYBILL', 'QUERY_ADD_MODULE', 'TRAVEL_F3.BAS'
GO
EXEC X_SET_PROP 'BV_DOC_WAYBILL', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'BV_DOC_WAYBILL', 'CREATE_PROV_SQL', 'BV_SAVE_G_PROV1_WAYBILL'
GO
EXEC X_SET_PROP 'BV_DOC_WAYBILL', 'REPORT_EXTERNAL_GENERATOR', '1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DEP_NAME', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DEP_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DEP_NAME', 'CONTROLSOURCE', 'm.cALIAS + ".DEP_NAME"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DEP_NAME', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DEP_NAME', 'SHORT_CODE_OBJ', 'DEP_NAME'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DEP_NAME', 'CONTROLSOURCE_EDIT', 'm.cALIAS + ".DEP_NAME"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_LINK', 'TITLE', 'Автомобиль'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_LINK', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_LINK', 'STORAGE', 'INVENTORY'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_LINK', 'REFERENCE_TO_DICT', 'INVENTORY_CARD'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_LINK', 'SHORT_CODE_OBJ', 'AUTO_LINK'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_CODE', 'TITLE', 'Автомобиль'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01("INVENTORY_CARD", oForm.ALIAS, "LINK,CODE,NAME", "AUTO_LINK, AUTO_CODE, AUTO_NAME", "", "", "dbo.BV_GetInvGrp(LINK) = ''10105'' OR dbo.BV_GetInvGrp(LINK) = ''10115'' OR dbo.BV_GetInvGrp(LINK) = ''10125'' OR dbo.BV_GetInvGrp(LINK) = ''10135'' OR dbo.BV_GetInvGrp(LINK) = ''10145'' OR dbo.BV_GetInvGrp(LINK) = ''10852'' OR dbo.BV_GetInvGrp(LINK) = ''10802''", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_CODE', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_CODE', 'CONTROLSOURCE', 'm.cAlias+".AUTO_CODE"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_CODE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_CODE', 'STORAGE', 'INVENTORY'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_CODE', 'REFERENCE_TO_DICT', 'DOC_WAYBILL_AUTO_LINK'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_CODE', 'TYPE_FIELD_DICT', 'CHAR(5)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_CODE', 'SHORT_CODE_OBJ', 'AUTO_CODE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".AUTO_CODE"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_CODE', 'CONTROL_NAME_EDIT', 'ASel_Spr1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_NAME', 'TITLE', 'Автомобиль'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_NAME', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_NAME', 'CONTROLSOURCE', 'm.cAlias+".AUTO_NAME"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_NAME', 'STORAGE', 'INVENTORY'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_NAME', 'REFERENCE_TO_DICT', 'DOC_WAYBILL_AUTO_LINK'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_NAME', 'SHORT_CODE_OBJ', 'AUTO_NAME'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".AUTO_NAME"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_NAME', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_AUTO_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_LINK', 'TITLE', 'Водитель'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_LINK', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_LINK', 'REFERENCE_TO_DICT', 'KU_EMPL_PLACING'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_LINK', 'SHORT_CODE_OBJ', 'EMP_LINK'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_CODE', 'TITLE', 'Водитель'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_CODE', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("KU_EMPL_PLACING", oForm.ALIAS,"LINK, TAB, NAME_EMPL", "EMP_LINK, EMP_CODE, EMP_NAME", "", "", "", .T., 1, oForm, oObj,"",.T.,"EMPL_GROUPS")'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_CODE', 'CONTROLSOURCE', 'm.cAlias+".EMP_CODE"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_CODE', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_CODE', 'REFERENCE_TO_DICT', 'DOC_WAYBILL_DRIVER_EMP_LINK'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_CODE', 'TYPE_FIELD_DICT', 'CHAR(5)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_CODE', 'SHORT_CODE_OBJ', 'EMP_CODE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".EMP_CODE"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_CODE', 'CONTROL_NAME_EDIT', 'ASel_Spr2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_NAME', 'TITLE', 'Водитель'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_NAME', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_NAME', 'CONTROLSOURCE', 'm.cAlias+".EMP_NAME"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_NAME', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_NAME', 'REFERENCE_TO_DICT', 'DOC_WAYBILL_DRIVER_EMP_LINK'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_NAME', 'SHORT_CODE_OBJ', 'EMP_NAME'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".EMP_NAME"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_NAME', 'CONTROL_NAME_EDIT', 'ATxtN2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DRIVER_EMP_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MISSION', 'TITLE', 'В распоряжение'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MISSION', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MISSION', 'CONTROLSOURCE', 'm.cAlias + ".MISSION"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MISSION', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MISSION', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MISSION', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MISSION', 'SHORT_CODE_OBJ', 'MISSION'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MISSION', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".MISSION"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MISSION', 'CONTROL_NAME_EDIT', 'ATxt3'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_ADDRESS', 'TITLE', 'Адрес подачи'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_ADDRESS', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_ADDRESS', 'CONTROLSOURCE', 'm.cAlias + ".ADDRESS"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_ADDRESS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_ADDRESS', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_ADDRESS', 'TYPE_FIELD_DICT', 'VARCHAR(120)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_ADDRESS', 'SHORT_CODE_OBJ', 'ADDRESS'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_ADDRESS', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ADDRESS"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_ADDRESS', 'CONTROL_NAME_EDIT', 'ATxt4'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_OUT', 'TITLE', 'Время выезда'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_OUT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_OUT', 'CONTROLSOURCE', 'm.cAlias + ".TIME_OUT"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_OUT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_OUT', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_OUT', 'TYPE_FIELD_DICT', 'TIME'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_OUT', 'SHORT_CODE_OBJ', 'TIME_OUT'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_OUT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TIME_OUT"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_OUT', 'CONTROL_NAME_EDIT', 'ATxt5'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_OUT', 'INPUT_MASK', '99.99'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_IN', 'TITLE', 'Время заезда'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_IN', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_IN', 'CONTROLSOURCE', 'm.cAlias + ".TIME_IN"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_IN', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_IN', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_IN', 'TYPE_FIELD_DICT', 'TIME'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_IN', 'SHORT_CODE_OBJ', 'TIME_IN'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_IN', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TIME_IN"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_IN', 'CONTROL_NAME_EDIT', 'ATxt6'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TIME_IN', 'INPUT_MASK', '99.99'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT_1', 'TITLE', 'Примечание'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT_1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT_1', 'CONTROLSOURCE', 'm.cAlias + ".COMMENT"'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT_1', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT_1', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT_1', 'TYPE_FIELD_DICT', 'VARCHAR(500)'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT_1', 'SHORT_CODE_OBJ', 'COMMENT'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COMMENT"'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT_1', 'CONTROL_NAME_EDIT', 'Aebox12'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_NOTE', 'TITLE', 'Прочие отметки'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_NOTE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_NOTE', 'CONTROLSOURCE', 'm.cAlias + ".NOTE"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_NOTE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_NOTE', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_NOTE', 'TYPE_FIELD_DICT', 'VARCHAR(120)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_NOTE', 'SHORT_CODE_OBJ', 'NOTE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_NOTE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NOTE"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_NOTE', 'CONTROL_NAME_EDIT', 'ATxt65'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_LINK', 'TITLE', 'Диспетчер-нарядчик'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_LINK', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_LINK', 'REFERENCE_TO_DICT', 'KU_EMPL_PLACING'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_LINK', 'SHORT_CODE_OBJ', 'EMP_LINK_D'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_CODE', 'TITLE', 'Диспетчер-нарядчик'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_CODE', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("KU_EMPL_PLACING", oForm.ALIAS,"LINK, TAB, NAME_EMPL", "EMP_LINK_D, EMP_CODE_D, EMP_NAME_D", "", "", "", .T., 1, oForm, oObj,"",.T.,"EMPL_GROUPS")'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_CODE', 'CONTROLSOURCE', 'm.cAlias+".EMP_CODE_D"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_CODE', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_CODE', 'REFERENCE_TO_DICT', 'DOC_WAYBILL_DISP_EMP_LINK'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_CODE', 'TYPE_FIELD_DICT', 'CHAR(5)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_CODE', 'SHORT_CODE_OBJ', 'EMP_CODE_D'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".EMP_CODE_D"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_CODE', 'CONTROL_NAME_EDIT', 'ASel_Spr7'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_NAME', 'TITLE', 'Диспетчер-нарядчик'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_NAME', 'CONTROLSOURCE', 'm.cAlias+".EMP_NAME_D"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_NAME', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_NAME', 'REFERENCE_TO_DICT', 'DOC_WAYBILL_DISP_EMP_LINK'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_NAME', 'SHORT_CODE_OBJ', 'EMP_NAME_D'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".EMP_NAME_D"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_NAME', 'CONTROL_NAME_EDIT', 'ATxtN7'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISP_EMP_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_B', 'TITLE', 'Показания спидометра (выезд)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_B', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_B', 'CONTROLSOURCE', 'm.cAlias + ".DISPLAY_B"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_B', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_B', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_B', 'TYPE_FIELD_DICT', 'NUMERIC(9,2)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_B', 'SHORT_CODE_OBJ', 'DISPLAY_B'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_B', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DISPLAY_B"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_B', 'CONTROL_NAME_EDIT', 'ATxt8'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_B', 'INPUT_MASK', '9999999.99'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_A', 'TITLE', 'Показания спидометра (заезд)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_A', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_A', 'CONTROLSOURCE', 'm.cAlias + ".DISPLAY_A"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_A', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_A', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_A', 'TYPE_FIELD_DICT', 'NUMERIC(9,2)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_A', 'SHORT_CODE_OBJ', 'DISPLAY_A'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_A', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DISPLAY_A"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_A', 'CONTROL_NAME_EDIT', 'ATxt9'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_DISPLAY_A', 'INPUT_MASK', '9999999.99'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_RACE', 'TITLE', 'Пробег'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_RACE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_RACE', 'CONTROLSOURCE', 'm.cAlias + ".RACE"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_RACE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_RACE', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_RACE', 'TYPE_FIELD_DICT', 'NUMERIC(8)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_RACE', 'SHORT_CODE_OBJ', 'RACE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_RACE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".RACE"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_RACE', 'CONTROL_NAME_EDIT', 'ATxt89'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_LINK', 'TITLE', 'Механик'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_LINK', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_LINK', 'REFERENCE_TO_DICT', 'KU_EMPL_PLACING'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_LINK', 'SHORT_CODE_OBJ', 'EMP_LINK_M'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_CODE', 'TITLE', 'Механик'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_CODE', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("KU_EMPL_PLACING", oForm.ALIAS,"LINK, TAB, NAME_EMPL","EMP_LINK_M, EMP_CODE_M, EMP_NAME_M", "", "", "", .T., 1, oForm, oObj,"",.T.,"EMPL_GROUPS")'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_CODE', 'CONTROLSOURCE', 'm.cAlias+".EMP_CODE_M"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_CODE', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_CODE', 'REFERENCE_TO_DICT', 'DOC_WAYBILL_MECH_EMP_LINK'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_CODE', 'TYPE_FIELD_DICT', 'CHAR(5)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_CODE', 'SHORT_CODE_OBJ', 'EMP_CODE_M'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".EMP_CODE_M"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_CODE', 'CONTROL_NAME_EDIT', 'ASel_Spr10'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_NAME', 'TITLE', 'Механик'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_NAME', 'CONTROLSOURCE', 'm.cAlias+".EMP_NAME_M"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_NAME', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_NAME', 'REFERENCE_TO_DICT', 'DOC_WAYBILL_MECH_EMP_LINK'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_NAME', 'SHORT_CODE_OBJ', 'EMP_NAME_M'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".EMP_NAME_M"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_NAME', 'CONTROL_NAME_EDIT', 'ATxtN10'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_MECH_EMP_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_LINK', 'TITLE', 'Горючее'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_LINK', 'STORAGE', 'NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_LINK', 'REFERENCE_TO_DICT', 'BV_NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_LINK', 'SHORT_CODE_OBJ', 'FUEL_LINK'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_CODE', 'TITLE', 'Горючее'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("BV_NOMENCLATURE", oForm.ALIAS, "LINK,CODE,NAME", "FUEL_LINK, FUEL_CODE, FUEL_NAME", "", "", "dbo.BV_GetNomenGrp(LINK) LIKE ''105_3%''", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_CODE', 'CONTROLSOURCE', 'm.cAlias+".FUEL_CODE"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_CODE', 'STORAGE', 'NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_CODE', 'REFERENCE_TO_DICT', 'DOC_WAYBILL_FUEL_LINK'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_CODE', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_CODE', 'SHORT_CODE_OBJ', 'FUEL_CODE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".FUEL_CODE"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_CODE', 'CONTROL_NAME_EDIT', 'ASel_Spr11'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_NAME', 'TITLE', 'Горючее'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_NAME', 'CONTROLSOURCE', 'm.cAlias+".FUEL_NAME"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_NAME', 'STORAGE', 'NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_NAME', 'REFERENCE_TO_DICT', 'DOC_WAYBILL_FUEL_LINK'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_NAME', 'SHORT_CODE_OBJ', 'FUEL_NAME'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".FUEL_NAME"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_NAME', 'CONTROL_NAME_EDIT', 'ATxtN11'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_REFUELING', 'TITLE', 'Заправлено, л'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_REFUELING', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_REFUELING', 'CONTROLSOURCE', 'm.cAlias + ".REFUELING"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_REFUELING', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_REFUELING', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_REFUELING', 'TYPE_FIELD_DICT', 'NUMERIC(7,3)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_REFUELING', 'SHORT_CODE_OBJ', 'REFUELING'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_REFUELING', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".REFUELING"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_REFUELING', 'CONTROL_NAME_EDIT', 'Parent.Page3.ATxt12'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_OUT', 'TITLE', 'Остаток при выезде, л'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_OUT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_OUT', 'CONTROLSOURCE', 'm.cAlias + ".FUEL_OUT"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_OUT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_OUT', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_OUT', 'TYPE_FIELD_DICT', 'NUMERIC(7,3)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_OUT', 'SHORT_CODE_OBJ', 'FUEL_OUT'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_OUT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FUEL_OUT"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_OUT', 'CONTROL_NAME_EDIT', 'Parent.Page3.ATxt13'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_IN', 'TITLE', 'Остаток при возвращении, л'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_IN', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_IN', 'CONTROLSOURCE', 'm.cAlias + ".FUEL_IN"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_IN', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_IN', 'TYPE_FIELD_DICT', 'NUMERIC(7,3)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_IN', 'SHORT_CODE_OBJ', 'FUEL_IN'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_IN', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FUEL_IN"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_IN', 'CONTROL_NAME_EDIT', 'Parent.Page3.ATxt14'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_NORM', 'TITLE', 'Расход по норме, л'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_NORM', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_NORM', 'CONTROLSOURCE', 'm.cAlias + ".FUEL_NORM"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_NORM', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_NORM', 'TYPE_FIELD_DICT', 'NUMERIC(7,3)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_NORM', 'SHORT_CODE_OBJ', 'FUEL_NORM'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_NORM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FUEL_NORM"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_NORM', 'CONTROL_NAME_EDIT', 'Parent.Page3.ATxt15'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_FACT', 'TITLE', 'Расход фактический, л'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_FACT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_FACT', 'CONTROLSOURCE', 'm.cAlias + ".FUEL_FACT"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_FACT', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_FACT', 'TYPE_FIELD_DICT', 'NUMERIC(7,3)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_FACT', 'SHORT_CODE_OBJ', 'FUEL_FACT'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_FACT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FUEL_FACT"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_FUEL_FACT', 'CONTROL_NAME_EDIT', 'Parent.Page3.ATxt16'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_ECONOMY', 'TITLE', 'Экономия, л'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_ECONOMY', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_ECONOMY', 'CONTROLSOURCE', 'm.cAlias + ".ECONOMY"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_ECONOMY', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_ECONOMY', 'TYPE_FIELD_DICT', 'NUMERIC(7,3)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_ECONOMY', 'SHORT_CODE_OBJ', 'ECONOMY'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_ECONOMY', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ECONOMY"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_ECONOMY', 'CONTROL_NAME_EDIT', 'Parent.Page3.ATxt17'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_OVERDRAFT', 'TITLE', 'Перерасход, л'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_OVERDRAFT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_OVERDRAFT', 'CONTROLSOURCE', 'm.cAlias + ".OVERDRAFT"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_OVERDRAFT', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_OVERDRAFT', 'TYPE_FIELD_DICT', 'NUMERIC(7,3)'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_OVERDRAFT', 'SHORT_CODE_OBJ', 'OVERDRAFT'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_OVERDRAFT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".OVERDRAFT"'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_OVERDRAFT', 'CONTROL_NAME_EDIT', 'Parent.Page3.ATxt18'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TABLE_COEFF', 'SAVE_OBJECT_METHOD', 'X_SAVE_WITH_ORDERS(''BV_SAVE_DOC_WAYBILL_COEFF'', m.cAlias, ''RATE_APP,COR_COEFF,RACE,ORDERS'',"DOC_WAYBILL_TABLE_COEFF")'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TABLE_COEFF', 'CLOSE_CODE', 'LINK_WAYBILL'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TABLE_COEFF', 'SELECT_RECORDS_METHOD', 'L_SQLEXEC(m.Handle,"SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, * FROM DOC_WAYBILL_TABLE_COEFF WHERE LINK_WAYBILL = "+STR(m.nLINK)+" ORDER BY ORDERS", m.cAlias)
'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TABLE_COEFF', 'SERVER_TABLE_NAME', 'WAYBILL_COEFF'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TABLE_REFUEL', 'SAVE_OBJECT_METHOD', 'X_SAVE_WITH_ORDERS(''BV_SAVE_DOC_WAYBILL_REFUEL'', m.cAlias,''TYPE,SQLNULL(INV_LINK),SQLNULL(SOU_LINK), PRICE,QUANTITY_REST,QUANTITY_IN,QUANTITY_OUT,ORDERS'',"DOC_WAYBILL_TABLE_REFUEL")'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TABLE_REFUEL', 'CLOSE_CODE', 'LINK_WAYBILL'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TABLE_REFUEL', 'SELECT_RECORDS_METHOD', 'L_SQLEXEC(m.Handle,"SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, * FROM DOC_WAYBILL_TABLE_REFUEL WHERE LINK_WAYBILL = "+STR(m.nLINK)+" ORDER BY ORDERS", m.cAlias)
'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_TABLE_REFUEL', 'SERVER_TABLE_NAME', 'WAYBILL_REFUEL'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_OPTIONS', 'TITLE', 'Настройки Путевых листов'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_OPTIONS', 'SAVE_OBJECT_METHOD', 'X_SAVE_DOCUMENT_OPTIONS()'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_OPTIONS', 'EDIT_OBJECT_METHOD', 'bdoc_brow(''bv_doc_waybill_options'')'
GO
EXEC X_SET_PROP 'DOC_WAYBILL_OPTIONS', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_OPTIONS(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_MARKER', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_MARKER', 'CONTROLSOURCE', 'm.cAlias+''.CHECKED'''
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_MARKER', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_RATE_APP', 'TITLE', 'Норма расхода, л/100км'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_RATE_APP', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_RATE_APP', 'CONTROLSOURCE', 'm.cAlias+''.RATE_APP'''
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_RATE_APP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_RATE_APP', 'TYPE_FIELD_DICT', 'NUMERIC(4,1)'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_RATE_APP', 'SHORT_CODE_OBJ', 'RATE_APP'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_COEFF', 'TITLE', 'Доп. коэффициент (%)'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_COEFF', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_COEFF', 'CONTROLSOURCE', 'm.cAlias+''.COR_COEFF'''
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_COEFF', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_COEFF', 'TYPE_FIELD_DICT', 'NUMERIC(4,1)'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_COEFF', 'SHORT_CODE_OBJ', 'COR_COEFF'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_RACE', 'TITLE', 'Расстояние, км'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_RACE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_RACE', 'CONTROLSOURCE', 'm.cAlias+''.RACE'''
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_RACE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_RACE', 'TYPE_FIELD_DICT', 'NUMERIC(6,1)'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_RACE', 'SHORT_CODE_OBJ', 'RACE'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_QTY', 'TITLE', 'Расход, л'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_QTY', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_QTY', 'CONTROLSOURCE', 'm.cAlias+''.QTY'''
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_QTY', 'TYPE_FIELD_DICT', 'NUMERIC(6,2)'
GO
EXEC X_SET_PROP 'WB_COEFF_TABLE_QTY', 'SHORT_CODE_OBJ', 'QTY'
GO
EXEC X_SET_PROP 'DWB_TYP_LINK_1', 'TITLE', 'Ссылка на операцию'
GO
EXEC X_SET_PROP 'DWB_TYP_LINK_1', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DWB_TYP_LINK_1', 'SHORT_CODE_OBJ', 'TYP_LINK_1'
GO
EXEC X_SET_PROP 'DWB_TYP_LINK_1', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_1', 'TITLE', 'Типовая операция на заправку'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_1', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "TYP_LINK_1", "TYP_NAME_1", "DOC_WAYBILL")'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_1', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_1', 'REFERENCE_TO_DICT', 'DWB_TYP_LINK_1'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_1', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_1', 'SHORT_CODE_OBJ', 'TYP_NAME_1'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TYP_NAME_1"'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_1', 'CONTROL_NAME_EDIT', 'Asel_spr1'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_1', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'DWB_TYP_LINK_2', 'TITLE', 'Ссылка на операцию'
GO
EXEC X_SET_PROP 'DWB_TYP_LINK_2', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DWB_TYP_LINK_2', 'SHORT_CODE_OBJ', 'TYP_LINK_2'
GO
EXEC X_SET_PROP 'DWB_TYP_LINK_2', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_2', 'TITLE', 'Типовая операция на списание'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_2', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "TYP_LINK_2", "TYP_NAME_2", "DOC_WAYBILL")'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_2', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_2', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_2', 'REFERENCE_TO_DICT', 'DWB_TYP_LINK_2'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_2', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_2', 'SHORT_CODE_OBJ', 'TYP_NAME_2'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TYP_NAME_2"'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_2', 'CONTROL_NAME_EDIT', 'Asel_spr2'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_2', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'DWB_TYP_LINK_21', 'TITLE', 'Ссылка на операцию'
GO
EXEC X_SET_PROP 'DWB_TYP_LINK_21', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DWB_TYP_LINK_21', 'SHORT_CODE_OBJ', 'TYP_LINK_3'
GO
EXEC X_SET_PROP 'DWB_TYP_LINK_21', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_21', 'TITLE', 'Типовая операция на списание (внебюдж.)'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_21', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "TYP_LINK_3", "TYP_NAME_3", "DOC_WAYBILL")'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_21', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_21', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_21', 'REFERENCE_TO_DICT', 'DWB_TYP_LINK_21'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_21', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_21', 'SHORT_CODE_OBJ', 'TYP_NAME_3'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_21', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TYP_NAME_3"'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_21', 'CONTROL_NAME_EDIT', 'Asel_spr9'
GO
EXEC X_SET_PROP 'DWB_TYP_NAME_21', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'DWB_LINK_VKR', 'TITLE', 'ВКР'
GO
EXEC X_SET_PROP 'DWB_LINK_VKR', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DWB_LINK_VKR', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DWB_LINK_VKR', 'REFERENCE_TO_DICT', 'DICTIONARY_FKR'
GO
EXEC X_SET_PROP 'DWB_LINK_VKR', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DWB_LINK_VKR', 'SHORT_CODE_OBJ', 'LINK_VKR'
GO
EXEC X_SET_PROP 'DWB_LINK_VKR', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DWB_CODE_VKR', 'TITLE', 'ВКР'
GO
EXEC X_SET_PROP 'DWB_CODE_VKR', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_FKR",oForm.ALIAS,"LINK, CODE, NAME", "LINK_VKR, CODE_VKR, NAME_VKR", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DWB_CODE_VKR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DWB_CODE_VKR', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DWB_CODE_VKR', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DWB_CODE_VKR', 'REFERENCE_TO_DICT', 'DWB_LINK_VKR'
GO
EXEC X_SET_PROP 'DWB_CODE_VKR', 'TYPE_FIELD_DICT', 'CHAR(5)'
GO
EXEC X_SET_PROP 'DWB_CODE_VKR', 'SHORT_CODE_OBJ', 'CODE_VKR'
GO
EXEC X_SET_PROP 'DWB_CODE_VKR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_VKR"'
GO
EXEC X_SET_PROP 'DWB_CODE_VKR', 'CONTROL_NAME_EDIT', 'ASel_spr3'
GO
EXEC X_SET_PROP 'DWB_CODE_VKR', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DWB_NAME_VKR', 'TITLE', 'ВКР'
GO
EXEC X_SET_PROP 'DWB_NAME_VKR', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DWB_NAME_VKR', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DWB_NAME_VKR', 'REFERENCE_TO_DICT', 'DWB_LINK_VKR'
GO
EXEC X_SET_PROP 'DWB_NAME_VKR', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'DWB_NAME_VKR', 'SHORT_CODE_OBJ', 'NAME_VKR'
GO
EXEC X_SET_PROP 'DWB_NAME_VKR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_VKR"'
GO
EXEC X_SET_PROP 'DWB_NAME_VKR', 'CONTROL_NAME_EDIT', 'ATxtN3'
GO
EXEC X_SET_PROP 'DWB_NAME_VKR', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DWB_LINK_EKR', 'TITLE', 'ВКР'
GO
EXEC X_SET_PROP 'DWB_LINK_EKR', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'DWB_LINK_EKR', 'REFERENCE_TO_DICT', 'DICTIONARY_ITEM'
GO
EXEC X_SET_PROP 'DWB_LINK_EKR', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DWB_LINK_EKR', 'SHORT_CODE_OBJ', 'LINK_EKR'
GO
EXEC X_SET_PROP 'DWB_LINK_EKR', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DWB_CODE_EKR', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'DWB_CODE_EKR', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_ITEM",oForm.ALIAS,"LINK, CODE, NAME", "LINK_EKR, CODE_EKR, NAME_EKR", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DWB_CODE_EKR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DWB_CODE_EKR', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'DWB_CODE_EKR', 'REFERENCE_TO_DICT', 'DWB_LINK_EKR'
GO
EXEC X_SET_PROP 'DWB_CODE_EKR', 'TYPE_FIELD_DICT', 'CHAR(3)'
GO
EXEC X_SET_PROP 'DWB_CODE_EKR', 'SHORT_CODE_OBJ', 'CODE_EKR'
GO
EXEC X_SET_PROP 'DWB_CODE_EKR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_EKR"'
GO
EXEC X_SET_PROP 'DWB_CODE_EKR', 'CONTROL_NAME_EDIT', 'ASel_spr4'
GO
EXEC X_SET_PROP 'DWB_CODE_EKR', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DWB_NAME_EKR', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'DWB_NAME_EKR', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'DWB_NAME_EKR', 'REFERENCE_TO_DICT', 'DWB_LINK_EKR'
GO
EXEC X_SET_PROP 'DWB_NAME_EKR', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'DWB_NAME_EKR', 'SHORT_CODE_OBJ', 'NAME_EKR'
GO
EXEC X_SET_PROP 'DWB_NAME_EKR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_EKR"'
GO
EXEC X_SET_PROP 'DWB_NAME_EKR', 'CONTROL_NAME_EDIT', 'ATxtN4'
GO
EXEC X_SET_PROP 'DWB_NAME_EKR', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DWB_LINK_SUB', 'TITLE', 'Подразделение'
GO
EXEC X_SET_PROP 'DWB_LINK_SUB', 'STORAGE', 'SUBDIV_HEAD'
GO
EXEC X_SET_PROP 'DWB_LINK_SUB', 'REFERENCE_TO_DICT', 'DICTIONARY_SUBDIVISION'
GO
EXEC X_SET_PROP 'DWB_LINK_SUB', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DWB_LINK_SUB', 'SHORT_CODE_OBJ', 'LINK_SUB'
GO
EXEC X_SET_PROP 'DWB_LINK_SUB', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DWB_CODE_SUB', 'TITLE', 'Структурное подразделение'
GO
EXEC X_SET_PROP 'DWB_CODE_SUB', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_SUBDIVISION",oForm.ALIAS,"link, CODE, NAME", "LINK_SUB, CODE_SUB, NAME_SUB", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DWB_CODE_SUB', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DWB_CODE_SUB', 'STORAGE', 'SUBDIV_HEAD'
GO
EXEC X_SET_PROP 'DWB_CODE_SUB', 'REFERENCE_TO_DICT', 'DWB_LINK_SUB'
GO
EXEC X_SET_PROP 'DWB_CODE_SUB', 'TYPE_FIELD_DICT', 'VARCHAR(5)'
GO
EXEC X_SET_PROP 'DWB_CODE_SUB', 'SHORT_CODE_OBJ', 'CODE_SUB'
GO
EXEC X_SET_PROP 'DWB_CODE_SUB', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_SUB"'
GO
EXEC X_SET_PROP 'DWB_CODE_SUB', 'CONTROL_NAME_EDIT', 'ASel_spr5'
GO
EXEC X_SET_PROP 'DWB_CODE_SUB', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DWB_NAME_SUB', 'TITLE', 'Подразделение'
GO
EXEC X_SET_PROP 'DWB_NAME_SUB', 'STORAGE', 'SUBDIV_HEAD'
GO
EXEC X_SET_PROP 'DWB_NAME_SUB', 'REFERENCE_TO_DICT', 'DWB_LINK_SUB'
GO
EXEC X_SET_PROP 'DWB_NAME_SUB', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'DWB_NAME_SUB', 'SHORT_CODE_OBJ', 'NAME_SUB'
GO
EXEC X_SET_PROP 'DWB_NAME_SUB', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_SUB"'
GO
EXEC X_SET_PROP 'DWB_NAME_SUB', 'CONTROL_NAME_EDIT', 'ATxtN5'
GO
EXEC X_SET_PROP 'DWB_NAME_SUB', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DWB_LINK_ANL', 'TITLE', 'КАУ'
GO
EXEC X_SET_PROP 'DWB_LINK_ANL', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DWB_LINK_ANL', 'REFERENCE_TO_DICT', 'DICTIONARY_ANALYTICAL_CODES'
GO
EXEC X_SET_PROP 'DWB_LINK_ANL', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DWB_LINK_ANL', 'SHORT_CODE_OBJ', 'LINK_ANL'
GO
EXEC X_SET_PROP 'DWB_LINK_ANL', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DWB_CODE_ANL', 'TITLE', 'КАУ'
GO
EXEC X_SET_PROP 'DWB_CODE_ANL', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_ANALYTICAL_CODES",oForm.ALIAS,"LINK, CODE, NAME", "LINK_ANL, CODE_ANL, NAME_ANL", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DWB_CODE_ANL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DWB_CODE_ANL', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DWB_CODE_ANL', 'REFERENCE_TO_DICT', 'DWB_LINK_ANL'
GO
EXEC X_SET_PROP 'DWB_CODE_ANL', 'TYPE_FIELD_DICT', 'CHAR(6)'
GO
EXEC X_SET_PROP 'DWB_CODE_ANL', 'SHORT_CODE_OBJ', 'CODE_ANL'
GO
EXEC X_SET_PROP 'DWB_CODE_ANL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_ANL"'
GO
EXEC X_SET_PROP 'DWB_CODE_ANL', 'CONTROL_NAME_EDIT', 'ASel_spr6'
GO
EXEC X_SET_PROP 'DWB_CODE_ANL', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DWB_NAME_ANL', 'TITLE', 'КАУ'
GO
EXEC X_SET_PROP 'DWB_NAME_ANL', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DWB_NAME_ANL', 'REFERENCE_TO_DICT', 'DWB_LINK_ANL'
GO
EXEC X_SET_PROP 'DWB_NAME_ANL', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DWB_NAME_ANL', 'SHORT_CODE_OBJ', 'NAME_ANL'
GO
EXEC X_SET_PROP 'DWB_NAME_ANL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_ANL"'
GO
EXEC X_SET_PROP 'DWB_NAME_ANL', 'CONTROL_NAME_EDIT', 'ATxtN6'
GO
EXEC X_SET_PROP 'DWB_NAME_ANL', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DWB_LINK_MOL', 'TITLE', 'МОЛ'
GO
EXEC X_SET_PROP 'DWB_LINK_MOL', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DWB_LINK_MOL', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DWB_LINK_MOL', 'REFERENCE_TO_DICT', 'KU_EMPL_PLACING'
GO
EXEC X_SET_PROP 'DWB_LINK_MOL', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DWB_LINK_MOL', 'SHORT_CODE_OBJ', 'LINK_MOL'
GO
EXEC X_SET_PROP 'DWB_LINK_MOL', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DWB_CODE_MOL', 'TITLE', 'МОЛ (Кт160, Кт064)'
GO
EXEC X_SET_PROP 'DWB_CODE_MOL', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("KU_EMPL_PLACING", oForm.ALIAS,"LINK, TAB, NAME_EMPL", "LINK_MOL, CODE_MOL, NAME_MOL", "", "", "", .T., 1, oForm, oObj,"",.T.,"EMPL_GROUPS")'
GO
EXEC X_SET_PROP 'DWB_CODE_MOL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DWB_CODE_MOL', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DWB_CODE_MOL', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DWB_CODE_MOL', 'REFERENCE_TO_DICT', 'DWB_LINK_MOL'
GO
EXEC X_SET_PROP 'DWB_CODE_MOL', 'TYPE_FIELD_DICT', 'CHAR(6)'
GO
EXEC X_SET_PROP 'DWB_CODE_MOL', 'SHORT_CODE_OBJ', 'CODE_MOL'
GO
EXEC X_SET_PROP 'DWB_CODE_MOL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_MOL"'
GO
EXEC X_SET_PROP 'DWB_CODE_MOL', 'CONTROL_NAME_EDIT', 'ASel_spr7'
GO
EXEC X_SET_PROP 'DWB_CODE_MOL', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DWB_NAME_MOL', 'TITLE', 'МОЛ (Кт160, Кт064)'
GO
EXEC X_SET_PROP 'DWB_NAME_MOL', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DWB_NAME_MOL', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DWB_NAME_MOL', 'REFERENCE_TO_DICT', 'DWB_LINK_MOL'
GO
EXEC X_SET_PROP 'DWB_NAME_MOL', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DWB_NAME_MOL', 'SHORT_CODE_OBJ', 'NAME_MOL'
GO
EXEC X_SET_PROP 'DWB_NAME_MOL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_MOL"'
GO
EXEC X_SET_PROP 'DWB_NAME_MOL', 'CONTROL_NAME_EDIT', 'ATxtN7'
GO
EXEC X_SET_PROP 'DWB_NAME_MOL', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DWB_LINK_DEP', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'DWB_LINK_DEP', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DWB_LINK_DEP', 'REFERENCE_TO_DICT', 'DICTIONARY_DEPARTMENT'
GO
EXEC X_SET_PROP 'DWB_LINK_DEP', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DWB_LINK_DEP', 'SHORT_CODE_OBJ', 'LINK_DEP'
GO
EXEC X_SET_PROP 'DWB_LINK_DEP', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DWB_CODE_DEP', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'DWB_CODE_DEP', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_DEPARTMENT",oForm.ALIAS,"LINK, CODE, NAME", "LINK_DEP, CODE_DEP, NAME_DEP", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DWB_CODE_DEP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DWB_CODE_DEP', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DWB_CODE_DEP', 'REFERENCE_TO_DICT', 'DWB_LINK_DEP'
GO
EXEC X_SET_PROP 'DWB_CODE_DEP', 'TYPE_FIELD_DICT', 'CHAR(3)'
GO
EXEC X_SET_PROP 'DWB_CODE_DEP', 'SHORT_CODE_OBJ', 'CODE_DEP'
GO
EXEC X_SET_PROP 'DWB_CODE_DEP', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_DEP"'
GO
EXEC X_SET_PROP 'DWB_CODE_DEP', 'CONTROL_NAME_EDIT', 'ASel_spr7'
GO
EXEC X_SET_PROP 'DWB_CODE_DEP', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DWB_NAME_DEP', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'DWB_NAME_DEP', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DWB_NAME_DEP', 'REFERENCE_TO_DICT', 'DWB_LINK_DEP'
GO
EXEC X_SET_PROP 'DWB_NAME_DEP', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DWB_NAME_DEP', 'SHORT_CODE_OBJ', 'NAME_DEP'
GO
EXEC X_SET_PROP 'DWB_NAME_DEP', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_DEP"'
GO
EXEC X_SET_PROP 'DWB_NAME_DEP', 'CONTROL_NAME_EDIT', 'ATxtN7'
GO
EXEC X_SET_PROP 'DWB_NAME_DEP', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DWB_NUM_TYPE', 'TITLE', 'Нумерация документа'
GO
EXEC X_SET_PROP 'DWB_NUM_TYPE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DWB_NUM_TYPE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DWB_NUM_TYPE', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DWB_NUM_TYPE', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DWB_NUM_TYPE', 'SHORT_CODE_OBJ', 'NUM_TYPE'
GO
EXEC X_SET_PROP 'DWB_NUM_TYPE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NUM_TYPE"'
GO
EXEC X_SET_PROP 'DWB_NUM_TYPE', 'CONTROL_NAME_EDIT', 'RADIO10'
GO
EXEC X_SET_PROP 'DWB_NUM_FORMAT', 'TITLE', 'Формат печати'
GO
EXEC X_SET_PROP 'DWB_NUM_FORMAT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DWB_NUM_FORMAT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DWB_NUM_FORMAT', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DWB_NUM_FORMAT', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DWB_NUM_FORMAT', 'SHORT_CODE_OBJ', 'FORMAT'
GO
EXEC X_SET_PROP 'DWB_NUM_FORMAT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FORMAT"'
GO
EXEC X_SET_PROP 'DWB_NUM_FORMAT', 'CONTROL_NAME_EDIT', 'RADIO11'
GO
EXEC X_SET_PROP 'DWB_OPT_AUTODRIVER', 'TITLE', 'При выборе автомобиля подставлять водителя с предыдущего путевого листа для этого автомобиля'
GO
EXEC X_SET_PROP 'DWB_OPT_AUTODRIVER', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DWB_OPT_AUTODRIVER', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DWB_OPT_AUTODRIVER', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DWB_OPT_AUTODRIVER', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DWB_OPT_AUTODRIVER', 'SHORT_CODE_OBJ', 'AUTODRIVER'
GO
EXEC X_SET_PROP 'DWB_OPT_AUTODRIVER', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".AUTODRIVER"'
GO
EXEC X_SET_PROP 'DWB_OPT_AUTODRIVER', 'CONTROL_NAME_EDIT', 'chk_Driver'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_MARKER', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_MARKER', 'CONTROLSOURCE', 'm.cAlias+''.CHECKED'''
GO
EXEC X_SET_PROP 'WB_TABLE_WR_MARKER', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_TYPE', 'TITLE', 'Тип ГСМ'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_TYPE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_TYPE', 'CONTROLSOURCE', 'm.cAlias+''.TYPE'''
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_TYPE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_TYPE', 'TYPE_FIELD_DICT', 'CHAR(10)'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_TYPE', 'SHORT_CODE_OBJ', 'TYPE'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_LINK_INV', 'TITLE', 'Горючее'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_LINK_INV', 'STORAGE', 'NOMENCLATURE'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_LINK_INV', 'REFERENCE_TO_DICT', 'BV_NOMENCLATURE'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_LINK_INV', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_LINK_INV', 'SHORT_CODE_OBJ', 'INV_LINK'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_LINK_INV', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_INV', 'TITLE', 'Код ГСМ'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_INV', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("BV_NOMENCLATURE", oForm.Pages.Page3.Bchildspisok2.Bgrid1.RecordSource, "LINK,CODE,NAME", "INV_LINK, INV_CODE, INV_NAME", "", "", "dbo.BV_GetNomenGrp(LINK) LIKE ''105_3%''", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_INV', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_INV', 'CONTROLSOURCE', 'm.cAlias+".INV_CODE"'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_INV', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_INV', 'STORAGE', 'NOMENCLATURE'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_INV', 'REFERENCE_TO_DICT', 'WB_TABLE_WR_LINK_INV'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_INV', 'TYPE_FIELD_DICT', 'CHAR(20)'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_INV', 'SHORT_CODE_OBJ', 'INV_CODE'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_INV', 'CONTROLSOURCE_EDIT', 'm.cAlias+".INV_CODE"'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_INV', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_NAME_INV', 'TITLE', 'Наименование ГСМ'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_NAME_INV', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_NAME_INV', 'CONTROLSOURCE', 'm.cAlias+".INV_NAME"'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_NAME_INV', 'STORAGE', 'NOMENCLATURE'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_NAME_INV', 'REFERENCE_TO_DICT', 'WB_TABLE_WR_LINK_INV'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_NAME_INV', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_NAME_INV', 'SHORT_CODE_OBJ', 'INV_NAME'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_NAME_INV', 'CONTROLSOURCE_EDIT', 'm.cAlias+".INV_NAME"'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_NAME_INV', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_LINK_SOU', 'TITLE', 'Источник финансирования'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_LINK_SOU', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_LINK_SOU', 'REFERENCE_TO_DICT', 'DICTIONARY_FINANCE_SOURCE'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_LINK_SOU', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_LINK_SOU', 'SHORT_CODE_OBJ', 'SOU_LINK'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_LINK_SOU', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_SOU', 'TITLE', 'Код ИФ'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_SOU', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_FIN_SOURCE", oForm.Pages.Page3.Bchildspisok2.Bgrid1.RecordSource, "LINK, CODE, NAME", "SOU_LINK, SOU_CODE, SOU_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_SOU', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_SOU', 'CONTROLSOURCE', 'm.cAlias+".SOU_CODE"'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_SOU', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_SOU', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_SOU', 'REFERENCE_TO_DICT', 'WB_TABLE_WR_LINK_SOU'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_SOU', 'TYPE_FIELD_DICT', 'CHAR(1)'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_SOU', 'SHORT_CODE_OBJ', 'SOU_CODE'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_SOU', 'CONTROLSOURCE_EDIT', 'm.cAlias+".SOU_CODE"'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_CODE_SOU', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_NAME_SOU', 'TITLE', 'ИФ'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_NAME_SOU', 'CONTROLSOURCE', 'm.cAlias+".SOU_NAME"'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_NAME_SOU', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_NAME_SOU', 'REFERENCE_TO_DICT', 'WB_TABLE_WR_LINK_SOU'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_NAME_SOU', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_NAME_SOU', 'SHORT_CODE_OBJ', 'SOU_NAME'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_NAME_SOU', 'CONTROLSOURCE_EDIT', 'm.cAlias+".SOU_NAME"'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_NAME_SOU', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_REST', 'TITLE', 'Остаток (вх.)'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_REST', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_REST', 'CONTROLSOURCE', 'm.cAlias+''.QUANTITY_REST'''
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_REST', 'TYPE_FIELD_DICT', 'NUMERIC(18,3)'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_REST', 'SHORT_CODE_OBJ', 'QUANTITY_REST'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_PRICE', 'TITLE', 'Цена'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_PRICE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_PRICE', 'CONTROLSOURCE', 'm.cAlias+".PRICE"'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_PRICE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_PRICE', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_PRICE', 'TYPE_FIELD_DICT', 'numeric(20,4)'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_PRICE', 'SHORT_CODE_OBJ', 'PRICE'
GO
EXEC X_SET_PROP 'WB_TABLE_WR_PRICE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PRICE"'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_IN', 'TITLE', 'Заправлено'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_IN', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_IN', 'CONTROLSOURCE', 'm.cAlias+''.QUANTITY_IN'''
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_IN', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_IN', 'TYPE_FIELD_DICT', 'NUMERIC(7,3)'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_IN', 'SHORT_CODE_OBJ', 'QUANTITY_IN'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_OUT', 'TITLE', 'Списано'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_OUT', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_OUT', 'CONTROLSOURCE', 'm.cAlias+''.QUANTITY_OUT'''
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_OUT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_OUT', 'TYPE_FIELD_DICT', 'NUMERIC(7,3)'
GO
EXEC X_SET_PROP 'WB_REFUEL_TABLE_QTY_OUT', 'SHORT_CODE_OBJ', 'QUANTITY_OUT'
GO




GO
EXECUTE dbo.X_FORM_VIEW_OPTIONS 'DOC_WAYBILL_OPTIONS'
GO


GO

--ОБЪЕКТЫ БД 03.07.2014
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SALARY_DGH_SALDO_MONTH_VKR]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[SALARY_DGH_SALDO_MONTH_VKR]

GO

CREATE  FUNCTION DBO.SALARY_DGH_SALDO_MONTH_VKR(@LINK int, @DATE1 datetime, @LINK_S_FIN INT, @LINK_EKR INT = null, @DEP_LINK INT)
RETURNS NUMERIC(18,2)
AS  
BEGIN

RETURN 
	ISNULL(
		(
			SELECT 
				SUM(CASE WHEN  P.[OBJECT] = 1 THEN J.SUMMA ELSE 0 END) - SUM(CASE WHEN P.[OBJECT] =  2 THEN J.SUMMA ELSE 0 END)
			FROM 
				dbo.PAYS P
				INNER JOIN dbo.CALCULATE_JURNAL J ON P.LINK = J.LINK_PAYS
			WHERE
				J.LINK_DEP = @DEP_LINK 
				AND J.LINK_EMPL IS NULL 
				AND J.PERS_LINK = @LINK 
				AND J.LINK_VKR = @LINK_S_FIN
				AND (J.LINK_EKR = @LINK_EKR OR  ISNULL(@LINK_EKR,0) = 0 ) 
				AND YEAR(J.PERIOD_BEGIN) = YEAR(@DATE1) 
				AND MONTH(J.PERIOD_BEGIN) < MONTH(@DATE1)	
			)
	,0)

END
                                                        

GO


GRANT EXECUTE ON dbo.[SALARY_DGH_SALDO_MONTH_VKR] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_PKG_LIST_POST]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[SA_PKG_LIST_POST]

GO

CREATE VIEW dbo.SA_PKG_LIST_POST
AS
SELECT 
	P.LINK,
	P.CODE,
	P.NAME,
	PD.LINK_PKG as LINK_UP,
	DATE_BEGIN = ISNULL(PD.DATE_BEGIN,'20000101'),
	DATE_END = ISNULL(((SELECT TOP 1 DATE_BEGIN FROM PKG_POST_date B WHERE B.link_POST  =pd.LINK_POST AND B.date_begin > pd.date_begin ORDER BY B.date_begin asc) - 1 ),'20991231')  
FROM dbo.POST P LEFT JOIN dbo.PKG_POST_DATE pd ON pd.link_POST = P.LINK
			    LEFT JOIN dbo.PKG_POST G on G.link = pd.link_PKG


GO


GRANT SELECT ON dbo.[SA_PKG_LIST_POST] TO PUBLIC

GO





GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[DICTIONARY_POST_LIST_PKG]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[DICTIONARY_POST_LIST_PKG]

GO

CREATE VIEW dbo.DICTIONARY_POST_LIST_PKG
AS
SELECT 
	P.LINK,
	P.CODE,
	P.NAME ,
	PD.LINK_PKG ,
	code_PKG = G.CODE,	
	name_PKG = G.name,
	DATE_BEGIN = ISNULL(PD.DATE_BEGIN,'20000101'),
	DATE_END = ISNULL(((SELECT TOP 1 DATE_BEGIN FROM PKG_POST_date B WHERE pd.LINK_POST = B.link_POST AND B.date_begin > pd.date_begin ORDER BY B.date_begin asc) - 1 ) ,'20991231')
FROM dbo.POST P INNER JOIN dbo.PKG_POST_DATE pd ON pd.link_POST = P.LINK
			    INNER JOIN dbo.PKG_POST G on G.link = pd.link_PKG



GO


GRANT SELECT ON dbo.[DICTIONARY_POST_LIST_PKG] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[PKG_LIST_POST]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[PKG_LIST_POST]

GO

CREATE VIEW dbo.PKG_LIST_POST
AS
SELECT 
	P.LINK,
	P.CODE,
	P.NAME/*,
	P.LINK_PKG as LINK_UP*/
FROM dbo.POST P

GO


GRANT SELECT ON dbo.[PKG_LIST_POST] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RN_VIEW_TYPE_KOR]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[RN_VIEW_TYPE_KOR]

GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2014

*******************************************************************************/

CREATE VIEW dbo.[RN_VIEW_TYPE_KOR]
AS

select 1 as link, '1' as code , 'Уточнение Расчета в части показателей, касающихся уплаты страховых взносов на обязательное пенсионное страхование (в том числе по дополнительным тарифам)' AS NAME
union
select 2 as link, '2' as code , 'Уточнение Расчета в части изменения сумм начисленных страховых взносов на обязательное пенсионное страхование (в том числе по дополнительным тарифам)' AS Name
union
select 3 as link, '3' as code , 'Уточнение Расчета в части страховых взносов на обязательное медицинское страхование или других показателей, не затрагивающих сведения индивидуального учета по застрахованным лицам' AS Name


GO


GRANT SELECT ON dbo.[RN_VIEW_TYPE_KOR] TO PUBLIC

GO



GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[sa_dict_pays_empl0]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[sa_dict_pays_empl0]

GO

CREATE   FUNCTION dbo.sa_dict_pays_empl0(@link_empl INT = -1, @link_sovm INT = -1, @BUFF_ID VARCHAR(20) = NULL) 

RETURNS TABLE

AS

RETURN

SELECT
		P.LINK,
		P.LINK_EMPL,
		LINK_SOVM = ISNULL(P.LINK_SOVM,0),
		P.LINK_PAYS,
		[DATE_BEG] = P.[DATE],
		D.[DATE_END],
		P.SUMMA,
		P.LINK_KBK,
		P.LINK_MP,
		P.NO_CALC
FROM
	dbo.PAYS_EMPL P WITH (NOLOCK)
	CROSS APPLY (SELECT MIN(P1.[DATE])-1 AS [DATE_END] FROM dbo.PAYS_EMPL P1 WHERE P1.LINK_EMPL = P.LINK_EMPL AND ISNULL(P1.link_sovm,0) = ISNULL(P.link_sovm,0) and P1.LINK_PAYS = P.LINK_PAYS AND P1.[DATE] > P.[DATE]) D
WHERE
	(
		(@LINK_EMPL = -1 
		AND 
		(	@BUFF_ID IS NULL
			OR 
			@BUFF_ID IS NOT NULL AND EXISTS (SELECT * FROM DBO.BUFFER B WITH (NOLOCK) WHERE B.ID = @BUFF_ID AND B.LINK = P.LINK_EMPL)
		))
		OR
		(@LINK_EMPL > 0 AND P.LINK_EMPL = @LINK_EMPL)
	)
	and
	(@link_sovm = -1 OR ISNULL(P.link_sovm,0) = @link_sovm)	

GO


GRANT SELECT ON dbo.[sa_dict_pays_empl0] TO PUBLIC

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BK_VIEW_EXPORT_FORMAT_NALOG_FN]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[BK_VIEW_EXPORT_FORMAT_NALOG_FN]

GO
CREATE FUNCTION dbo.BK_VIEW_EXPORT_FORMAT_NALOG_FN (@YEAR INT = NULL)
RETURNS TABLE

RETURN

	-- Форматы для налога на прибыль --
	SELECT FORM_CODE = 'ND_NP',
		FNAME = 'Формат 5.02 (с 01.01.2009 г.)', PROC_NAME = 'BK_EXPORT_F1151006', 
		PRG_SKRIPT = CONVERT(VARCHAR(100),''),
		DIR = 'IMNS',
		TEST_PROC = ''
	WHERE @YEAR < 2011

	UNION ALL

	SELECT FORM_CODE = 'ND_NP',
		FNAME = 'Формат 5.03 (с 01.01.2011 г.)', PROC_NAME = 'BK_EXPORT_F1151006_503', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = ''
	WHERE @YEAR BETWEEN 2011 AND 2013

	UNION ALL

	SELECT FORM_CODE = 'ND_NP',
		FNAME = 'Формат 5.05 (с 01.12.2013 г.)', PROC_NAME = 'BK_EXPORT_F1151006_505', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = ''
	WHERE @YEAR >= 2013

	UNION ALL
	-- Форматы для транспортного налога --
	SELECT
		FORM_CODE = 'ND_TN',
		FNAME = 'Формат 4.01 (с 01.01.2007 г.)',
		PROC_NAME = 'BK_EXPORT_F1152004', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = 'BK_TEST_EXP_F1152027'
	WHERE @YEAR < 2012	

	UNION ALL

	SELECT
		FORM_CODE = 'ND_TN',
		FNAME = 'Формат 5.01 (с 01.01.2012 г.)',
		PROC_NAME = 'BK_EXPORT_F1152004_501', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = ''
	WHERE @YEAR = 2012

	UNION ALL

	SELECT
		FORM_CODE = 'ND_TN',
		FNAME = 'Формат 5.02 (с 01.01.2013 г.)',
		PROC_NAME = 'BK_EXPORT_F1152004_502', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = ''
	WHERE @YEAR >= 2013

	UNION ALL

	SELECT FORM_CODE = 'AV_TN',
		FNAME = 'Формат 4.01 (с 01.01.2007 г.)', PROC_NAME = 'BK_EXPORT_F1152027', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = 'BK_TEST_EXP_F1152027'

	UNION ALL

	--- Форматы для налога на имущество ---
	SELECT FORM_CODE = 'AV_F1152028',
		FNAME = 'Формат 5.00 (с 01.01.2008 г.)',
		PROC_NAME = 'BK_EXPORT_F1152028', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = 'BK_TEST_EXP_F1152028'
	UNION ALL
	SELECT FORM_CODE = 'AV_ASS',
		FNAME = 'Формат 5.00 (с 01.01.2008 г.)',
		PROC_NAME = 'BK_EXPORT_F1152026', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = 'BK_TEST_EXP_F1152028'
	UNION ALL
	-- Форматы с 01.01.2012 --
	SELECT FORM_CODE = 'ND_IMU',
		FNAME = 'Формат 5.02 (с 01.01.2012 г.)',
		PROC_NAME = 'BK_EXPORT_F1152026_502', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = '' --'BK_TEST_EXP_F1152028'
	WHERE @YEAR < 2013
	UNION ALL
	SELECT FORM_CODE = 'AV_IMU',
		FNAME = 'Формат 5.02 (с 01.01.2012 г.)',
		PROC_NAME = 'BK_EXPORT_F1152028_502', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = '' --'BK_TEST_EXP_F1152028'
	WHERE @YEAR < 2014		
	UNION ALL
	-- Форматы с 01.01.2013 --
	SELECT FORM_CODE = 'ND_IMU',
		FNAME = 'Формат 5.03 (с 01.01.2013 г.)',
		PROC_NAME = 'BK_EXPORT_F1152026_503', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = '' --'BK_TEST_EXP_F1152028'
	UNION ALL
	SELECT FORM_CODE = 'AV_IMU',
		FNAME = 'Формат 5.03 (с 01.01.2014 г.)',
		PROC_NAME = 'BK_EXPORT_F1152028_503', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = '' --'BK_TEST_EXP_F1152028'
	WHERE @YEAR >= 2014		

	UNION ALL
	-- Форматы для 4ФСС --
	SELECT FORM_CODE = '4FSS',
		FNAME = 'формат, утвержденный приказом Минздравсоцразвития России от 06.11.2009 n 871н', PROC_NAME = 'SA_4FSS_EXPORT', 
		PRG_SKRIPT = '',
		DIR = 'PF',
		TEST_PROC = 'SA_4FSS_EXPORT_TEST'
	WHERE
		@YEAR <= 2010	
	UNION ALL	
	SELECT FORM_CODE = '4FSS',
		FNAME = 'Версия формата 0.3 (Приказ №19 от 12.02.2010 в ред. от 21.03.2011 (№53)', PROC_NAME = 'SA_4FSS_EXPORT_v03', 
		PRG_SKRIPT = '',
		DIR = 'PF',
		TEST_PROC = 'SA_4FSS_EXPORT_TEST'
	WHERE
		@YEAR = 2011
	UNION ALL
	SELECT FORM_CODE = '4FSS',
		FNAME = 'Версия формата 0.4 (Приказ № от 22.11.2011)', PROC_NAME = 'SA_4FSS_EXPORT_v04', 
		PRG_SKRIPT = '',
		DIR = 'PF',
		TEST_PROC = 'SA_4FSS_EXPORT_TEST'
	WHERE
		@YEAR = 2012
	UNION ALL
	SELECT FORM_CODE = '4FSS',
		FNAME = 'Версия формата 0.5 (Приказ №107н от 19.03.2013)', PROC_NAME = 'SA_4FSS_EXPORT_v05', 
		PRG_SKRIPT = '',
		DIR = 'PF',
		TEST_PROC = 'SA_4FSS_EXPORT_TEST'
	WHERE
		@YEAR = 2013	
	UNION ALL
	SELECT FORM_CODE = '4FSS',
		FNAME = 'Версия формата 0.6 (Приказ №107н от 19.03.2013 в ред. от 11.02.2014 № 94н)', PROC_NAME = 'SA_4FSS_EXPORT_v05', 
		PRG_SKRIPT = '',
		DIR = 'PF',
		TEST_PROC = 'SA_4FSS_EXPORT_TEST'
	WHERE
		@YEAR >= 2014	
	UNION ALL
	
	-- Формат выгрузки РСВ-1 --
	SELECT FORM_CODE = 'РСВ-1',
		FNAME = 'Формат 07.00 (2011)', PROC_NAME = 'SA_RSV1_EXPORT_0700_2011', 
		PRG_SKRIPT = '',
		DIR = 'PF',
		TEST_PROC = 'SA_RSV1_EXPORT_TEST'
	WHERE
		@YEAR = 2011	
	UNION ALL	
	
	-- Формат выгрузки РСВ-1 --
	SELECT FORM_CODE = 'РСВ-1',
		FNAME = 'Формат 07.00 (от 15.03.2012 г. №232н)', PROC_NAME = 'SA_RSV1_EXPORT_0700_2012', 
		PRG_SKRIPT = '',
		DIR = 'PF',
		TEST_PROC = 'SA_RSV1_EXPORT_TEST'
	WHERE
		@YEAR = 2012			
	UNION ALL	
	
	-- Формат выгрузки РСВ-1 --
	SELECT FORM_CODE = 'РСВ-1',
		FNAME = 'Формат 07.00 (от 15.03.2012 г. №232н)', PROC_NAME = 'SA_RSV1_EXPORT_0700_2013', 
		PRG_SKRIPT = '',
		DIR = 'PF',
		TEST_PROC = 'SA_RSV1_EXPORT_TEST'
	WHERE
		@YEAR = 2013
	UNION ALL	
	
	-- Формат выгрузки РСВ-1 --
	SELECT FORM_CODE = 'РСВ-1',
		FNAME = 'Формат 07.00 (от 03.03.2014 г. №25п)', PROC_NAME = 'SA_RSV1_EXPORT_0700_2014', 
		PRG_SKRIPT = '',
		DIR = 'PF',
		TEST_PROC = 'SA_RSV1_EXPORT_TEST'
	WHERE
		@YEAR >= 2014	
	UNION ALL
	-- Формат выгрузки П-2 (краткая) --
	SELECT FORM_CODE = '0617005',
		FNAME = 'Формат выгрузки формы П-2 (краткая) для Росстата', PROC_NAME = 'BK_EXPORT_F0617005', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''

	UNION ALL
	-- Формат выгрузки П-2 (квартальная) --
	SELECT FORM_CODE = '0617004',
		FNAME = 'Формат выгрузки формы П-2 (квартальная) для Росстата', PROC_NAME = 'BK_EXPORT_F0617004', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''
	UNION ALL
	-- П-2 кв. с 01.01.2011 --
	SELECT FORM_CODE = '0617004_11',
		FNAME = 'Формат выгрузки формы П-2 (квартальная) для Росстата', PROC_NAME = 'BK_EXPORT_F0617004_11', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''

	-- Формат выгрузки П-2 ИНВ (годовая) --
	UNION ALL
	SELECT FORM_CODE = 'П2_ИНВ',
		FNAME = 'Формат выгрузки формы П-2(ИНВ) для Росстата', PROC_NAME = 'BK_EXPORT_F0617010', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''
	WHERE @YEAR < 2012	

	UNION ALL
	SELECT FORM_CODE = 'П2_ИНВ',
		FNAME = 'Формат выгрузки формы П-2(ИНВ) для Росстата', PROC_NAME = 'BK_EXPORT_F0617010_2012', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''
	WHERE @YEAR >= 2012	

	UNION ALL
	-- Формат выгрузки П-4 --
	SELECT FORM_CODE = '0606010',
		FNAME = 'Формат выгрузки формы П-4 для Росстата', PROC_NAME = 'SK_EXPORT_F0606010', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''
	WHERE 
		@YEAR <= 2012	
	UNION ALL
	-- Формат выгрузки П-4 c 01.01.2013 --
	SELECT FORM_CODE = '0606010',
		FNAME = 'Формат выгрузки формы П-4 для Росстата', PROC_NAME = 'SK_EXPORT_F0606010_13', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''
	WHERE 
		@YEAR >= 2013		


	UNION ALL
	-- Формат выгрузки 1-ГС --
	SELECT FORM_CODE = '1GS',
		FNAME = 'Формат выгрузки формы 1-ГС для Росстата', PROC_NAME = 'KJ_EXPORT_1GS', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''
	UNION ALL
	-- Формат выгрузки 2-ГС --
	SELECT FORM_CODE = '2GS_GZ',
		FNAME = 'Формат выгрузки формы 2-ГС для Росстата', PROC_NAME = 'KJ_EXPORT_2GS', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''
	UNION ALL
	-- Формат выгрузки 1-МС --
	SELECT FORM_CODE = '1MS',
		FNAME = 'Формат выгрузки формы 1-МС для Росстата', PROC_NAME = 'KJ_EXPORT_1MS', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''
	UNION ALL
	-- Формат выгрузки 2-МС --
	SELECT FORM_CODE = '2MS',
		FNAME = 'Формат выгрузки формы 2-МС для Росстата', PROC_NAME = 'KJ_EXPORT_2MS', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''
	UNION ALL
	-- Формат выгрузки 1-Т(ГМС) --
	SELECT FORM_CODE = '1T_GMS',
		FNAME = 'Формат выгрузки формы 1-Т(ГМС) для Росстата', PROC_NAME = 'KJ_EXPORT_1T_GMS', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''
	UNION ALL
	-- Формат выгрузки 1-торги (квартальная) --
	SELECT FORM_CODE = '0607006',
		FNAME = 'Формат выгрузки формы 1-торги для Росстата', PROC_NAME = 'BK_EXPORT_F0607006', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''
	UNION ALL
	-- Формат выгрузки 1-торги (квартальная) --
	SELECT FORM_CODE = '1_ТОРГИ',
		FNAME = 'Формат выгрузки формы 1-торги для Росстата', PROC_NAME = 'BK_EXPORT_F0607006_11', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''
	UNION ALL
	-- Формат выгрузки 11 краткая (годовая) --
	SELECT FORM_CODE = '0602002',
		FNAME = 'Формат выгрузки формы 11-краткая для Росстата', PROC_NAME = 'BK_EXPORT_F0602002', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''

	UNION ALL
	SELECT FORM_CODE = 'КРАТ_11',
		FNAME = 'Формат выгрузки формы 11-краткая для Росстата', PROC_NAME = 'BK_EXPORT_F0602002_2012', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''
	WHERE 
		@YEAR >= 2012		
	
	-- Выгрузка АХД (МЗ 2013) --		
	UNION ALL
	SELECT
		FORM_CODE = 'AHD_EXPORT_REST',
		FNAME = 'Формат 1.00 (с 01.09.2013 г.)',
		PROC_NAME = 'BK_EXPORT_AHD_REST',
		PRG_SKRIPT = '',
		DIR = 'AHD',
		TEST_PROC = ''

	UNION ALL
	SELECT
		FORM_CODE = 'AHD_EXPORT_PROV',
		FNAME = 'Формат 1.00 (с 01.09.2013 г.)',
		PROC_NAME = 'BK_EXPORT_AHD_PROV',
		PRG_SKRIPT = '',
		DIR = 'AHD',
		TEST_PROC = ''
	

	-- Выгрузка данных об ОС --		
	UNION ALL
	SELECT
		FORM_CODE = 'EOD_EXPORT_INV1',
		FNAME = 'Формат 1.00 (с 01.01.2013 г.)',
		PROC_NAME = 'BK_EXPORT_INV1',
		PRG_SKRIPT = '',
		DIR = 'AHD',
		TEST_PROC = ''



GO


GRANT SELECT ON dbo.[BK_VIEW_EXPORT_FORMAT_NALOG_FN] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[EXPORT_FORMATS_PROV]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[EXPORT_FORMATS_PROV]

GO

CREATE VIEW dbo.EXPORT_FORMATS_PROV
AS
SELECT FNAME = 'Формтат выгрузки (от 17.04.2014)', PROC_NAME = 'SS_PROV_EXPORT', PRG_SKRIPT = '',DIR = 'PROV'



GO


GRANT SELECT ON dbo.[EXPORT_FORMATS_PROV] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[sa_item_move]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[sa_item_move]

GO

CREATE view dbo.sa_item_move
as

Select 
	P1.LINK, P1.NEW_FACE, P1.EMPL_LINK, P1.STAFF_LINK, P1.NUM_STAKE, P1.STATUS, P1.DATE_BEGIN, P1.DATE_END, P1.DATE_END2, 
	P1.USL_PR, P1.ISP, P1.TYPE, P1.REASON, P1.KONTR_DATE, P1.KONTR_NUM, P1.ORDER_LINK, P1.ACTIVE, P1.ETS_RAZR, P1.TEMP_LINK, 
	date_end3 = isnull(D.[DATE_END] , '20991231') 
from 
	dbo.item_move P1 
	CROSS APPLY (SELECT MIN(P2.[date_begin])-1 AS [DATE_END] FROM dbo.item_move P2 WHERE P1.EMPL_LINK = P2.EMPL_LINK AND P2.active = 1 AND P2.NEW_FACE <> 3 AND P2.[date_begin] > P1.[date_begin]) D
where 
	P1.active = 1 AND P1.NEW_FACE <> 3


GO


GRANT SELECT ON dbo.[sa_item_move] TO PUBLIC

GO




GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[DICTIONARY_POST]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[DICTIONARY_POST]

GO

CREATE VIEW dbo.DICTIONARY_POST
AS
SELECT 
	P.LINK,
	P.CODE,
	P.NAME ,
	PD.LINK_PKG ,
	code_PKG = G.CODE,	
	name_PKG = G.name,
	DATE_BEGIN = ISNULL(PD.DATE_BEGIN,'20000101'),
	DATE_END = ISNULL(((SELECT TOP 1 DATE_BEGIN FROM PKG_POST_date B WHERE pd.LINK_POST = B.link_POST AND B.date_begin > pd.date_begin ORDER BY B.date_begin DESC) - 1 ) ,'20991231') 
 FROM dbo.POST P LEFT JOIN dbo.PKG_POST_DATE pd ON pd.link_POST = P.LINK
			    LEFT JOIN dbo.PKG_POST G on G.link = pd.link_PKG
 WHERE 
	(SELECT workdate FROM user_dates)	
			BETWEEN  ISNULL(PD.DATE_BEGIN,'20000101') 
			AND 	ISNULL(((SELECT TOP 1 DATE_BEGIN FROM PKG_POST_date B WHERE pd.LINK_POST = B.link_POST AND B.date_begin > pd.date_begin ORDER BY B.date_begin DESC) - 1 ) ,'20991231') 	    



GO


GRANT SELECT ON dbo.[DICTIONARY_POST] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_PKG_POST_OKLAD_FN]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[SA_PKG_POST_OKLAD_FN]

GO

CREATE   FUNCTION dbo.SA_PKG_POST_OKLAD_FN (@date DATETIME = NULL) 
RETURNS TABLE 
AS
/*Вывод базовых окладов для должностей по ПКГ*/
RETURN

	select STAFF_HEAD = S.LINK_UP, STAFF_LINK = ST.LINK, ST.POST_LINK, ST.LINK_KBK, pkg_oklad = PKG.OKLAD, PKG.LINK_PKG
	from
		(	
			SELECT LINK_UP, MAX(DATE_BEGIN) AS DATE_BEGIN
			FROM 
				dbo.STAFF WITH (NOLOCK)
			WHERE 
				DATE_BEGIN <= ISNULL(@date,[dbo].SalaryCalcPeriod())
			GROUP BY LINK_UP
		) S 
		INNER JOIN STAFF ST WITH (NOLOCK) ON S.LINK_UP = ST.LINK_UP and S.DATE_BEGIN = ST.DATE_BEGIN
		LEFT JOIN (
			SELECT LINK_POST, LINK_PKG, PKG.OKLAD
			FROM
				dbo.[PKG_POST_DATE] PPD WITH (NOLOCK)
				CROSS APPLY (SELECT MIN(DATE_BEGIN)-1 AS DATE_END FROM dbo.[PKG_POST_DATE] PPD2 WITH (NOLOCK) WHERE PPD.LINK_POST = PPD2.LINK_POST AND PPD2.DATE_BEGIN > PPD.DATE_BEGIN) D
				OUTER APPLY (SELECT TOP 1 SUMMA AS OKLAD FROM dbo.PKG_OKLAD PO WITH (NOLOCK) WHERE PO.link_up = PPD.LINK_PKG and PO.date_begin <= ISNULL(@date,[dbo].SalaryCalcPeriod()) order by PO.date_begin desc) PKG
			WHERE
				ISNULL(@date,[dbo].SalaryCalcPeriod()) BETWEEN 	DATE_BEGIN AND ISNULL(D.DATE_END,ISNULL(@date,[dbo].SalaryCalcPeriod()))
			) AS PKG ON PKG.LINK_POST = ST.POST_LINK

GO


GRANT SELECT ON dbo.[SA_PKG_POST_OKLAD_FN] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[DOCUMENTS_DED_PR_TABLE_DGH]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[DOCUMENTS_DED_PR_TABLE_DGH]

GO

CREATE   VIEW dbo.DOCUMENTS_DED_PR_TABLE_DGH
AS
SELECT
	[LINK]		= S.LINK_UP,
	[ORDERS]		= S.ORDERS,

	[PERS_LINK] 			= S.PERS_LINK,
	[FIO]			= (SELECT rtrim(fm)+' '+left(im,1)+'.'+left(ot,1)+'.' FROM person WHERE LINK = S.PERS_LINK),
	[SUMMA]				= S.SUMMA,
	[DISBURS]			= S.DISBURS,
	[NOTE]				= S.NOTE,
	[SUMMA_BASE]		= 0,
	LIC_SCHET,
	S.LINK_EKR,
	CODE_EKR		= K.CODE
	
FROM 
	dbo.SDOC_VEDOM_DGH V INNER JOIN dbo.SDOC_VEDOM_DGH_TABLE1 S ON V.LINK_UP = S.LINK_UP
	LEFT JOIN dbo.SA_PERSON_ECARD_ACTUAL PE ON PE.PERS_LINK = S.PERS_LINK AND PE.CARD_LINK = V.LINK_CARD
	LEFT JOIN dbo.KOSGU K ON S.LINK_EKR = K.LINK
GO


GRANT SELECT ON dbo.[DOCUMENTS_DED_PR_TABLE_DGH] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[DOCUMENTS_DED_PR_DGH]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[DOCUMENTS_DED_PR_DGH]

GO

CREATE VIEW dbo.DOCUMENTS_DED_PR_DGH
AS
SELECT 
	[LINK]		= S.LINK,
	[NUMBER]	= S.NUMBER,
	[DATE]		= S.[DATE],
	[COMMENTARY] = S.[COMMENTARY],
	[FLAG_JC]	= S.FLAG_JC,
	[SUMMA]		= S.SUMMA_T,
	[REF_PAY]	= SD.LINK_PAY,
	[CODE_PAY]	= P.CODE,
	[NAME_PAY]	= P.[NAME],
	[LINK_VKR]	= SD.LINK_VKR,
	[NAME_VKR]	= COALESCE(F.CODE,'Пропорционально'),
	[LINK_EKR]	= SD.LINK_EKR,
	[CODE_EKR]	= COALESCE(K.CODE,'Пропорционально'),
	[REF_BASE]	= S.DATE_CALC,
	[MONTH_BASE]	= MONTH(S.DATE_CALC),
	[YEAR_BASE]	= YEAR(S.DATE_CALC),
	[NUMBER_PAYROLL]= SD.NUMBER_PR,
	[NAME_PAYROLL]	= SD.NAME_PR,
	[SALDO]		= SD.SALDO,	
	[NDFL]		= SD.NDFL,
	[TYP_PAYMENT]	= SD.TYP_PAYMENT,
	[CODE_EMPL]	= (SELECT TOP 1 TAB FROM dbo.EMPL WHERE LINK = SD.REF_KASSIR),	
	[NAME_EMPL]	= dbo.sd_GetEmplName(SD.REF_KASSIR),
	[REF_EMPL] 	= SD.REF_KASSIR,
	[TYP_ROUND]	= SD.TYP_ROUND,
	[TypOkr]	= SD.TypOkr,
	[CARD_LINK]	= SD.LINK_CARD,
	[CARD_CODE] 	= C.CODE,
	[CARD_NAME] 	= C.[NAME],
	[LINK_DEP]  	= S.LINK_DEP,
	RKO = COALESCE(CONVERT(VARCHAR(2),BD.CNT) + CASE WHEN COALESCE(SD.LINK_CARD,0) = 0 THEN ' РКО' ELSE ' Пл.П' END,''),
	dep.NAME as name_dep,
	exported,
	exported_c = case when coalesce(exported,0) = 1 then COALESCE(EXPORT_INFO,'Выгруж.') else '' end
FROM dbo.SDOC S 
	INNER JOIN dbo.DEPARTMENTS dep ON dep.link = s.LINK_DEP
	inner join dbo.SDOC_VEDOM_DGH SD ON S.LINK = SD.LINK_UP
	LEFT JOIN dbo.PAYS P ON P.LINK = SD.LINK_PAY
	LEFT JOIN dbo.CARDS C ON SD.LINK_CARD = C.LINK
	LEFT JOIN dbo.SAL_SFIN F ON SD.LINK_VKR = F.LINK
	LEFT JOIN dbo.KOSGU K ON SD.LINK_EKR = K.LINK
	LEFT JOIN (Select LINK_VEDOM, CNT = COUNT(*) 
				FROM DBO.SDOC_VEDOM_RKO R
					INNER JOIN dbo.G_PROV G ON R.LINK_RKO = G.LINK
					INNER JOIN dbo.S_OBJECTS O ON O.LINK = G.[OBJECT]
				WHERE
					O.CODE IN ('DOCUMENTS_RKO', 'DOCUMENTS_PAY')	
				GROUP BY LINK_VEDOM ) BD ON BD.LINK_VEDOM = S.LINK


GO


GRANT SELECT ON dbo.[DOCUMENTS_DED_PR_DGH] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_PKG_POST_FN]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[SA_PKG_POST_FN]

GO

CREATE   FUNCTION dbo.SA_PKG_POST_FN(@date DATETIME = NULL) 
RETURNS TABLE 
AS
/*Вывод квалификационных групп с базовыми окладами на заданную дату*/
RETURN

	SELECT 
		P.LINK,
		P.CODE,
		P.NAME,
		PKG.OKLAD
	FROM 
		dbo.SALARY_CALC_PERIOD UI
		INNER JOIN dbo.PKG_POST P WITH (NOLOCK) on 1=1
		OUTER APPLY (SELECT TOP 1 SUMMA AS OKLAD FROM dbo.PKG_OKLAD PO WITH (NOLOCK) WHERE PO.link_up = P.link and PO.date_begin <= ISNULL(@date,UI.SC_DATE) order by PO.date_begin desc) PKG
		 

GO


GRANT SELECT ON dbo.[SA_PKG_POST_FN] TO PUBLIC

GO

GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FB_FINANS_POLUCH]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[FB_FINANS_POLUCH]
GO

CREATE                 	FUNCTION dbo.FB_FINANS_POLUCH(@varKSintFyear int, 
					@varKSdDateB datetime, 
					@varKSdDateE datetime, 
					@varKSintPer_num int, 
					@varKSintSumType numeric (5, 3), 
					@varKSFinLink int = 0, 
					@varKSFinObjCode char(100), 
					@varKSintTypePer int = 1,
					@varKScTypeBudg Char(1) = '1')
-- за год @varKSintTypePer = 1 - за год,
--			   = 2 - по кварталам,
--			   = 3 - по месяцам
-- за период = + 10		  
RETURNS @varKSResTable TABLE
	(dep	[int] NULL,
	 dep_acc [int] NULL,
	 rbs_dep [int] NULL,
	 rbs_acc [int] NULL,
	 vkr	[int] NULL,
	 ekr	[int] NULL, 
	 dop_cl	[int] NULL, 
	 P1	[numeric](28, 2) NULL,
	 P2	[numeric](28, 2) NULL,
	 P3	[numeric](28, 2) NULL,
	 P4	[numeric](28, 2) NULL,
	 P5	[numeric](28, 2) NULL,
	 P6	[numeric](28, 2) NULL,
	 P7	[numeric](28, 2) NULL,
	 P8	[numeric](28, 2) NULL,
	 P9	[numeric](28, 2) NULL,
	 P10	[numeric](28, 2) NULL,
	 P11	[numeric](28, 2) NULL,
	 P12	[numeric](28, 2) NULL)

AS
BEGIN
DECLARE @varKSAccount int,
	@varKSFinObj int,
	@varKSdEndDate1 datetime,
	@varKSdEndDate2 datetime,
	@varKSdEndDate3 datetime,
	@varKSdEndDate4 datetime,
	@varKSdEndDate5 datetime,
	@varKSdEndDate6 datetime,
	@varKSdEndDate7 datetime,
	@varKSdEndDate8 datetime,
	@varKSdEndDate9 datetime,
	@varKSdEndDate10 datetime,
	@varKSdEndDate11 datetime,
	@varKSdEndDate12 datetime,
	@varKSdBegDate1 datetime,
	@varKSdBegDate2 datetime,
	@varKSdBegDate3 datetime,
	@varKSdBegDate4 datetime,
	@varKSdBegDate5 datetime,
	@varKSdBegDate6 datetime,
	@varKSdBegDate7 datetime,
	@varKSdBegDate8 datetime,
	@varKSdBegDate9 datetime,
	@varKSdBegDate10 datetime,
	@varKSdBegDate11 datetime,
	@varKSdBegDate12 datetime,
	@varKSdDateEndP	 datetime,
	@varKSdDateBegP	 datetime,
	@varKSiOwnDep	 int,
	@cSinth			 char(3)

DECLARE @varKSTempTable TABLE 
	(dep	[int] NULL,
	 dep_acc [int] NULL,
	 rbs_dep [int] NULL,
	 rbs_acc [int] NULL,
	 vkr	[int] NULL,
	 ekr	[int] NULL, 
	 dop_cl	[int] NULL, 
	 P1	[numeric](28, 2) NULL,
	 P2	[numeric](28, 2) NULL,
	 P3	[numeric](28, 2) NULL,
	 P4	[numeric](28, 2) NULL,
	 P5	[numeric](28, 2) NULL,
	 P6	[numeric](28, 2) NULL,
	 P7	[numeric](28, 2) NULL,
	 P8	[numeric](28, 2) NULL,
	 P9	[numeric](28, 2) NULL,
	 P10	[numeric](28, 2) NULL,
	 P11	[numeric](28, 2) NULL,
	 P12	[numeric](28, 2) NULL)

DECLARE @varKSTableOborot TABLE 
	(DATE_PROV	datetime null,
	 DEP	 	[int] NULL,
	 DEP_ACC 	[int] NULL,
	 RBS_DEP 	[int] NULL,
	 RBS_ACC 	[int] NULL,
	 INDATE 	datetime null,
	 VKR	[int] NULL,
	 EKR	[int] NULL, 
	 DOP_CL	[int] NULL, 
	 SUMMA	[numeric](19, 2) NULL)

set @varKSiOwnDep = isnull (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())
set @varKSdBegDate1 = convert(datetime,convert(char(4),@varKSintFyear) + '0101')
SET @varKSdBegDate2 =  convert(datetime,convert(char(4),@varKSintFyear) + '0201')
SET @varKSdBegDate3 =  convert(datetime,convert(char(4),@varKSintFyear) + '0301')
SET @varKSdBegDate4 =  convert(datetime,convert(char(4),@varKSintFyear) + '0401')
SET @varKSdBegDate5 =  convert(datetime,convert(char(4),@varKSintFyear) + '0501')
SET @varKSdBegDate6 =  convert(datetime,convert(char(4),@varKSintFyear) + '0601')
SET @varKSdBegDate7 =  convert(datetime,convert(char(4),@varKSintFyear) + '0701')
SET @varKSdBegDate8 =  convert(datetime,convert(char(4),@varKSintFyear) + '0801')
SET @varKSdBegDate9 =  convert(datetime,convert(char(4),@varKSintFyear) + '0901')
SET @varKSdBegDate10 =  convert(datetime,convert(char(4),@varKSintFyear) + '1001')
SET @varKSdBegDate11 =  convert(datetime,convert(char(4),@varKSintFyear) + '1101')
SET @varKSdBegDate12 =  convert(datetime,convert(char(4),@varKSintFyear) + '1201')
SET @varKSdEndDate1 = @varKSdBegDate2 - 1
SET @varKSdEndDate2 = @varKSdBegDate3 - 1
SET @varKSdEndDate3 = @varKSdBegDate4 - 1
SET @varKSdEndDate4 = @varKSdBegDate5 - 1
SET @varKSdEndDate5 = @varKSdBegDate6 - 1
SET @varKSdEndDate6 = @varKSdBegDate7 - 1
SET @varKSdEndDate7 = @varKSdBegDate8 - 1
SET @varKSdEndDate8 = @varKSdBegDate9 - 1
SET @varKSdEndDate9 = @varKSdBegDate10 - 1
SET @varKSdEndDate10 = @varKSdBegDate11 - 1
SET @varKSdEndDate11 = @varKSdBegDate12 - 1
SET @varKSdEndDate12 = convert(datetime,convert(char(4),@varKSintFyear + 1)+'0101') - 1

if @varKSdDateB is null 
	set @varKSdDateB = @varKSdBegDate1

select @varKSintPer_num  = (case @varKSintTypePer
				when 13 then @varKSintPer_num				
				when 12 then (case when @varKSintPer_num < 4 then 1
						when @varKSintPer_num < 7 then 4
						when @varKSintPer_num < 10 then 7
						else 10 end)
				when 11 then 1
				else 0 end)
					
/*
IF @varKSFinObjCode like '%_ASSIGN%'
	SELECT	@varKSintLimType = 0,
		@varKSintLimPer = max(FIN_SMETA_PER)
		FROM WorkMode
ELSE
	SELECT	@varKSintLimType = max(FIN_LIM_TYPE),
		@varKSintLimPer = max(FIN_LIM_PER)
		FROM WorkMode

IF @varKSintLimType = 0 or @varKSintLimPer = 0 or @varKSintPer_num = 0
*/

IF @varKSintTypePer < 12 or @varKSintPer_num = 0
begin
	set @varKSdDateEndP = convert(datetime,convert(char(4),@varKSintFyear+1) + '0101') - 1
	set @varKSdDateBegP= convert(datetime,convert(char(4),@varKSintFyear) + '0101')
end
else 
begin
	if @varKSintTypePer = 12
	BEGIN
		if @varKSintPer_num = 10
		begin
			set @varKSdDateEndP = convert(datetime,convert(char(4),@varKSintFyear+1) + '0101') - 1
			set @varKSdDateBegP = convert(datetime,(convert(char(4),@varKSintFyear) + '1001'))		
		end
		else
		begin
			if @varKSintPer_num = 7
				set @varKSdDateEndP = convert(datetime,convert(char(4),@varKSintFyear+1) + convert(char(2),@varKSintPer_num + 3) + '01') - 1
			else 
				set @varKSdDateEndP = convert(datetime,convert(char(4),@varKSintFyear+1) + '0' + convert(char(1),@varKSintPer_num + 3) + '01') - 1
			set @varKSdDateBegP = convert(datetime,(convert(char(4),@varKSintFyear) + '0' + convert(char(1),@varKSintPer_num) + '01'))
		end
	END 
	else 
	BEGIN
		if @varKSintPer_num = 12
			set @varKSdDateEndP = convert(datetime,convert(char(4),@varKSintFyear+1) + '0101') - 1
		else 		
			if @varKSintPer_num > 8
				set @varKSdDateEndP = convert(datetime,convert(char(4),@varKSintFyear+1) + convert(char(2),@varKSintPer_num + 1) + '01') - 1
			else 
				set @varKSdDateEndP = convert(datetime,convert(char(4),@varKSintFyear+1) + '0' + convert(char(1),@varKSintPer_num + 1) + '01') - 1
		if @varKSintPer_num < 10
			set @varKSdDateBegP = convert(datetime,(convert(char(4),@varKSintFyear) + '0' + convert(char(1),@varKSintPer_num) + '01'))
		else 		
			set @varKSdDateBegP = convert(datetime,(convert(char(4),@varKSintFyear) + convert(char(2),@varKSintPer_num) + '01'))

	END
end   

-- дата расчета не должна выходить за пределы периода
if @varKSdDateE is null or @varKSdDateE > @varKSdDateEndP
	set @varKSdDateE = @varKSdDateEndP
/*
if  @varKSFinLink = 0 or @varKSFinLink is null
	select  @varKSFinObj = link from s_objects where code = @varKSFinObjCode
else */
select  @varKSFinObj = object from g_prov where link = @varKSFinLink

if @varKSFinObjCode like '%_ASSIGN%'
	set @cSinth = '503'
else
    set @cSinth = '501'

--SELECT @varKSAccount = link 
--FROM s_accounts 
--WHERE cSinth = @cSinth and cAnalit = '12' and cSource = @varKScTypeBudg  
	
/*IF @varKSFinObjCode like '%_ASSIGN%'
INSERT INTO @varKSResTable (dep, dep_acc, vkr, ekr,dop_cl, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT GP.dep, FH.ACCOUNT, F.vkr, F.ekr, F.dop_cl, 
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 1) or (@varKSintTypePer = 13 and @varKSintPer_num = 1)) then sum(F.p1) * @varKSintSumType else 0 end) as p1,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 1) or (@varKSintTypePer = 13 and @varKSintPer_num = 2)) then sum(F.p2) * @varKSintSumType else 0 end) as p2,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 1) or (@varKSintTypePer = 13 and @varKSintPer_num = 3)) then sum(F.p3) * @varKSintSumType else 0 end) as p3,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 4) or (@varKSintTypePer = 13 and @varKSintPer_num = 4)) then sum(F.p4) * @varKSintSumType else 0 end) as p4,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 4) or (@varKSintTypePer = 13 and @varKSintPer_num = 5)) then sum(F.p5) * @varKSintSumType else 0 end) as p5,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 4) or (@varKSintTypePer = 13 and @varKSintPer_num = 6)) then sum(F.p6) * @varKSintSumType else 0 end) as p6,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 7) or (@varKSintTypePer = 13 and @varKSintPer_num = 7)) then sum(F.p7) * @varKSintSumType else 0 end) as p7,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 7) or (@varKSintTypePer = 13 and @varKSintPer_num = 8)) then sum(F.p8) * @varKSintSumType else 0 end) as p8,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 7) or (@varKSintTypePer = 13 and @varKSintPer_num = 9)) then sum(F.p9) * @varKSintSumType else 0 end) as p9,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 10) or (@varKSintTypePer = 13 and @varKSintPer_num = 10)) then sum(F.p10) * @varKSintSumType else 0 end) as p10,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 10) or (@varKSintTypePer = 13 and @varKSintPer_num = 11)) then sum(F.p11) * @varKSintSumType else 0 end) as p11,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 10) or (@varKSintTypePer = 13 and @varKSintPer_num = 12)) then sum(F.p12) * @varKSintSumType else 0 end) as p12
	from finanse F
	inner join G_Prov GP on GP.object in (select link from s_objects where Code = 'FINANS_ASSIGN' and NOT @varKSFinObjCode like '%_SVOD')
				and GP.DATE_PROV is not null  
				and GP.DEP = @varKSiOwnDep
				and GP.DATE_PROV <= @varKSdDateE
				and GP.DATE_PROV >= @varKSdDateB
				and not GP.LINK = @varKSFinLink
				and F.link_up = GP.link
	inner join FINANSE_HEAD FH on FH.LINK = GP.LINK and FH.FYEAR = @varKSintFyear
	inner join department_accounts DA on da.link = FH.ACCOUNT
						and ((DA.type = 2 or DA.type = 3) and @varKScTypeBudg = '1'
						or (DA.type = 1 or DA.type = 4)  and @varKScTypeBudg = '2' or @varKScTypeBudg is null)
	group by DA.LINK_UP, FH.ACCOUNT, GP.dep, GP.ACC, vkr, ekr, dop_cl
ELSE 
begin*/
	--INSERT INTO @varKSTableOborot (DATE_PROV, DEP, DEP_ACC, RBS_DEP, RBS_ACC, INDATE, VKR, EKR,DOP_CL, SUMMA)
	--SELECT DATE_PROV,DEP, DEP_ACC, DEP_LINK, null, INDATE, KBK AS VKR, EKR, AP2 AS DOP_CL, isnull(k_summa,0)
	--from FB_LimitOborotByPeriod(@varKSdDateBegP,@varKSdDateEndP, @varKSAccount)
	--where not LINK_UP = @varKSFinLink
	--	and DEP_LINK = @varKSiOwnDep
	--	and DATE_PROV between @varKSdDateB and @varKSdDateE
	
	SELECT @varKSAccount = link 
	FROM s_accounts 
	WHERE cSinth = @cSinth and cAnalit = '13' and cSource = @varKScTypeBudg  

	INSERT INTO @varKSTableOborot (DATE_PROV, DEP, DEP_ACC, RBS_DEP, RBS_ACC, INDATE, VKR, EKR,DOP_CL, SUMMA)
	SELECT DATE_PROV,DEP, DEP_ACC, DEP_LINK, ACC_LINK, INDATE, KBK AS VKR, EKR, AP2 AS DOP_CL, isnull(k_summa,0)
	from FB_LimitOborotByPeriod(@varKSdDateBegP,@varKSdDateEndP, @varKSAccount)
	where not LINK_UP = @varKSFinLink
		and DEP_LINK = @varKSiOwnDep
		and DATE_PROV between @varKSdDateB and @varKSdDateE
		and isnull(k_summa,0) <> 0
		
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, summa,0,0,0,0,0,0,0,0,0,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate1 and @varKSdEndDate1) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate1 and @varKSdEndDate1))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, 0, summa,0,0,0,0,0,0,0,0,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate2 and @varKSdEndDate2) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate2 and @varKSdEndDate2))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, 0,0,summa,0,0,0,0,0,0,0,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate3 and @varKSdEndDate3) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate3 and @varKSdEndDate3))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, 0,0,0,summa,0,0,0,0,0,0,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate4 and @varKSdEndDate4) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate4 and @varKSdEndDate4))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL,0,0,0,0,summa,0,0,0,0,0,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate5 and @varKSdEndDate5) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate5 and @varKSdEndDate5))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, 0,0,0,0,0,summa,0,0,0,0,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate6 and @varKSdEndDate6) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate6 and @varKSdEndDate6))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, 0,0,0,0,0,0,summa,0,0,0,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate7 and @varKSdEndDate7) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate7 and @varKSdEndDate7))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, 0,0,0,0,0,0,0,summa,0,0,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate8 and @varKSdEndDate8) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate8 and @varKSdEndDate8))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, 0,0,0,0,0,0,0,0,summa,0,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate9 and @varKSdEndDate9) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate9 and @varKSdEndDate9))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, 0,0,0,0,0,0,0,0,0,summa,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate10 and @varKSdEndDate10) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate10 and @varKSdEndDate10))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, 0,0,0,0,0,0,0,0,0,0,summa,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate11 and @varKSdEndDate11) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate11 and @varKSdEndDate11))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL,0,0,0,0,0,0,0,0,0,0,0,summa
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate12 and @varKSdEndDate12) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate12 and @varKSdEndDate12))
					
	
		INSERT INTO @varKSresTable(dep, dep_acc, rbs_dep, rbs_acc, vkr, ekr, dop_cl, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
			SELECT f.dep, F.DEP_ACC, f.rbs_dep, f.rbs_acc, F.vkr, F.ekr, F.dop_cl,  
			sum(F.p1) * @varKSintSumType as p1,
			sum(F.p2) * @varKSintSumType as p2, 
			sum(F.p3) * @varKSintSumType as p3, 
			sum(F.p4) * @varKSintSumType as p4, 
			sum(F.p5) * @varKSintSumType as p5, 
			sum(F.p6) * @varKSintSumType as p6, 
			sum(F.p7) * @varKSintSumType as p7, 
			sum(F.p8) * @varKSintSumType as p8, 
			sum(F.p9) * @varKSintSumType as p9, 
			sum(F.p10) * @varKSintSumType as p10, 
			sum(F.p11) * @varKSintSumType as p11, 
			sum(F.p12) * @varKSintSumType as p12
			from @varKSTempTable F 
			group by dep, DEP_acc, rbs_dep, rbs_acc, vkr, ekr, dop_cl
--END 	

IF @varKSintTypePer = 1 or @varKSintTypePer > 10
	UPDATE @varKSResTable
		SET p1 = p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9 + p10 + p11 + p12,
		p2 = 0,	p3 = 0,	p4 = 0,	p5 = 0,	p6 = 0,	p7 = 0,	p8 = 0,	p9 = 0,	p10 = 0, p11 = 0, p12 = 0
IF @varKSintTypePer = 2
	UPDATE @varKSResTable
		SET p1 = p1 + p2 + p3, p2 = 0, p3 = 0,
		p4 = p4 + p5 + p6, p5 = 0, p6 = 0,
		p7 = p7 + p8 + p9, p8 = 0, p9 = 0,
		p10 = p10 + p11 + p12, p11 = 0, p12 = 0

RETURN
END
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BD_JURN_BO]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[BD_JURN_BO]
GO


/*
© Кейсистемс (Keysystems), 2005
*/

CREATE     VIEW BD_JURN_BO
AS
SELECT
 [LINK] 	= JB.LINK,
 [FLAG_HAND]	= (CASE WHEN JB.LINK_PO_PROV IS NULL THEN 0 ELSE 1 END),
 [AP1]		= JB.LINK_DOC,
 [CODE_AP1]	= O.NUMBER,
 [DATE_AP1]	= JB.DATE_DOC,	
 [NAME_AP1]	= O.INFO,
 [TYPE_AP1]	= O.TYPE,
 [KBK_LINK]	= JB.LINK_KBK,
 [KBK_CODE]	= (SELECT CODE FROM dbo.KL_KBK WHERE LINK =JB.LINK_KBK),	
 [KBK_TYPE]	= (SELECT [TYPE] FROM dbo.KL_KBK WHERE LINK =JB.LINK_KBK),	
 [SGU_LINK]	= JB.LINK_SGU,
 [SGU_CODE]	= (SELECT CODE FROM dbo.DICTIONARY_KOSGU WHERE LINK =JB.LINK_SGU),	
 [SGU_NAME]	= (SELECT NAME FROM dbo.DICTIONARY_KOSGU WHERE LINK =JB.LINK_SGU),	
 [DOP_LINK]	= JB.LINK_DOP,
 [DOP_CODE]     = (SELECT CODE FROM dbo.BD_DOP_CLASSIF WHERE LINK =JB.LINK_DOP),	
 [DOP_NAME]     = (SELECT NAME FROM dbo.BD_DOP_CLASSIF WHERE LINK =JB.LINK_DOP),	
 [ACCOUNT_LINK] = JB.LINK_ACCOUNT,
 [ACCOUNT_CODE] = (SELECT CODE FROM dbo.DICTIONARY_ACCOUNTS WHERE LINK =JB.LINK_ACCOUNT),	
 [ACCOUNT_NAME] = (SELECT ANAME FROM dbo.DICTIONARY_ACCOUNTS WHERE LINK =JB.LINK_ACCOUNT),	
 [SUMMA]	=  JB.SUMMA,
 [IST_FIN]	=  JB.IST_FIN,
 FS_NAME = FS.NAME,
 [PROV_LINK]	=  JB.LINK_PO_PROV,
 [DATE_PR]	=  JB.DATE_PR,	
 [DATE_SN]	=  JB.DATE_SN,
 [COMMENT] 	=  JB.COMMENT,
 [TP]		= O.TP,
 [OBJECT]	= O.OBJECT,
 [DOC_LINK]	= O.DOC_LINK,
 [DEP]		= O.DEP,
 JB.DO,
 DO_NAME = case JB.DO when 1 then 'Денежное' else 'Бюджетное' end
FROM dbo.JURN_BO JB
inner join BB_FIN_SOURCE FS on FS.CODE = JB.IST_FIN
left join dbo.BD_OSNOV O on O.LINK =JB.LINK_DOC





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[TRAVEL]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[TRAVEL]

GO

CREATE   VIEW [dbo].TRAVEL
AS
SELECT it.link, 
	[flag_jc] = (CASE WHEN R.ref_doc IS NULL THEN 0 ELSE 1 END),
	o.number, o.date, o.dep_link, it.empl_link, it.order_link, 
	[tab_num] = LEFT(E.TAB,6), 
	[fio] = LEFT(ISNULL( LTRIM(PERS.FM) + ' ' + LTRIM(PERS.IM) + ' ' + LTRIM(PERS.OT),'Не заполнено'),100), 
	fm = LTRIM(PERS.FM), im = LTRIM(PERS.IM), ot = LTRIM(PERS.OT),
	[subdiv] = S.[NAME], 
	[post] = p.[NAME], 
	it.place, it.org, it.date_begin, duration = datediff(day, it.date_begin, it.date_end)+1, it.date_end, it.type_link, 
	[type_name] = KV.[name],
	it.target,it.target_DOP, it.payer, it.reason, it.udost_num, it.udost_date, it.active,
	dep.NAME as name_dep 
FROM 
	dbo.item_travel it 
	inner join dbo.orders o on it.order_link=o.link
	INNER JOIN dbo.EMPL E on it.empl_link = E.LINK
	INNER JOIN dbo.PERSON PERS on E.PERS_LINK = PERS.LINK
    INNER JOIN dbo.DEPARTMENTS dep ON dep.link = E.DEP_LINK
	inner JOIN USER_INFO UI ON (UI.CODE_TASK = 'KADRY' OR UI.DEP_LINK = O.DEP_LINK)
	LEFT JOIN dbo.empl_staff1(DEFAULT) es ON ES.EMPL_LINK = it.EMPL_LINK
	LEFT JOIN dbo.subdiv s ON s.link=es.subdiv_link
	LEFT JOIN dbo.post p on p.link=es.post_link
	LEFT JOIN dbo.komand_vid KV ON KV.LINK = it.type_link
	LEFT JOIN ( 
		select distinct sd.ref_doc from dbo.SDOC S INNER JOIN dbo.SDOC_AVAC SD ON (S.LINK = SD.LINK_UP AND S.OBJECT =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'DOCUMENTS_CALC_TRAVEL'))
	) R ON R.ref_doc = it.link


GO


GRANT SELECT ON dbo.[TRAVEL] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[sa_ets_actual]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[sa_ets_actual]

GO

CREATE  function [dbo].sa_ets_actual(@date datetime = NULL)
returns table
as

return

SELECT 
	H.LINK,
	NAME, 
	name_short,
	T.RAZR, 
	T.KOEF, 
	T.ADDIT,
	MIN_VAL = ISNULL(M.VAL,0),	
	summa = case when OPT1.VAL <=1 then SUMMA.VAL else ROUND(SUMMA.VAL, 0, OPT1.VAL - 2) end
from 
	dbo.ets_head H WITH (NOLOCK) 
	INNER JOIN dbo.ETS T WITH (NOLOCK)ON H.link = T.link_up
	INNER JOIN dbo.SALARY_CALC_PERIOD CP ON 1=1 
	CROSS JOIN (SELECT dbo.sa_get_option_by_code('SA_ETS_HEAD_OPT1') AS VAL) OPT1
	CROSS APPLY (SELECT MIN(T1.DATE_BEGIN)-1 AS DATE_END FROM dbo.ETS T1 WITH (NOLOCK) WHERE T1.link_up = T.link_up AND T1.RAZR = T.RAZR AND T1.DATE_BEGIN > T.DATE_BEGIN) D
	CROSS APPLY (SELECT MAX(TARIF) AS TARIF FROM dbo.MINROT A WITH (NOLOCK) WHERE PERIOD <= ISNULL(@date,CP.SC_DATE)) TT	
	OUTER APPLY (SELECT TOP 1 M.date_begin, min_val, priznak FROM dbo.ets_min_val M WITH (NOLOCK) WHERE M.link_up = T.LINK_UP AND ISNULL(@date,CP.SC_DATE) >= M.date_begin ORDER BY M.date_begin DESC) MV
	CROSS APPLY (SELECT (case when ISNULL(priznak,0) = 0 then min_val else TT.TARIF end) AS VAL) M 
	CROSS APPLY (SELECT ISNULL(T.KOEF,0) * ISNULL(M.VAL,0) + ISNULL(ADDIT,0) AS VAL) SUMMA 

GO

GRANT SELECT ON dbo.[sa_ets_actual] TO PUBLIC

GO

GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_ETS]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[SA_ETS]

GO

CREATE VIEW [dbo].SA_ETS AS

SELECT 
	T.LINK, 
	T.LINK_UP, 
	T.RAZR, 
	T.KOEF, 
	T.ADDIT,
	T.date_begin,  
	D.DATE_END,	
	sal_actual = (case when CP.SC_DATE between T.date_begin and coalesce(D.DATE_END,'30000101') then 1 else 0 end),
	MIN_VAL = ISNULL(M.VAL,0),
	summa = case when OPT1.VAL <=1 then SUMMA.VAL else ROUND(SUMMA.VAL, 0, OPT1.VAL - 2) end
from 
	dbo.ETS T 
	INNER JOIN dbo.SALARY_CALC_PERIOD CP ON 1=1 
	CROSS JOIN (SELECT dbo.sa_get_option_by_code('SA_ETS_HEAD_OPT1') AS VAL) OPT1
	CROSS APPLY (SELECT MIN(T1.DATE_BEGIN)-1 AS DATE_END FROM dbo.ETS T1 WHERE T1.link_up = T.link_up AND T1.RAZR = T.RAZR AND T1.DATE_BEGIN > T.DATE_BEGIN) D
	CROSS APPLY (SELECT MAX(TARIF) AS TARIF FROM dbo.MINROT A WHERE PERIOD <= CP.SC_DATE) TT	
	OUTER APPLY (SELECT TOP 1 M.date_begin, min_val, priznak FROM dbo.ets_min_val M WHERE M.link_up = T.LINK_UP AND CP.SC_DATE >= M.date_begin ORDER BY M.date_begin DESC) MV
	CROSS APPLY (SELECT (case when ISNULL(priznak,0) = 0 then min_val else TT.TARIF end) AS VAL) M 
	CROSS APPLY (SELECT ISNULL(T.KOEF,0) * ISNULL(M.VAL,0) + ISNULL(ADDIT,0) AS VAL) SUMMA 
GO


GRANT SELECT ON dbo.[SA_ETS] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_ETS_MIN_VAL]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[SA_ETS_MIN_VAL]

GO

CREATE View [dbo].SA_ETS_MIN_VAL as
select 
	link,
	link_up,
	date_begin,
	D.DATE_END,	
	priznak, 
	min_val,
	sal_actual = (case when CP.SC_DATE between date_begin and coalesce( D.DATE_END,'30000101') then 1 else 0 end),
	comment = (case when priznak = 1 then 'Ставка 1 разряда берется из настроек по зарплате' else '' end)
from 
	dbo.ets_min_val M
	INNER JOIN dbo.SALARY_CALC_PERIOD CP ON 1=1
	CROSS APPLY (SELECT MIN(M1.DATE_BEGIN)-1 AS DATE_END FROM dbo.ets_min_val M1 WHERE M1.link_up = M.link_up AND M1.DATE_BEGIN > M.DATE_BEGIN) D
GO


GRANT SELECT ON dbo.[SA_ETS_MIN_VAL] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[sa_all_pays_order_money_date]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[sa_all_pays_order_money_date]

GO

CREATE function dbo.sa_all_pays_order_money_date(@ORDER_LINK int = -1, @date datetime = null, @WORK TINYINT = 1) 

/*	
	Функция выводит все постоянные начисления для приказов
*/

RETURNS @basis_sum table (item_link int, link_pay int, summa_base numeric(18,2), perc numeric(18,2), summa numeric(18,2))
Begin

IF @WORK > 0
BEGIN

	SET @date = (SELECT ISNULL(@date,UD.WORKDATE) FROM dbo.USER_DATES UD)

	declare @DEP_LINK int
	SELECT TOP 1 @DEP_LINK = ZB_LINK FROM dbo.KS_OPTIONS_ZB
	IF @DEP_LINK IS NULL
		SELECT @DEP_LINK = dbo.GetOwnDepLink()

		----
		declare @decode_base table ( link int identity(1,1) not null,	
						link_pay int, -- надбавки
						link_base_pay int, -- базовый вид оплаты
						marker tinyint,
						num_order tinyint,
						WAY_CALC TINYINT)
		
		-- Список надбавок: рабочая таблица для раскодирования групп. Содержит деревья по каждой должности.
		insert into @decode_base (link_pay, link_base_pay, marker, num_order, WAY_CALC)
		Select distinct ap.PAY_LINK, 0, 0, 0, W.CODE
		from 
			dbo.ORDERS O WITH (NOLOCK)
			INNER JOIN dbo.ITEM_MOVE M WITH (NOLOCK) ON M.ORDER_LINK = O.LINK
			INNER JOIN dbo.MONEY_PERIOD as ap WITH (NOLOCK) ON M.LINK = AP.item_link
			INNER JOIN dbo.PAYS P WITH (NOLOCK) ON ap.PAY_LINK = p.LINK
			INNER JOIN dbo.WAY_CALC W WITH (NOLOCK) ON (P.WAY_CALC = W.CODE AND W.[TYPE] = 1 AND const_pay_empl = 1 AND W.CODE <> 16)
		where 	
			( @ORDER_LINK = -1 and O.DEP_LINK = @DEP_LINK
			OR 
			M.ORDER_LINK = @ORDER_LINK )

		declare @link int 
		declare @link_pay int

		declare @num_order int
		declare @doit int
	
		/*Черный список видов оплат, которые зацыклены. Для прекращения их рассмотрения при построении дерева.*/
		declare @black_list table (link_pay int)

		SET @NUM_ORDER = 0
		SET @DOIT = 1
		
		WHILE  @DOIT = 1 
		BEGIN
			SET @NUM_ORDER = @NUM_ORDER + 1
			--ПРОВЕРИМ ОЧЕРЕДНОЕ НАЧИСЛЕНИЕ (ЛИСТ ДЕРЕВА) НА НАЛИЧИЕ У НЕГО БАЗОВЫХ НАЧИСЛЕНИЙ (СВОИХ ЛИСТЬЕВ)
			WHILE EXISTS (SELECT * FROM @DECODE_BASE WHERE MARKER = 0 AND LINK_BASE_PAY = 0)
			BEGIN
				/*НАХОДИМ ОЧЕРЕДНОЙ ЛИСТ И РАССМАТРИВАЕМП ЕГО КАК УЗЕЛ*/	
				SELECT @LINK = COALESCE(MIN(LINK),0) FROM @DECODE_BASE WHERE MARKER = 0 AND LINK_BASE_PAY = 0 
				SELECT @LINK_PAY = LINK_PAY FROM @DECODE_BASE WHERE LINK = @LINK
				
				/*ДЛЯ ОЧЕРЕДНОГО НАЧИСЛЕНИЯ (УЗЛА) ОПРЕДЕЛЯЮТСЯ СВОИ ЛИСТЬЯ*/
				IF EXISTS (SELECT * FROM dbo.PAYS P INNER JOIN dbo.WAY_CALC W ON P.WAY_CALC = W.CODE
								WHERE P.LINK = @LINK_PAY AND P.[OBJECT] = 1 AND W.[TYPE] = 1 AND W.CONST_PAY_EMPL = 1 AND W.ISPERCENT IN (1,4) -- База может быть только у начислений процентом и коэффициентом
							)
				BEGIN					
				
					INSERT INTO @DECODE_BASE (LINK_PAY, LINK_BASE_PAY, MARKER, NUM_ORDER, WAY_CALC)
					SELECT DISTINCT @LINK_PAY, PAY_LINK, 0, @NUM_ORDER, WAY_CALC 
					FROM 
						DBO.GROUP_PAYS(@LINK_PAY) GP
						INNER JOIN (SELECT DISTINCT P.LINK, P.WAY_CALC FROM DBO.PAYS P WITH (NOLOCK) INNER JOIN DBO.WAY_CALC W WITH (NOLOCK) ON (P.WAY_CALC = W.CODE AND P.OBJECT = 1 AND W.[TYPE] = 1 AND W.CONST_PAY_EMPL = 1)) P ON GP.PAY_LINK = P.LINK
					WHERE 
						PAY_LINK <> @LINK_PAY 
						AND NOT EXISTS (SELECT LINK_PAY FROM @DECODE_BASE WHERE NUM_ORDER <= @NUM_ORDER AND LINK_PAY = PAY_LINK AND  LINK_BASE_PAY = @LINK_PAY) 

				END				
				/*В ЧЕРНЫЙ СПИСКО ЗАПИШЕМ ВИНОВНИКА ЗАЦИКЛИВАНИЯ, ЧТОБЫ ДАЛЬШЕ С НИМ НЕ ИМЕТЬ ДЕЛ*/
				INSERT INTO @BLACK_LIST 
				SELECT DISTINCT PAY_LINK FROM DBO.GROUP_PAYS(@LINK_PAY) WHERE PAY_LINK <> @LINK_PAY AND EXISTS (SELECT LINK_PAY FROM @DECODE_BASE WHERE NUM_ORDER <= @NUM_ORDER AND LINK_PAY = PAY_LINK AND  LINK_BASE_PAY = @LINK_PAY) 
				
				/*ПОМЕЧАЕМ ТЕ УЗЛЫ, КОТОРЫЕ УЖЕ РАССМОТРЕЛИ НА ДАННОМ УРОВНЕ*/
				UPDATE @DECODE_BASE SET MARKER = 1 WHERE LINK = @LINK
	
			END
	
			/*ЛИСТЬЯ ПРЕВРАЩАЕМ В УЗЛЫ*/		
			INSERT INTO @DECODE_BASE (LINK_PAY, LINK_BASE_PAY, MARKER, NUM_ORDER)
			SELECT DISTINCT LINK_BASE_PAY, 0, 0, @NUM_ORDER FROM @DECODE_BASE 
				WHERE NUM_ORDER = @NUM_ORDER AND LINK_PAY NOT IN (SELECT LINK_PAY FROM @BLACK_LIST)
			
			/*СТОРОЖ НА СТРЕМЕ*/
			IF NOT EXISTS (SELECT * FROM @DECODE_BASE WHERE NUM_ORDER = @NUM_ORDER) OR @NUM_ORDER > 10 /*МАКСИМАЛЬНАЯ ВЛОЖЕННОСТЬ НА ЭТОМ УРОВНЕ*/
				SET @DOIT = 0
		END

		DECLARE @ETS TABLE (LINK INT, RAZR INT, KOEF numeric(6, 3), SUMMA NUMERIC(18,2))
		INSERT INTO @ETS (LINK, RAZR, KOEF, SUMMA)
		SELECT LINK, RAZR, KOEF, SUMMA FROM dbo.sa_ets_actual(@date)
		
		DECLARE @PKG TABLE (STAFF_HEAD INT, pkg_oklad NUMERIC(18,2))
		INSERT INTO @PKG (STAFF_HEAD, pkg_oklad)
		SELECT STAFF_HEAD, pkg_oklad FROM dbo.SA_PKG_POST_OKLAD_FN(@date)
		--select STAFF_HEAD = S.LINK_UP, pkg_oklad = o.OKLAD
		--from
		--	(	
		--		SELECT LINK_UP, MAX(DATE_BEGIN) AS DATE_BEGIN
		--		FROM dbo.STAFF
		--		WHERE DATE_BEGIN <= @date
		--		GROUP BY LINK_UP
		--	) S inner join STAFF ST on S.LINK_UP = ST.LINK_UP and S.DATE_BEGIN = ST.DATE_BEGIN
		--	inner join dbo.POST P on P.LINK = ST.POST_LINK
		--	inner join dbo.SA_PKG_POST_FN(@date) o on o.link = p.LINK_PKG		
		
				
		DECLARE @OMP TABLE (ITEM_LINK INT, PAY_LINK INT, VALUE NUMERIC(18,2), SUMMA NUMERIC(18,2), WAY_CALC TINYINT)

		INSERT INTO @OMP (ITEM_LINK, PAY_LINK, VALUE, SUMMA, WAY_CALC)
		SELECT 
			MP.ITEM_LINK, 
			MP.PAY_LINK,
			[VALUE]	=(case when wc.ETS <> 0 AND WC.ISPERCENT = 2 then ISNULL(koef,0)
							else ISNULL(MP.SUMMA,0)
						end),
			 
			[SUMMA]	= (case when wc.isPercent = 0 then MP.SUMMA 
							else (case when WC.CODE = 8 then ISNULL(pkg_oklad,0) * MP.SUMMA
									else (case when wc.ETS <> 0 AND WC.ISPERCENT = 2 then ISNULL(ets.summa,0) else NULL end)
							end)
						end),
			P.WAY_CALC		
		FROM
			dbo.ORDERS O WITH (NOLOCK)
			INNER JOIN dbo.ITEM_MOVE IM WITH (NOLOCK) ON IM.ORDER_LINK = O.LINK			
			INNER JOIN dbo.MONEY_PERIOD MP WITH (NOLOCK) ON MP.ITEM_LINK=IM.LINK
			INNER JOIN dbo.PAYS P WITH (NOLOCK) ON MP.PAY_LINK=P.LINK
			INNER JOIN dbo.WAY_CALC WC WITH (NOLOCK) ON P.WAY_CALC=WC.CODE AND WC.[TYPE]=1
			LEFT JOIN @PKG PKG on pkg.STAFF_HEAD = IM.STAFF_LINK
			LEFT JOIN @ETS ETS on ETS.link = P.link_ets and ets.razr = im.ETS_RAZR
		WHERE
			@date between @date and ISNULL(MP.DATE_END,@date)
			AND
			(	
				@ORDER_LINK = -1 and O.DEP_LINK = @DEP_LINK
				OR 
				IM.ORDER_LINK = @ORDER_LINK 
			)
			AND ISNULL(MP.date_end,@date) >= @date
	
		/*Определяются для каждого пункта приказа базовые суммы для расчета надбавок */
		Insert into @basis_sum
		/*Данные для расчета: постоянные оплаты суммами*/
		Select 
			ap.item_link, ap.PAY_LINK, summa_base= ISNULL(ap.SUMMA,0), perc= 0, ISNULL(ap.SUMMA,0)
		From 
			@OMP AP	
			INNER JOIN dbo.WAY_CALC W ON (AP.WAY_CALC = W.CODE AND W.[TYPE] = 1 AND W.const_pay_empl = 1 AND W.isPercent not in (1,4) )			
		WHERE
			ISNULL(ap.value,ap.SUMMA) > 0	

		/*Данные для расчета: Надбавки */
		declare @empl_add_pay table (item_link int, link_pay int, calc_perc numeric(18,2), isPercent tinyint )
		insert into @empl_add_pay 
		Select 
			ap.item_link, ap.PAY_LINK,  ISNULL([value],0),  W.isPercent
		from  
			@OMP AP	INNER JOIN dbo.WAY_CALC W ON (AP.WAY_CALC = W.CODE AND W.[TYPE] = 1 AND W.const_pay_empl = 1 AND W.isPercent in (1,4) AND W.CODE <> 16)			
		Where	
			ISNULL(ap.value,ap.SUMMA) > 0

		/*СПРАВОЧНИК - ОЧЕРЕДЬ РАСЧЕТА НАДБАВОК*/
		DECLARE @ORDER TABLE (ORD INT /*НОМЕР В ОЧЕРЕДИ*/, LEV /*УРОВЕНЬ ЗАВИСИМОСТИ*/ INT, LINK_PAY INT, MARKER INT)
		INSERT INTO @ORDER
		SELECT B.LINK, B.NUM_ORDER, B.LINK_PAY, 0 
		FROM 
			@DECODE_BASE AS B 
			INNER JOIN (SELECT LINK_PAY, MAX_LINK = MAX(B2.LINK) FROM  @DECODE_BASE B2 GROUP BY LINK_PAY) B2 ON B2.LINK_PAY = B.LINK_PAY AND B2.MAX_LINK = B.LINK
		WHERE 	B.LINK_BASE_PAY <> 0
			
		/*справочник базисов для начислений*/
		declare @basis table (link_pay int, link_base_pay int)
		insert into @basis
		Select distinct link_pay, link_base_pay
		from  @decode_base where link_base_pay <> 0 and marker = 0
		/*расчет сумм надбавок последовательно от листьев к корню*/

		While exists (Select * from @order where marker = 0)
		Begin
			/*определение очередной надбавки*/		
			Select @num_order = ISNULL(Max(ord),0) from @order where marker = 0 
			Select @link_pay = link_pay from @order where ord = @num_order
	
			/*расчт по ней суммы*/
			Insert into @basis_sum
			Select 
				bs.item_link, b.link_pay, 
				/*Для начисления по дополнительному табелю процентов нет*/
				summa_base = sum( bs.summa ),
				perc= ap.calc_perc, 
				summa = convert(numeric(18,2), sum(bs.summa) * ap.calc_perc / (case when ap.isPercent = 1 then 100 else 1 end) )
			from 	
				@empl_add_pay as ap
				inner join @basis as b on ap.link_pay = b.link_pay 
				inner join @basis_sum as bs on b.link_base_pay = bs.link_pay and ap.item_link = bs.item_link
			where  
				b.link_pay = @link_pay
			group by
				bs.item_link, b.link_pay, ap.calc_perc, ap.isPercent 
		
			/*Пометим расчитанную надбавку работника, чтобы к ней больше не возвращаться*/
			Update @order Set marker = 1 where ord = @num_order
		
		End
		
		delete from @basis_sum where summa = 0
	/*Расчет окончен*/		

END

return

end


GO


GRANT SELECT ON dbo.[sa_all_pays_order_money_date] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_DICT_PAYS_EMPL]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[SA_DICT_PAYS_EMPL]

GO

CREATE   FUNCTION DBO.SA_DICT_PAYS_EMPL(@DATE DATETIME = NULL, @LINK_EMPL INT = -1, @LINK_SOVM INT = -1, @BUFF_ID VARCHAR(20) = NULL) 
RETURNS @RES TABLE 
(
		LINK INT,
		LINK_EMPL INT,
		LINK_SOVM INT,
		LINK_PAYS INT,
		DATE_BEGIN DATETIME,
		DATE_END DATETIME,
		WAY_CALC TINYINT,
		BASE NUMERIC(15,4),
		VALUE NUMERIC(15,4),
		SUMMA  NUMERIC(15,4),
		LINK_KBK INT,
		NUM_STAKE NUMERIC(6,3),
		LINK_MP INT,
		LINK_ETS INT,
		LINK_PKG INT,
		NO_CALC TINYINT
)

BEGIN

	--@PE
	DECLARE @PE TABLE (LINK INT, LINK_EMPL INT, LINK_PAYS INT, LINK_SOVM INT, LINK_KBK INT, DATE_BEG DATETIME, DATE_END DATETIME, SUMMA NUMERIC(15,4), LINK_MP INT, NO_CALC TINYINT)
	INSERT INTO @PE (LINK, LINK_EMPL, LINK_PAYS, LINK_SOVM, LINK_KBK, DATE_BEG, DATE_END, SUMMA, LINK_MP, NO_CALC)
	SELECT LINK, LINK_EMPL, LINK_PAYS, LINK_SOVM, LINK_KBK, DATE_BEG, DATE_END, SUMMA, LINK_MP, NO_CALC FROM DBO.SA_DICT_PAYS_EMPL0(@LINK_EMPL,@LINK_SOVM,@BUFF_ID) PE 

	--@EI
	DECLARE @EI TABLE (EMPL_LINK INT, POST_LINK INT, ETS_RAZR TINYINT, LINK_KBK INT, NUM_STAKE NUMERIC(6,3))
	INSERT INTO @EI (EMPL_LINK, POST_LINK, ETS_RAZR, LINK_KBK, NUM_STAKE)
	SELECT EMPL_LINK, POST_LINK, ETS_RAZR, LINK_KBK, NUM_STAKE FROM DBO.SA_EMPLS_INFO(@DATE, @LINK_EMPL) EI
	
	--@sa_ets_actual
	DECLARE @sa_ets_actual TABLE (LINK INT, razr INT, SUMMA NUMERIC(18,2), MIN_VAL NUMERIC(18,2) )
	INSERT INTO @sa_ets_actual (LINK, razr, SUMMA, MIN_VAL)
	SELECT LINK, razr, SUMMA, MIN_VAL
	FROM dbo.sa_ets_actual(@date)

	--@SA_PKG_POST_FN
	--DECLARE @SA_PKG_POST_FN TABLE (LINK INT, OKLAD NUMERIC(18,2) )
	--INSERT INTO @SA_PKG_POST_FN (LINK, OKLAD)
	--SELECT LINK, OKLAD FROM dbo.SA_PKG_POST_FN(@date)

	----ОСНОВНЫЕ ДОЛЖНОСТИ
	INSERT INTO @RES
	SELECT 
		PE.LINK,
		PE.LINK_EMPL,
		PE.LINK_SOVM,
		PE.LINK_PAYS,
		DATE_BEGIN = PE.[DATE_BEG],
		PE.[DATE_END],
		P.WAY_CALC,
		[BASE]	= (CASE WHEN WC.CODE = 8 THEN ISNULL(PKG.OKLAD,0) 
					ELSE (CASE WHEN WC.ETS <> 0 AND WC.ISPERCENT = 2 THEN ISNULL(ETS.MIN_VAL,0)
						ELSE NULL
						END) 
					END),
		[VALUE]	= (CASE WHEN WC.ISPERCENT = 0 THEN ISNULL(PE.SUMMA,0)
						ELSE (CASE WHEN WC.CODE = 8 THEN ISNULL(PKG.OKLAD,0) * (CASE WHEN ISNULL(PKG.OKLAD,0) * ISNULL(PE.SUMMA,0) > 9999999 THEN -1 ELSE ISNULL(PE.SUMMA,0) END)
								ELSE (CASE WHEN WC.ETS <> 0 AND WC.ISPERCENT = 2 AND ISNULL(PE.SUMMA,0) > 0 THEN ISNULL(ETS.SUMMA,0) ELSE ISNULL(PE.SUMMA,0) END)
							END)		
					END),
		[SUMMA]	= (CASE WHEN WC.ISPERCENT = 0 THEN ISNULL(PE.SUMMA,0)
						ELSE (CASE WHEN WC.CODE = 8 THEN ISNULL(PKG.OKLAD,0) * (CASE WHEN ISNULL(PKG.OKLAD,0) * ISNULL(PE.SUMMA,0) > 9999999 THEN -1 ELSE ISNULL(PE.SUMMA,0) END)
								ELSE (CASE WHEN WC.ETS <> 0 AND WC.ISPERCENT = 2 AND ISNULL(PE.SUMMA,0) > 0 THEN ISNULL(ETS.SUMMA,0) ELSE ISNULL(PE.SUMMA,0) END)
							END)		
					END),
		LINK_KBK = ISNULL(PE.LINK_KBK,ISNULL(SOVM.LINK_SFIN,EI.LINK_KBK)),
		EI.NUM_STAKE,
		PE.LINK_MP,
		P.LINK_ETS,
		PKG.LINK_PKG,
		PE.NO_CALC
	FROM
		DBO.WAY_CALC WC
		INNER JOIN DBO.PAYS P ON P.WAY_CALC = WC.CODE
		INNER JOIN @PE PE ON P.LINK = PE.LINK_PAYS
		INNER JOIN DBO.EMPL E ON E.LINK = PE.LINK_EMPL
		--ОСНОВНАЯ ДОЛЖНОСТЬ
		LEFT JOIN @EI EI ON EI.EMPL_LINK = PE.LINK_EMPL
		--СОВМЕЩАЕМЫЕ ДОЛЖНОСТИ	
		LEFT JOIN DBO.STO_TARIF_EMPL SOVM ON SOVM.LINK_EMPL = PE.LINK_EMPL AND SOVM.LINK = PE.LINK_SOVM
		---------
		LEFT JOIN (

			SELECT LINK_POST AS LINK, LINK_PKG, PKG.OKLAD
			FROM
				dbo.[PKG_POST_DATE] PPD
				CROSS APPLY (SELECT MIN(DATE_BEGIN)-1 AS DATE_END FROM dbo.[PKG_POST_DATE] PPD2 WHERE PPD.LINK_POST = PPD2.LINK_POST AND PPD2.DATE_BEGIN > PPD.DATE_BEGIN) D
				CROSS APPLY (SELECT TOP 1 SUMMA AS OKLAD FROM dbo.PKG_OKLAD PO WITH (NOLOCK) WHERE PO.link_up = PPD.LINK_PKG and PO.date_begin <= @date order by PO.date_begin desc) PKG
			WHERE
				@date BETWEEN 	DATE_BEGIN AND ISNULL(D.DATE_END,@date)
			) AS PKG ON PKG.LINK = ISNULL(SOVM.LINK_POST,EI.POST_LINK)
		
		LEFT JOIN @sa_ets_actual ETS ON ETS.LINK = P.LINK_ETS AND ETS.RAZR = ISNULL(SOVM.LINK_ETS +ISNULL(SOVM.INC_ETS1_VALUE,0) +ISNULL(SOVM.INC_ETS2_VALUE,0) +ISNULL(SOVM.INC_ETS3_VALUE,0) , ISNULL(EI.ETS_RAZR,0)+ISNULL(E.INC_ETS1_VALUE,0) +ISNULL(E.INC_ETS2_VALUE,0) +ISNULL(E.INC_ETS3_VALUE,0))
		LEFT JOIN DBO.SAL_SFIN KBK ON KBK.LINK = ISNULL(SOVM.LINK_SFIN,PE.LINK_KBK)
	WHERE 
		WC.[TYPE] = 1
		AND
		P.[OBJECT] = 1
		AND
		(@LINK_EMPL = -1 OR PE.LINK_EMPL = @LINK_EMPL)
		AND
		(@LINK_SOVM = -1 OR ISNULL(PE.LINK_SOVM,0) = @LINK_SOVM)
	

RETURN 

END



GO


GRANT SELECT ON dbo.[SA_DICT_PAYS_EMPL] TO PUBLIC

GO

GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[FB_REST_FINANS]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[FB_REST_FINANS]

GO
CREATE FUNCTION dbo.FB_REST_FINANS(@varKSintFyear int, 
					@varKSdDate 		datetime, 
					@varKSintPer_num 	int, 
					@varKSintSumType 	numeric (5, 3), 
					@varKSFinLink 		int = 0, 
					@varKSFinObjCode 	char(100),
					@varKSintTypePer 	int = 1,
					@varKScTypeBudg 	Char(1) = '1',
					@varKSiIsRBS		INT	= 0)

-- за год @varKSintTypePer = 1 - за год,
--			   = 2 - по кварталам,
--			   = 3 - по месяцам
-- за период = + 10		  
RETURNS @varKSResTable TABLE
	(dep	[int] NULL,
	 dep_acc [int] NULL,
	 rbs_dep [int] NULL,
	 rbs_acc [int] NULL,
	 vkr	[int] NULL,
	 ekr	[int] NULL, 
	 dop_cl	[int] NULL, 
	 reg int null,
	 P1	[numeric](28, 2) NULL,
	 P2	[numeric](28, 2) NULL,
	 P3	[numeric](28, 2) NULL,
	 P4	[numeric](28, 2) NULL,
	 P5	[numeric](28, 2) NULL,
	 P6	[numeric](28, 2) NULL,
	 P7	[numeric](28, 2) NULL,
	 P8	[numeric](28, 2) NULL,
	 P9	[numeric](28, 2) NULL,
	 P10	[numeric](28, 2) NULL,
	 P11	[numeric](28, 2) NULL,
	 P12	[numeric](28, 2) NULL,
	 Y2	[numeric](28, 2) NULL,
	 Y3	[numeric](28, 2) NULL)

AS
BEGIN
DECLARE @varKSAccount int,
	@varKSFinObj int,
	@varKSdEndDate1 datetime,
	@varKSdEndDate2 datetime,
	@varKSdEndDate3 datetime,
	@varKSdEndDate4 datetime,
	@varKSdEndDate5 datetime,
	@varKSdEndDate6 datetime,
	@varKSdEndDate7 datetime,
	@varKSdEndDate8 datetime,
	@varKSdEndDate9 datetime,
	@varKSdEndDate10 datetime,
	@varKSdEndDate11 datetime,
	@varKSdEndDate12 datetime,
	@varKSdBegDate1 datetime,
	@varKSdBegDate2 datetime,
	@varKSdBegDate3 datetime,
	@varKSdBegDate4 datetime,
	@varKSdBegDate5 datetime,
	@varKSdBegDate6 datetime,
	@varKSdBegDate7 datetime,
	@varKSdBegDate8 datetime,
	@varKSdBegDate9 datetime,
	@varKSdBegDate10 datetime,
	@varKSdBegDate11 datetime,
	@varKSdBegDate12 datetime,
	@varKSdDateEndP	 datetime,
	@varKSdDateBegP	 datetime,
	@varKSiOwnDep	int,
	@iYear3			tinyint,
	@cSinth			char(3)
			

set @iYear3 = dbo.sa_get_option_by_code('FINANSE_3_YEAR')

DECLARE @varKSTempTable TABLE 
	(dep	[int] NULL,
	 dep_acc [int] NULL,
	 rbs_dep [int] NULL,
	 rbs_acc [int] NULL,
	 vkr	[int] NULL,
	 ekr	[int] NULL, 
	 dop_cl	[int] NULL, 
	 reg int null,
	 P1	[numeric](19, 2) NULL,
	 P2	[numeric](19, 2) NULL,
	 P3	[numeric](19, 2) NULL,
	 P4	[numeric](19, 2) NULL,
	 P5	[numeric](19, 2) NULL,
	 P6	[numeric](19, 2) NULL,
	 P7	[numeric](19, 2) NULL,
	 P8	[numeric](19, 2) NULL,
	 P9	[numeric](19, 2) NULL,
	 P10	[numeric](19, 2) NULL,
	 P11	[numeric](19, 2) NULL,
	 P12	[numeric](19, 2) NULL)

DECLARE @varKSTableOborot TABLE 
	(DATE_PROV	datetime null,
	 DEP	 	[int] NULL,
	 DEP_ACC 	[int] NULL,
	 RBS_DEP 	[int] NULL,
	 RBS_ACC 	[int] NULL,
	 INDATE 	datetime null,
	 VKR	[int] NULL,
	 EKR	[int] NULL, 
	 DOP_CL	[int] NULL, 
	REG int null,
	  SUMMA	[numeric](19, 2) NULL)


set @varKSiOwnDep = isnull (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())
IF @varKSiIsRBS < 1 or @varKSiIsRBS is null
	set @varKSiIsRBS = dbo.FB_GetDepIS_RBS(@varKSiOwnDep,default) 

set @varKSdBegDate1 = convert(datetime,convert(char(4),@varKSintFyear) + '0101')
SET @varKSdBegDate2 =  convert(datetime,convert(char(4),@varKSintFyear) + '0201')
SET @varKSdBegDate3 =  convert(datetime,convert(char(4),@varKSintFyear) + '0301')
SET @varKSdBegDate4 =  convert(datetime,convert(char(4),@varKSintFyear) + '0401')
SET @varKSdBegDate5 =  convert(datetime,convert(char(4),@varKSintFyear) + '0501')
SET @varKSdBegDate6 =  convert(datetime,convert(char(4),@varKSintFyear) + '0601')
SET @varKSdBegDate7 =  convert(datetime,convert(char(4),@varKSintFyear) + '0701')
SET @varKSdBegDate8 =  convert(datetime,convert(char(4),@varKSintFyear) + '0801')
SET @varKSdBegDate9 =  convert(datetime,convert(char(4),@varKSintFyear) + '0901')
SET @varKSdBegDate10 =  convert(datetime,convert(char(4),@varKSintFyear) + '1001')
SET @varKSdBegDate11 =  convert(datetime,convert(char(4),@varKSintFyear) + '1101')
SET @varKSdBegDate12 =  convert(datetime,convert(char(4),@varKSintFyear) + '1201')
SET @varKSdEndDate1 = @varKSdBegDate2 - 1
SET @varKSdEndDate2 = @varKSdBegDate3 - 1
SET @varKSdEndDate3 = @varKSdBegDate4 - 1
SET @varKSdEndDate4 = @varKSdBegDate5 - 1
SET @varKSdEndDate5 = @varKSdBegDate6 - 1
SET @varKSdEndDate6 = @varKSdBegDate7 - 1
SET @varKSdEndDate7 = @varKSdBegDate8 - 1
SET @varKSdEndDate8 = @varKSdBegDate9 - 1
SET @varKSdEndDate9 = @varKSdBegDate10 - 1
SET @varKSdEndDate10 = @varKSdBegDate11 - 1
SET @varKSdEndDate11 = @varKSdBegDate12 - 1
SET @varKSdEndDate12 = convert(datetime,convert(char(4),@varKSintFyear + 1)+'0101') - 1


select @varKSintPer_num  = (case @varKSintTypePer
				when 13 then @varKSintPer_num				
				when 12 then (case when @varKSintPer_num < 4 then 1
						when @varKSintPer_num < 7 then 4
						when @varKSintPer_num < 10 then 7
						else 10 end)
				when 11 then 1
				else 0 end)
						
/*
IF @varKSFinObjCode like '%_ASSIGN%'
	SELECT	@varKSintLimType = 0,
		@varKSintLimPer = max(FIN_SMETA_PER)
		FROM WorkMode
ELSE
	SELECT	@varKSintLimType = max(FIN_LIM_TYPE),
		@varKSintLimPer = max(FIN_LIM_PER)
		FROM WorkMode

IF @varKSintLimType = 0 or @varKSintLimPer = 0 or @varKSintPer_num = 0
*/

IF @varKSintTypePer < 12 or @varKSintPer_num = 0
begin
	set @varKSdDateEndP = convert(datetime,convert(char(4),@varKSintFyear+1) + '0101') - 1
	set @varKSdDateBegP= convert(datetime,convert(char(4),@varKSintFyear) + '0101')
end
else 
begin
	if @varKSintTypePer = 12
	BEGIN
		if @varKSintPer_num = 10
		begin
			set @varKSdDateEndP = convert(datetime,convert(char(4),@varKSintFyear+1) + '0101') - 1
			set @varKSdDateBegP = convert(datetime,(convert(char(4),@varKSintFyear) + '1001'))		
		end
		else
		begin
			if @varKSintPer_num = 7
				set @varKSdDateEndP = convert(datetime,convert(char(4),@varKSintFyear+1) + convert(char(2),@varKSintPer_num + 3) + '01') - 1
			else 
				set @varKSdDateEndP = convert(datetime,convert(char(4),@varKSintFyear+1) + '0' + convert(char(1),@varKSintPer_num + 3) + '01') - 1
			set @varKSdDateBegP = convert(datetime,(convert(char(4),@varKSintFyear) + '0' + convert(char(1),@varKSintPer_num) + '01'))
		end
	END 
	else 
	BEGIN
		if @varKSintPer_num = 12
			set @varKSdDateEndP = convert(datetime,convert(char(4),@varKSintFyear+1) + '0101') - 1
		else 		
			if @varKSintPer_num > 8
				set @varKSdDateEndP = convert(datetime,convert(char(4),@varKSintFyear+1) + convert(char(2),@varKSintPer_num + 1) + '01') - 1
			else 
				set @varKSdDateEndP = convert(datetime,convert(char(4),@varKSintFyear+1) + '0' + convert(char(1),@varKSintPer_num + 1) + '01') - 1
		if @varKSintPer_num < 10
			set @varKSdDateBegP = convert(datetime,(convert(char(4),@varKSintFyear) + '0' + convert(char(1),@varKSintPer_num) + '01'))
		else 		
			set @varKSdDateBegP = convert(datetime,(convert(char(4),@varKSintFyear) + convert(char(2),@varKSintPer_num) + '01'))

	END
end   

-- дата расчета не должна выходить за пределы периода
if @varKSdDate > @varKSdDateEndP
	set @varKSdDate = @varKSdDateEndP
/*
if  @varKSFinLink = 0 or @varKSFinLink is null
	select  @varKSFinObj = link from s_objects where code = @varKSFinObjCode
else */
	select  @varKSFinObj = object from g_prov where link = @varKSFinLink
if @varKSFinObjCode like '%_ASSIGN%'
	set @cSinth = '503'
else
    if @varKSFinObjCode = 'FB_SMETA_VNEB' or @varKSFinObjCode = 'FB_PLAN_FHD'
    	set @cSinth = '504'
	else
	    set @cSinth = '501'

if @varKSFinObjCode like '%_SVOD' 
	--IF @varKSiIsRBS = 2
		SELECT @varKSAccount = link 
		FROM s_accounts 
		WHERE cSinth = @cSinth and cAnalit = '12' and cSource = @varKScTypeBudg  
	--else 
	--	SELECT @varKSAccount = link 
	--	FROM s_accounts 
	--	WHERE cSinth = @cSinth and cAnalit = '11' and cSource = @varKScTypeBudg  
else 
	IF @varKSiIsRBS > 1
		SELECT @varKSAccount = link 
		FROM s_accounts 
		WHERE cSinth = @cSinth and cAnalit = '14' and cSource = @varKScTypeBudg  
	ELSE
		SELECT @varKSAccount = link 
		FROM s_accounts 
		WHERE cSinth = @cSinth and cAnalit = '13' and cSource = @varKScTypeBudg  

SET @varKSFinObjCode = REPLACE(@varKSFinObjCode,'_CC','') 

IF /*@varKSFinObjCode like '%_ASSIGN%' or */ @varKSFinObjCode LIKE '%_SMETA%' or @varKSFinObjCode = 'FB_RESULT_FINANS' or @varKSFinObjCode LIKE 'FB_PLAN%'
	
INSERT INTO @varKSResTable (dep, dep_acc, rbs_dep, rbs_acc, vkr, ekr,dop_cl, REG, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, Y2, Y3)
	SELECT DA.LINK_UP, FH.ACCOUNT, GP.dep, GP.ACC, F.vkr, F.ekr, F.dop_cl, F.REG, 
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 1) or (@varKSintTypePer = 13 and @varKSintPer_num = 1)) then sum(F.p1) * @varKSintSumType else 0 end) as p1,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 1) or (@varKSintTypePer = 13 and @varKSintPer_num = 2)) then sum(F.p2) * @varKSintSumType else 0 end) as p2,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 1) or (@varKSintTypePer = 13 and @varKSintPer_num = 3)) then sum(F.p3) * @varKSintSumType else 0 end) as p3,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 4) or (@varKSintTypePer = 13 and @varKSintPer_num = 4)) then sum(F.p4) * @varKSintSumType else 0 end) as p4,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 4) or (@varKSintTypePer = 13 and @varKSintPer_num = 5)) then sum(F.p5) * @varKSintSumType else 0 end) as p5,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 4) or (@varKSintTypePer = 13 and @varKSintPer_num = 6)) then sum(F.p6) * @varKSintSumType else 0 end) as p6,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 7) or (@varKSintTypePer = 13 and @varKSintPer_num = 7)) then sum(F.p7) * @varKSintSumType else 0 end) as p7,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 7) or (@varKSintTypePer = 13 and @varKSintPer_num = 8)) then sum(F.p8) * @varKSintSumType else 0 end) as p8,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 7) or (@varKSintTypePer = 13 and @varKSintPer_num = 9)) then sum(F.p9) * @varKSintSumType else 0 end) as p9,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 10) or (@varKSintTypePer = 13 and @varKSintPer_num = 10)) then sum(F.p10) * @varKSintSumType else 0 end) as p10,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 10) or (@varKSintTypePer = 13 and @varKSintPer_num = 11)) then sum(F.p11) * @varKSintSumType else 0 end) as p11,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 10) or (@varKSintTypePer = 13 and @varKSintPer_num = 12)) then sum(F.p12) * @varKSintSumType else 0 end) as p12,
	case @iYear3 when 1 then sum(F.Y2) * @varKSintSumType else 0 end as YS2,
	case @iYear3 when 1 then sum(F.Y3) * @varKSintSumType else 0 end as YS3
	from finanse F
	inner join G_Prov GP on GP.object in (select link from s_objects where REPLACE(Code,'_CC','') = @varKSFinObjCode)
				and GP.DATE_PROV is not null  
				and GP.DEP = @varKSiOwnDep
				and GP.DATE_PROV <= @varKSdDate
				and not GP.LINK = @varKSFinLink
				and F.link_up = GP.link
	inner join FINANSE_HEAD FH on FH.LINK = GP.LINK and FH.FYEAR = @varKSintFyear
	inner join department_accounts DA on da.link = FH.ACCOUNT
						and ((DA.type = 2 or DA.type = 3) and @varKScTypeBudg = '1'
						or (DA.type = 1 or DA.type = 4)  and @varKScTypeBudg = '2' or @varKScTypeBudg is null)
	group by DA.LINK_UP, FH.ACCOUNT, GP.dep, GP.ACC, vkr, ekr, dop_cl, REG
ELSE 
begin
	INSERT INTO @varKSTableOborot (DATE_PROV, DEP, DEP_ACC, RBS_DEP, RBS_ACC, INDATE, VKR, EKR,DOP_CL, REG, SUMMA)
	SELECT DATE_PROV,DEP, DEP_ACC, DEP_LINK, ACC_LINK, INDATE, KBK AS VKR, EKR, AP2 AS DOP_CL, AP3 as REG, isnull(k_summa,0)
	from FB_LimitOborotByPeriod(@varKSdDateBegP,@varKSdDateEndP, @varKSAccount)
	where not LINK_UP = @varKSFinLink
		and DEP_LINK = @varKSiOwnDep
		and not DATE_PROV > @varKSdDate
	IF @varKSiIsRBS > 1 and @varKSFinObjCode not like '%_SVOD' 
	begin
		SELECT @varKSAccount = link 
		FROM s_accounts 
		WHERE cSinth = @cSinth and cAnalit = '13' and cSource = @varKScTypeBudg  
	
		INSERT INTO @varKSTableOborot (DATE_PROV, DEP, DEP_ACC, RBS_DEP, RBS_ACC, INDATE, VKR, EKR,DOP_CL, REG, SUMMA)
		SELECT DATE_PROV,DEP, DEP_ACC, DEP_LINK, ACC_LINK, INDATE, KBK AS VKR, EKR, AP2 AS DOP_CL,  AP3 as REG, isnull(k_summa,0)
		from FB_LimitOborotByPeriod(@varKSdDateBegP,@varKSdDateEndP, @varKSAccount)
		where not LINK_UP = @varKSFinLink
			and DEP_LINK = @varKSiOwnDep
			and not DATE_PROV > @varKSdDate
	end	


	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, REG, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, REG, summa,0,0,0,0,0,0,0,0,0,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate1 and @varKSdEndDate1) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate1 and @varKSdEndDate1))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, REG, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, REG, 0, summa,0,0,0,0,0,0,0,0,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate2 and @varKSdEndDate2) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate2 and @varKSdEndDate2))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, REG, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, REG, 0,0,summa,0,0,0,0,0,0,0,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate3 and @varKSdEndDate3) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate3 and @varKSdEndDate3))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, REG, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, REG, 0,0,0,summa,0,0,0,0,0,0,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate4 and @varKSdEndDate4) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate4 and @varKSdEndDate4))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, REG, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL,REG, 0,0,0,0,summa,0,0,0,0,0,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate5 and @varKSdEndDate5) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate5 and @varKSdEndDate5))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, REG, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, REG, 0,0,0,0,0,summa,0,0,0,0,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate6 and @varKSdEndDate6) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate6 and @varKSdEndDate6))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, REG, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, REG, 0,0,0,0,0,0,summa,0,0,0,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate7 and @varKSdEndDate7) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate7 and @varKSdEndDate7))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, REG, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, REG, 0,0,0,0,0,0,0,summa,0,0,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate8 and @varKSdEndDate8) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate8 and @varKSdEndDate8))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, REG, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, REG, 0,0,0,0,0,0,0,0,summa,0,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate9 and @varKSdEndDate9) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate9 and @varKSdEndDate9))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, REG, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, REG, 0,0,0,0,0,0,0,0,0,summa,0,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate10 and @varKSdEndDate10) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate10 and @varKSdEndDate10))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, REG, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, REG, 0,0,0,0,0,0,0,0,0,0,summa,0
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate11 and @varKSdEndDate11) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate11 and @varKSdEndDate11))
	INSERT INTO @varKSTempTable (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR,DOP_CL, REG, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL,REG, 0,0,0,0,0,0,0,0,0,0,0,summa
	from @varKSTableOborot
	where ((not INDATE is null and INDATE between @varKSdBegDate12 and @varKSdEndDate12) 
		or (INDATE is null and DATE_PROV between @varKSdBegDate12 and @varKSdEndDate12))
					
	
		INSERT INTO @varKSresTable(dep, dep_acc, rbs_dep, rbs_acc, vkr, ekr, dop_cl, REG, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
			SELECT f.dep, F.DEP_ACC, f.rbs_dep, f.rbs_acc, F.vkr, F.ekr, F.dop_cl, F.REG,  
			sum(F.p1) * @varKSintSumType as p1,
			sum(F.p2) * @varKSintSumType as p2, 
			sum(F.p3) * @varKSintSumType as p3, 
			sum(F.p4) * @varKSintSumType as p4, 
			sum(F.p5) * @varKSintSumType as p5, 
			sum(F.p6) * @varKSintSumType as p6, 
			sum(F.p7) * @varKSintSumType as p7, 
			sum(F.p8) * @varKSintSumType as p8, 
			sum(F.p9) * @varKSintSumType as p9, 
			sum(F.p10) * @varKSintSumType as p10, 
			sum(F.p11) * @varKSintSumType as p11, 
			sum(F.p12) * @varKSintSumType as p12
			from @varKSTempTable F 
			group by dep, DEP_acc, rbs_dep, rbs_acc, vkr, ekr, dop_cl, REG
END 	

IF @varKSintTypePer = 1 or @varKSintTypePer > 10
	UPDATE @varKSResTable
		SET p1 = p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9 + p10 + p11 + p12,
		p2 = 0,	p3 = 0,	p4 = 0,	p5 = 0,	p6 = 0,	p7 = 0,	p8 = 0,	p9 = 0,	p10 = 0, p11 = 0, p12 = 0
IF @varKSintTypePer = 2
	UPDATE @varKSResTable
		SET p1 = p1 + p2 + p3, p2 = 0, p3 = 0,
		p4 = p4 + p5 + p6, p5 = 0, p6 = 0,
		p7 = p7 + p8 + p9, p8 = 0, p9 = 0,
		p10 = p10 + p11 + p12, p11 = 0, p12 = 0

delete from @varKSResTable where P1 = 0 and P2 = 0 and P3 = 0 and P4 = 0 and P5 = 0 and P6 = 0 and P7 = 0 and P8 = 0 and P9 = 0 and P10 = 0 and P11 = 0 and P12 = 0

RETURN

END

GO


GRANT SELECT ON dbo.[FB_REST_FINANS] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[sa_dict_wh_pays_empl]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[sa_dict_wh_pays_empl]

GO

CREATE FUNCTION dbo.sa_dict_wh_pays_empl (@date DATETIME = NULL, @link_empl INT = -1, @link_tar_empl INT = -1,@BUFF_ID VARCHAR(20) = NULL, @DEP_LINK INT = NULL) 
RETURNS @RES TABLE 
(
	dep_link INT,
	date_begin DATETIME,
	date_end DATETIME,
	link_wh INT,
	link_doc_wh INT,
	DOC_NAME VARCHAR(254),
	link_empl INT,
	link_tar_empl INT,
	fio VARCHAR(254),
	tab VARCHAR(10),
	POST_NAME VARCHAR(254),
	SUBDIV_NAME VARCHAR(254),
	num_stake NUMERIC(5,2),
	link_pay	INT,
	pays_code VARCHAR(10),
	pays_name VARCHAR(254),
	way_calc TINYINT,
	link_les INT,
	l_name VARCHAR(254),
	t TINYINT, 
	link_paral INT,
	p_name VARCHAR(254),
	link_clas INT,
	c_name VARCHAR(254),
	base NUMERIC(18,2),
	perc NUMERIC(8,4),
	summa NUMERIC(18,2),
	link_sfin INT,
	CODE_SFIN VARCHAR(20),
	link_ets INT,
	fact NUMERIC(18,2),
	norm NUMERIC(18,2),
	type_period TINYINT,
	weeks NUMERIC(18,4),
	link_pkg INT,
	OBJ_CODE VARCHAR(30),
	CODE_TYPE VARCHAR(10),
	NO_CALC TINYINT,
	M_STAVKA NUMERIC(18,2),
	FOT TINYINT
)

BEGIN

--@SA_EMPLS_W_FN
DECLARE @SA_EMPLS_W_FN TABLE 
	(LINK INT, LINK_EMPL INT, razr_base INT, inc_ets1_value INT, inc_ets2_value INT, inc_ets3_value INT, LINK_POST INT,
	fio VARCHAR(254), POST_NAME VARCHAR(254), SUBDIV_NAME VARCHAR(254), fot TINYINT, tab VARCHAR(10), num_stake NUMERIC(5,2),
	[koef] NUMERIC(7, 4), OBJ_CODE VARCHAR(30), CODE_TYPE VARCHAR(4)
	)
INSERT INTO @SA_EMPLS_W_FN (LINK, LINK_EMPL, razr_base, inc_ets1_value, inc_ets2_value, inc_ets3_value, LINK_POST,
	fio, POST_NAME, SUBDIV_NAME, fot, tab, num_stake,
	koef, OBJ_CODE, CODE_TYPE)
SELECT LINK, LINK_EMPL, razr_base, inc_ets1_value, inc_ets2_value, inc_ets3_value, LINK_POST,
	fio, POST_NAME, SUBDIV_NAME, fot, tab, num_stake,
	koef, OBJ_CODE, CODE_TYPE
FROM dbo.SA_EMPLS_W_FN(@link_empl,@date,@BUFF_ID, @DEP_LINK)
WHERE (@link_tar_empl = -1 OR ISNULL(LINK,0) = @link_tar_empl)

--@sa_ets_actual
DECLARE @sa_ets_actual TABLE (LINK INT, razr INT, SUMMA NUMERIC(18,2))
INSERT INTO @sa_ets_actual (LINK, razr, SUMMA)
SELECT LINK, razr, SUMMA
FROM dbo.sa_ets_actual(@date)

----@SA_PKG_POST_FN
--DECLARE @SA_PKG_POST_FN TABLE (LINK INT, OKLAD NUMERIC(18,2) )
--INSERT INTO @SA_PKG_POST_FN (LINK, OKLAD)
--SELECT LINK, OKLAD FROM dbo.SA_PKG_POST_FN(@date)

--@sto_paral_fn
DECLARE @sto_paral_fn TABLE (LINK INT, DEP_LINK INT, NAME VARCHAR(50), WEEK_HOURS NUMERIC(3,1) )
INSERT INTO @sto_paral_fn (LINK, DEP_LINK, NAME, WEEK_HOURS)
SELECT LINK, DEP_LINK, NAME, WEEK_HOURS FROM dbo.sto_paral_fn(@date)

--@sto_clas_fn
DECLARE @sto_clas_fn TABLE (LINK INT, DEP_LINK INT, NAME VARCHAR(50), WEEK_HOURS NUMERIC(3,1), KOEF NUMERIC(10,4) )
INSERT INTO @sto_clas_fn (LINK, DEP_LINK, NAME, WEEK_HOURS, KOEF)
SELECT LINK, DEP_LINK, NAME, WEEK_HOURS, KOEF FROM dbo.sto_clas_fn(@date)

--@STD
DECLARE @STD TABLE (link_pay INT, dep_link INT, type_period smallint, [hours] numeric(5, 2))
INSERT INTO @STD (link_pay, dep_link, type_period, [hours])
SELECT std.link_pay, std.dep_link, type_period, [hours] = max(std.[hours]) FROM dbo.STO_STD_HOURS as std group by std.link_pay, std.dep_link, std.type_period

--@CU
DECLARE @CU TABLE (LINK_CLAS INT, LINK_LES INT, CNT numeric(10, 4), [DATE] DATETIME, DEP_LINK INT)
INSERT INTO @CU (LINK_CLAS, LINK_LES, CNT, [DATE], DEP_LINK)
SELECT LINK_CLAS, LINK_LES, CNT, U.[DATE],U.DEP_LINK
FROM dbo.STO_CNT_STUD_LES U INNER JOIN dbo.STO_CNT_STUD_LES1 U1 ON U.LINK = U1.LINK_UP

DECLARE @O1 TINYINT, @O2 NUMERIC(5,2)
SET @O1 = dbo.SA_GET_OPTION_BY_CODE('STO_W_HOURS_DOC_OPT1')
SET @O2 = dbo.SA_GET_OPTION_BY_CODE('STO_W_HOURS_DOC_OPT2')

INSERT INTO @RES
(
	dep_link,
	date_begin,
	date_end,
	link_wh,
	link_doc_wh,
	DOC_NAME,
	link_empl,
	link_tar_empl,
	fio,
	tab,
	POST_NAME,
	SUBDIV_NAME,
	num_stake,
	link_pay,
	pays_code,
	pays_name,
	way_calc,
	link_les,
	l_name,
	t, 
	link_paral,
	p_name,
	link_clas,
	c_name,
	base,
	perc,
	summa,
	link_sfin,
	CODE_SFIN,
	link_ets,
	fact,
	norm,
	type_period,
	weeks,
	link_pkg,
	OBJ_CODE,
	CODE_TYPE,
	NO_CALC,
	M_STAVKA,
	FOT
)
Select
	whd.dep_link,
	date_begin = (CASE WHEN ISNULL(WH.DATE1,WHD.DATE_BEGIN) > WHD.DATE_BEGIN THEN WH.DATE1 ELSE WHD.DATE_BEGIN END), 
	date_end = (CASE WHEN ISNULL(WH.DATE2,WHD.DATE_END) < WHD.DATE_END THEN WH.DATE2 ELSE WHD.DATE_END END), 
	link_wh = wh.link,
	link_doc_wh = wh.link_up,
	DOC_NAME = LEFT('№' + LTRIM(RTRIM(whd.number)) + ' от ' + CONVERT(VARCHAR(10),whd.date_doc,104) + ' (' + LTRIM(RTRIM(whd.comment)) + ')', 254),
	te.link_empl,
	wh.link_tar_empl,
	te.fio,
	te.tab,
	te.POST_NAME,
	te.SUBDIV_NAME,
	te.num_stake,
	wh.link_pay	,
	pays_code = pays.[code],
	pays_name = pays.[name],
	way_calc = pays.way_calc,
	wh.link_les,
	l_name = l.[name],
	t, 
	wh.link_paral,
	p_name = P.[name],
	wh.link_clas,
	c_name = c.name, 
	base = convert(numeric(18,2), (case ISNULL(te.fot,2) WHEN 2 then ISNULL(ETS.SUMMA,0) WHEN 1 THEN ISNULL(pkg.oklad,0) * ISNULL(te.koef,0) WHEN 3 THEN SU.SUMMA WHEN 4 THEN WH.M_STAVKA END)),
	perc = (case when ISNULL([percent],0) = 0 then 100 else [percent] end),
	summa = convert(numeric(18,2), 
			/*нагрузка*/wh.WEEK_HOURS 
			* (case when t = 4 and ISNULL(std.hours,0) > 0
					then 1 /*Для случая, когда нагрузка задана на месяц*/
				else /*Кол-во недель в месяце*/
					CASE WHEN @O1 = 1 THEN convert(numeric(18,5), (ROUND(datediff(day, whd.date_begin, whd.date_end) / 7,0))) / (ROUND(datediff(month, whd.date_begin, whd.date_end),0) +1 ) ELSE @O2 END
			end)
		* 
		/*Часовая ставка*/	
		 convert(numeric(18,5), 	
			/*Нормочасы в месяц*/
			(case when t = 3 then 0
			else 
				(case ISNULL(te.fot,2) WHEN 2 then ISNULL(ETS.SUMMA,0) WHEN 1 THEN ISNULL(pkg.oklad,0) * ISNULL(te.koef,0) WHEN 3 THEN SU.SUMMA WHEN 4 THEN WH.M_STAVKA END)
				/
				(CASE WHEN ISNULL(te.fot,2) IN (1,2,4) THEN
					(CASE WHEN  
						(case when t = 4 and ISNULL(std.hours,0) > 0
							then 
								ISNULL(std.hours,0)
							else 
								(case t when 1 then ISNULL(p.WEEK_HOURS,0) when 2 then ISNULL(c.WEEK_HOURS,0) end)
								* CASE WHEN @O1 = 1 THEN convert(numeric(18,5), (ROUND(datediff(day, whd.date_begin, whd.date_end) / 7,0))) / (ROUND(datediff(month, whd.date_begin, whd.date_end),0) +1 ) ELSE @O2 END
						end) <> 0
					THEN
						(case when t = 4 and ISNULL(std.hours,0) > 0
							then 
								ISNULL(std.hours,0)
							else 
								(case t when 1 then ISNULL(p.WEEK_HOURS,0) when 2 then ISNULL(c.WEEK_HOURS,0) end)
								* CASE WHEN @O1 = 1 THEN convert(numeric(18,5), (ROUND(datediff(day, whd.date_begin, whd.date_end) / 7,0))) / (ROUND(datediff(month, whd.date_begin, whd.date_end),0) +1 ) ELSE @O2 END
						end)
					ELSE 
						9999999999999.999
					END)
				ELSE
					1	
				END)
				*
				(CASE WHEN ISNULL(te.fot,2) = 3 THEN
					CU.CNT * C.KOEF
				ELSE 1
				END
				)	
			end) * (case when ISNULL([percent],0) = 0 then 1 else [percent] / 100 end)) 
		+ (case when t = 3 AND ISNULL(te.fot,2) IN (1,2,4) then 
			(case ISNULL(te.fot,2) WHEN 2 then ISNULL(ETS.SUMMA,0) WHEN 1 THEN ISNULL(pkg.oklad,0) * ISNULL(te.koef,0) WHEN 3 THEN WH.M_STAVKA END) else 0 end) 
			* (case when ISNULL([percent],0) = 0 then 1 else [percent] / 100 end)
			),
	link_sfin = wh.LINK_KBK,
	CODE_SFIN = KBK.[CODE],
	pays.link_ets,
	fact = wh.WEEK_HOURS,
	norm = 
				(CASE WHEN  
					(case when t = 4 and ISNULL(std.hours,0) > 0
						then 
							ISNULL(std.hours,0)
						else 
							(case t when 1 then ISNULL(p.WEEK_HOURS,0) when 2 then ISNULL(c.WEEK_HOURS,0) end)
					end) <> 0
				THEN
					(case when t = 4 and ISNULL(std.hours,0) > 0
						then 
							ISNULL(std.hours,0)
						else 
							(case t when 1 then ISNULL(p.WEEK_HOURS,0) when 2 then ISNULL(c.WEEK_HOURS,0) end)
					end)
				ELSE 
					NULL
				END),
	type_period,
	weeks = CASE WHEN @O1 = 1 THEN convert(numeric(18,5), (ROUND(datediff(day, whd.date_begin, whd.date_end) / 7,0))) / (ROUND(datediff(month, whd.date_begin, whd.date_end),0) +1 ) ELSE @O2 END,
	link_pkg,
	TE.OBJ_CODE,
	TE.CODE_TYPE,
	NO_CALC = ISNULL(WH.NO_CALC,0),
	wh.M_STAVKA,
	te.FOT
from 
	dbo.STO_W_HOURS_DOC  as whd 
	INNER JOIN dbo.STO_WEEK_HOURS as wh ON whd.link = wh.link_up
	inner join @SA_EMPLS_W_FN as te on ISNULL(wh.link_tar_empl,0) = te.link and wh.link_empl = te.LINK_EMPL
	inner join dbo.pays on wh.link_pay = pays.link
	inner join dbo.USER_DEP UD ON 1=1
	inner join dbo.SALARY_CALC_PERIOD UI on 1=1
	left join @sa_ets_actual AS ets on ets.link = pays.link_ets and ets.razr = (ISNULL(TE.razr_base,0) +ISNULL(inc_ets1_value,0) +ISNULL(inc_ets2_value,0) + ISNULL(inc_ets3_value,0))
	---------
	LEFT JOIN (

		SELECT LINK_POST AS LINK, LINK_PKG, PKG.OKLAD
		FROM
			dbo.[PKG_POST_DATE] PPD
			CROSS APPLY (SELECT MIN(DATE_BEGIN)-1 AS DATE_END FROM dbo.[PKG_POST_DATE] PPD2 WHERE PPD.LINK_POST = PPD2.LINK_POST AND PPD2.DATE_BEGIN > PPD.DATE_BEGIN) D
			CROSS APPLY (SELECT TOP 1 SUMMA AS OKLAD FROM dbo.PKG_OKLAD PO WITH (NOLOCK) WHERE PO.link_up = PPD.LINK_PKG and PO.date_begin <= @date order by PO.date_begin desc) PKG
		WHERE
			@date BETWEEN 	DATE_BEGIN AND ISNULL(D.DATE_END,@date)
		) AS PKG ON PKG.LINK = te.link_post
	
	left join @sto_paral_fn as p on wh.link_paral = p.link and p.dep_link = ISNULL(@DEP_LINK,UD.DEP_LINK)
	left join @sto_clas_fn as c on wh.link_clas = c.link and c.dep_link = ISNULL(@DEP_LINK,UD.DEP_LINK)
	left join dbo.STO_LESSON as l on wh.link_les = l.link
	left join dbo.SAL_SFIN KBK ON KBK.LINK = wh.LINK_KBK
	left join @STD std on std.link_pay = wh.link_pay and std.dep_link = ISNULL(@DEP_LINK,UD.DEP_LINK)
	LEFT JOIN dbo.STO_STUCHAS SU ON SU.DEP_LINK = ISNULL(@DEP_LINK,UD.DEP_LINK) AND ISNULL(@date,UI.SC_DATE) BETWEEN SU.DATE_BEGIN AND SU.DATE_END2
	LEFT JOIN @CU CU ON 
				CU.DEP_LINK = ISNULL(@DEP_LINK,UD.DEP_LINK)
			AND CU.LINK_CLAS = wh.link_clas 
			AND CU.LINK_LES = wh.link_les 
			AND YEAR(CU.[DATE]) = YEAR(ISNULL(@date,UI.SC_DATE))
			AND MONTH(CU.[DATE]) = MONTH(ISNULL(@date,UI.SC_DATE))

RETURN 

END



GO


GRANT SELECT ON dbo.[sa_dict_wh_pays_empl] TO PUBLIC

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[sa_to_all_pays_all_tar_empls]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[sa_to_all_pays_all_tar_empls]

GO

CREATE function [dbo].[sa_to_all_pays_all_tar_empls](@link_empl int = 0, @date datetime = null, @buff_id varchar(20) = null) 
/*	
	Тарификация. Игнатьев А.Н. 2005-08-25
	Функция выводит все начисления всех тарифицируемых работников по состоянию на расчетный период:
	1) Оплата за пед. нагрузки
	2) Надбавки за предмет (накручиваются только на оплату пед. нагрузок)
	3) Другие надбавки на любые виды оплат тарифицируемого работника (уровень вложенности ограничен 30 во избежании зацикливания)
*/
returns @basis_sum table (date_begin datetime, date_end datetime, link_empl int, link_tar_empl int, link_paral int, link_les int, link_pay int, summa_base numeric(18,2), perc numeric(18,2), summa numeric(18,2), wdays numeric(18,2), ndays numeric(18,2),LINK_KBK INT, LINK INT, OBJ_CODE VARCHAR(254), PERC_OK NUMERIC(18,2), t tinyint )

Begin

	/*
	Функция раскладывает все группы надбавок  в виде деревьев по каждому сотруднику.
	Затем, для каждого сотрудника строятся маршруты - последовательности расчета каждой надбавки - очереди.
	Проверяется и ликвидируется возможность зацикливания. 
	На всякий случай введен сторож, если вдруг зацикливание все же случилось.
	Стророж накладывает ограничение на вложенность видов оплат. Максимальный уровень вложенности - 30. (на обум)
	*/

	declare @SCPeriod datetime
	Select @SCPeriod = (case when @date is null then dbo.DateEndOfMonth(dbo.salarycalcperiod()) else @date end)

	declare @BeginMonth datetime, @EndMonth datetime
	Set @BeginMonth = dbo.DateBeginOfMonth(@SCPeriod)
	Set @EndMonth = dbo.DateEndOfMonth(@SCPeriod)

	declare @DEP_LINK int
	SET @DEP_LINK = (SELECT TOP 1 DEP_LINK FROM dbo.USER_DEP)

	--Если тарификация не используется, то дальше пропустить
	IF  EXISTS (SELECT * FROM dbo.STO_TARIF_EMPL WHERE (YEAR(@SCPeriod)) * 100 + MONTH(@SCPeriod) BETWEEN (YEAR(date_begin) * 100 + MONTH(date_begin)) AND (YEAR(isnull(date_end,@SCPeriod)) * 100 + MONTH(isnull(date_end,@SCPeriod)))
				AND dep_link = @DEP_LINK AND (@link_empl = 0 OR @link_empl = link_empl)  )
	BEGIN

--	IF dbo.sa_get_option_by_code('DICT_PAYS_EMPL_OPT2') = 1 and EXISTS( SELECT TOP 1 link_empl FROM dbo.CONST_PAYS_TAR_EMPLS where link_dep = @DEP_LINK and YEAR(date_begin) = YEAR(@SCPeriod) AND MONTH(date_begin) = MONTH(@SCPeriod))
--	BEGIN
--		INSERT INTO @basis_sum (date_begin, date_end, link_empl, link_tar_empl, link_paral, link_les, link_pay, summa_base, perc, summa, wdays, ndays, LINK_KBK)
--		SELECT date_begin, date_end, link_empl, link_tar_empl, link_paral, link_les, link_pay, summa_base, perc, summa, wdays, ndays, LINK_KBK from dbo.CONST_PAYS_TAR_EMPLS 
--		where link_dep = @DEP_LINK and YEAR(date_begin) = YEAR(@SCPeriod) AND MONTH(date_begin) = MONTH(@SCPeriod) AND (link_empl = @link_empl OR @link_empl = 0)
--	END
--	ELSE
--	BEGIN

		--Для кого считать
		declare @tar_empls table (link int, link_empl int, RAZR int, date_begin datetime, date_end datetime, link_kbk int, link_post int, fot tinyint, koef numeric(7,4), num_stake numeric(5,2))
		insert into @tar_empls (link, link_empl, RAZR, date_begin, date_end, link_kbk, link_post, fot, koef, num_stake)
		Select distinct link, link_empl, RAZR, date_begin, date_end, link_kbk, link_post, fot, koef, num_stake from dbo.sto_tar_empl_fast_fn(@link_empl,@date, @DEP_LINK) where 
			( (@buff_id is null and @link_empl = 0)
				OR link_empl = @link_empl 
				OR (@buff_id is not null and link_empl in (select link from dbo.buffer where id = @buff_id) )
			)
		order by
			link_empl

		----Временная таблица для быстрого определения нормы времени за заданный отрезок дней в пределах расчетного месяца
		DECLARE @NORM_DH TABLE (LINK_EMPL INT, PERIOD DATETIME, HOURS NUMERIC(10,2))
		INSERT INTO @NORM_DH (LINK_EMPL, PERIOD, HOURS)
		SELECT  
			E.LINK, DATEADD(d,[DAY],PERIOD)-1, HOURS * isnull(t.num_stake,0)
		FROM    
			@tar_empls T inner join dbo.EMPL E on T.link_empl = E.link
			INNER JOIN GRAPHICS G ON G.GRAPH_LINK = E.GRAPH_LINK INNER JOIN dbo.GRAPHIC_DAYS GD ON GD.LINK_UP=G.LINK 
		WHERE 
			E.DEP_LINK = @DEP_LINK AND GD.HOURS<>0 AND DATEADD(d,[DAY],PERIOD)-1 BETWEEN @BeginMonth AND @EndMonth
		UNION --График по умолчанию для вакансии
		SELECT  0 as LINK,DATEADD(d,[DAY],PERIOD)-1, HOURS
		FROM    GRAPHICS G INNER JOIN dbo.GRAPHIC_DAYS GD ON GD.LINK_UP=G.LINK 
		WHERE   GD.HOURS<>0 AND DATEADD(d,[DAY],PERIOD)-1 BETWEEN @BeginMonth AND @EndMonth
				AND G.GRAPH_LINK = (Select TOP 1 GR_LINK from KADRY_OPTIONS_GRAPHIC)
				AND @buff_id is null and @link_empl = 0
		ORDER BY 
				E.LINK

		/*Начисления по дополнительным табелям*/
		declare @empl_with_add_tabels table (LINK_EMPL int, LINK_PAYS int, summa numeric(18,2))
		insert into @empl_with_add_tabels
		Select distinct ap.LINK_EMPL, LINK_PAYS, 0 from dbo.sa_doptab_empls(@SCPeriod) ap inner join @tar_empls e1 on ap.link_empl = e1.link_empl

		/*Временная таблица с нагрузками */
		DECLARE @STO_W_HOURS_TABLE TABLE (LINK INT, LINK_UP INT, LINK_EMPL INT, LINK_TAR_EMPL INT, LINK_PARAL INT, LINK_LES INT, LINK_PAY INT, SUMMA NUMERIC(18,2), LINK_KBK INT, T TINYINT, DATE_BEGIN DATETIME, DATE_END DATETIME, PERC NUMERIC(18,2))
		INSERT INTO @STO_W_HOURS_TABLE (LINK, LINK_UP, LINK_EMPL, LINK_TAR_EMPL, LINK_PARAL, LINK_LES, LINK_PAY, SUMMA, LINK_KBK, T, DATE_BEGIN, DATE_END, PERC)
		Select w.link_wh, w.link_doc_wh, w.LINK_EMPL, w.LINK_TAR_EMPL, w.LINK_PARAL, w.LINK_LES, w.LINK_PAY, w.SUMMA, w.link_sfin, w.T, w.DATE_BEGIN, w.DATE_END, w.PERC
		from 
			dbo.sa_dict_wh_pays_empl(@SCPeriod,@link_empl,0,default,default) w
			inner join @tar_empls e1 on e1.link = w.link_tar_empl
		where (Year(@SCPeriod) * 100 + Month(@SCPeriod))   between (Year(w.date_begin) * 100 + Month(w.date_begin)) and (Year(isnull(w.date_end,@SCPeriod)) * 100 + Month(isnull(w.date_end,@SCPeriod)))  
		ORDER BY LINK_TAR_EMPL

		declare @decode_base table ( link int identity(1,1) not null,	
						link_pay int, -- надбавки
						link_base_pay int, -- базовый вид оплаты
						marker tinyint,
						num_order tinyint )

		-- Список надбавок: рабочая таблица для раскодирования групп. Содержит деревья по каждому сотруднику.
		insert into @decode_base (link_pay, link_base_pay, marker, num_order)
		Select distinct link_pay, 0, 0, 0 from dbo.STO_ADD_PAYMENT AS AP inner join @tar_empls te on ap.link_tar_empl = te.link
		union
		Select DISTINCT LINK_PAYS, 0, 0, 0 from @empl_with_add_tabels E
	
		declare @link int 
		declare @link_pay int
		declare @num_order int
		declare @doit int
	
		/*Черный список видов оплат, которые зацыклены. Для прекращения их рассмотрения при построении дерева.*/
		declare @black_list table (link_pay int)
		
		Set @num_order = 0
		Set @doit = 1
	
		
		declare @pays_tar_empls table (link_pay int)
	
		Insert into @pays_tar_empls 
		Select distinct link_pay From	dbo.STO_WEEK_HOURS	/*Данные для расчета: оплата за нагрузки*/
		Union	
		Select distinct link_pay From 	dbo.STO_LESSON_PAYS	/*Данные для расчета: Надбавки тарифного работника от предмета */
		Union	
		Select distinct link_pay From 	dbo.STO_ADD_PAYMENT	/*Надбавки тар. работника*/
	
	
		while  @doit = 1 
		BEGIN
			Set @num_order = @num_order + 1
			--Проверим очередное начисление (лист дерева) на наличие у него базовых начислений (своих листьев)
			while exists (Select * from @decode_base where marker = 0 and link_base_pay = 0)
			begin
				/*находим очередной лист и рассматриваемп его как узел*/	
				Select @link = isnull(min(link),0) from @decode_base where marker = 0 and link_base_pay = 0 
				Select @link_pay = link_pay from @decode_base where link = @link
				
				/*Для очередного начисления (узла) определяются свои листья*/
				insert into @decode_base (link_pay, link_base_pay, marker, num_order)
				Select distinct @link_pay, PAY_LINK, 0, @num_order from dbo.group_pays(@link_pay) where PAY_LINK <> @link_pay and not exists (Select link_pay from @decode_base where num_order <= @num_order and link_pay = PAY_LINK and  link_base_pay = @link_pay) 
					and PAY_LINK in (Select link_pay from @pays_tar_empls)
	
				/*В черный списко запишем виновника зацикливания, чтобы дальше с ним не иметь дел*/
				insert into @black_list 
				Select distinct PAY_LINK from dbo.group_pays(@link_pay) where PAY_LINK <> @link_pay and exists (Select link_pay from @decode_base where num_order <= @num_order and link_pay = PAY_LINK and  link_base_pay = @link_pay) 
				
				/*Помечаем те узлы, которые уже рассмотрели на данном уровне*/
				update @decode_base Set marker = 1 where link = @link
	
			end
			
			/*Листья превращаем в узлы*/		
			insert into @decode_base (link_pay, link_base_pay, marker, num_order)
			Select distinct link_base_pay, 0, 0, @num_order from @decode_base 
				where num_order = @num_order and link_pay not in (Select link_pay from @black_list)
			
			/*Сторож на стреме*/
			if not exists (Select * from @decode_base where num_order = @num_order) or @num_order > 30 /*Максимальная вложенность на этом уровне*/
				Set @doit = 0
		
		END

		-- Надбавка тар. сотрудника
		declare @ADD_PAYS table (link int, link_empl int, link_tar_empl int, link_pay int, date_begin datetime, date_end  datetime, mode_p tinyint, [percent] numeric(18,2),  ets_only tinyint, [summa] numeric(18,2), calc_perc numeric(18,2), link_ets int, LINK_KBK int)
--		insert into @ADD_PAYS (link, link_empl, link_tar_empl, link_pay, date_begin, date_end, mode_p, [percent],  ets_only, [summa], calc_perc, link_ets, LINK_KBK)
--		select
--			ap.link, ap.link_empl, ap.link_tar_empl, ap.link_pay, ap.date_begin, ap.date_end, ap.mode_p, ap.[percent], ap.ets_only, ap.[summa], ap.calc_perc, ap.link_ets, ap.LINK_KBK
--		from 
--			dbo.STO_ADD_PAYS_FN(@link_empl,@date,default,default,default) ap inner join @tar_empls e1 on e1.link = ap.link_tar_empl
--		where
--			(Year(@SCPeriod) * 100 + Month(@SCPeriod))   between (Year(ap.date_begin) * 100 + Month(ap.date_begin)) and (Year(isnull(ap.date_end,@SCPeriod)) * 100 + Month(isnull(ap.date_end,@SCPeriod)))  
--		order by
--			link_tar_empl

		declare @MinRot numeric(18,2)
		set @MinRot = dbo.Minrot1(@SCPeriod)

		/*Определяются для каждого сотрудника Базовые суммы для расчета надбавок */
		--Declare @basis_sum table (date_begin datetime, date_end datetime, link_empl int, link_tar_empl int, link_les int, link_pay int, summa numeric(18,2) )
		Insert into @basis_sum
		/*Данные для расчета: оплата за нагрузки*/
		Select (case when (case when te.date_begin > wht.date_begin then te.date_begin else wht.date_begin end) > @BeginMonth then (case when te.date_begin > wht.date_begin then te.date_begin else wht.date_begin end) else @BeginMonth end),
			(case when (case when isnull(te.date_end,@EndMonth) < isnull(wht.date_end, @EndMonth) then isnull(te.date_end,@EndMonth) else isnull(wht.date_end, @EndMonth) end) < @EndMonth then (case when isnull(te.date_end,@EndMonth) < isnull(wht.date_end, @EndMonth) then isnull(te.date_end,@EndMonth) else isnull(wht.date_end, @EndMonth) end) else @EndMonth end),
			wht.link_empl, 
			wht.link_tar_empl, 
			wht.link_paral, 		
			wht.link_les, 
			wht.link_pay, 
			summa_base= coalesce(wht.summa,0) * coalesce(te.num_stake,0), 
			perc= 0, 
			Summa = 
			(Case when isnull(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(wht.link_empl,MONTH(@SCPeriod),YEAR(@SCPeriod))),9999) > 0 
				then wht.SUMMA 
					* CASE WHEN isnull(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(wht.link_empl,MONTH(@SCPeriod),YEAR(@SCPeriod))),9999) <> 0 THEN 
							1.000000 / isnull(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(wht.link_empl,MONTH(@SCPeriod),YEAR(@SCPeriod))),9999)
							ELSE 0 END
					* (SELECT COUNT(DISTINCT PERIOD) FROM @NORM_DH ND WHERE ND.LINK_EMPL = wht.link_empl AND ND.PERIOD BETWEEN
						(case when (case when te.date_begin > wht.date_begin then te.date_begin else wht.date_begin end) > @BeginMonth then (case when te.date_begin > wht.date_begin then te.date_begin else wht.date_begin end) else @BeginMonth end)
						AND (case when (case when isnull(te.date_end,@EndMonth) < isnull(wht.date_end, @EndMonth) then isnull(te.date_end,@EndMonth) else isnull(wht.date_end, @EndMonth) end) < @EndMonth then (case when isnull(te.date_end,@EndMonth) < isnull(wht.date_end, @EndMonth) then isnull(te.date_end,@EndMonth) else isnull(wht.date_end, @EndMonth) end) else @EndMonth end)
						)	
				else 
					(CASE WHEN isnull(wht.link_empl,0) = 0 THEN wht.SUMMA ELSE 0 END)
			end) * coalesce(te.num_stake,0),
			wdays = (SELECT COUNT(DISTINCT PERIOD) FROM @NORM_DH ND WHERE ND.LINK_EMPL = wht.link_empl AND ND.PERIOD BETWEEN
						(case when (case when te.date_begin > wht.date_begin then te.date_begin else wht.date_begin end) > @BeginMonth then (case when te.date_begin > wht.date_begin then te.date_begin else wht.date_begin end) else @BeginMonth end)
						AND (case when (case when isnull(te.date_end,@EndMonth) < isnull(wht.date_end, @EndMonth) then isnull(te.date_end,@EndMonth) else isnull(wht.date_end, @EndMonth) end) < @EndMonth then (case when isnull(te.date_end,@EndMonth) < isnull(wht.date_end, @EndMonth) then isnull(te.date_end,@EndMonth) else isnull(wht.date_end, @EndMonth) end) else @EndMonth end)
						),
			ndays = isnull(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(wht.link_empl,MONTH(@SCPeriod),YEAR(@SCPeriod))),9999),
			wht.LINK_KBK,
			wht.LINK, 'STO_W_HOURS_TABLE',
			PERC,
			wht.t -- тип нагрузки
		From
			@STO_W_HOURS_TABLE as wht inner join @tar_empls te on wht.link_tar_empl = te.link
		Where
			(Year(@SCPeriod) * 100 + Month(@SCPeriod))   between (Year((case when te.date_begin > wht.date_begin then te.date_begin else wht.date_begin end)) * 100 + Month((case when te.date_begin > wht.date_begin then te.date_begin else wht.date_begin end))) and (Year(isnull(wht.date_end,@SCPeriod)) * 100 + Month(isnull(wht.date_end,@SCPeriod)))  
		
		Union All
		/*Данные для расчета: Надбавки тарифного работника от предмета */
		Select (case when (case when te.date_begin > wht.date_begin then te.date_begin else wht.date_begin end) > @BeginMonth then wht.date_begin else @BeginMonth end),
			(case when (case when isnull(te.date_end,@EndMonth) < isnull(wht.date_end, @EndMonth) then isnull(te.date_end,@EndMonth) else isnull(wht.date_end, @EndMonth) end) < @EndMonth then (case when isnull(te.date_end,@EndMonth) < isnull(wht.date_end, @EndMonth) then isnull(te.date_end,@EndMonth) else isnull(wht.date_end, @EndMonth) end) else @EndMonth end),
			wht.link_empl, 
			wht.link_tar_empl, 
			wht.link_paral, 
			wht.link_les, 
			link_pay= lp.link_pay, 
			summa_base= (case when lp.base = 1 then wht.summa else @MinRot end) *  coalesce(te.num_stake,0), 
			perc= LP.value, 
			Summa = 
			(Case when isnull(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(wht.link_empl,MONTH(@SCPeriod),YEAR(@SCPeriod))),9999) > 0 
				then CONVERT(NUMERIC(9,2),((case when lp.base = 1 then wht.summa else @MinRot end) * LP.value / 100)) 
					* CASE WHEN isnull(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(wht.link_empl,MONTH(@SCPeriod),YEAR(@SCPeriod))),9999) <> 0
						THEN 1.000000 / isnull(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(wht.link_empl,MONTH(@SCPeriod),YEAR(@SCPeriod))),9999)
						ELSE 0
					END
					* (SELECT COUNT(DISTINCT PERIOD) FROM @NORM_DH ND WHERE ND.LINK_EMPL = wht.link_empl AND ND.PERIOD BETWEEN
						(case when (case when te.date_begin > wht.date_begin then te.date_begin else wht.date_begin end) > @BeginMonth then (case when te.date_begin > wht.date_begin then te.date_begin else wht.date_begin end) else @BeginMonth end)
						AND (case when (case when isnull(te.date_end,@EndMonth) < isnull(wht.date_end, @EndMonth) then isnull(te.date_end,@EndMonth) else isnull(wht.date_end, @EndMonth) end) < @EndMonth then (case when isnull(te.date_end,@EndMonth) < isnull(wht.date_end, @EndMonth) then isnull(te.date_end,@EndMonth) else isnull(wht.date_end, @EndMonth) end) else @EndMonth end)
						)
				else 
					(CASE WHEN wht.link_empl = 0 THEN CONVERT(NUMERIC(9,2),((case when lp.base = 1 then wht.summa else @MinRot end) * LP.value / 100)) ELSE 0 END)
			end)  * coalesce(te.num_stake,0),
			wdays = (SELECT COUNT(DISTINCT PERIOD) FROM @NORM_DH ND WHERE ND.LINK_EMPL = wht.link_empl AND ND.PERIOD BETWEEN
						(case when (case when te.date_begin > wht.date_begin then te.date_begin else wht.date_begin end) > @BeginMonth then (case when te.date_begin > wht.date_begin then te.date_begin else wht.date_begin end) else @BeginMonth end)
						AND (case when (case when isnull(te.date_end,@EndMonth) < isnull(wht.date_end, @EndMonth) then isnull(te.date_end,@EndMonth) else isnull(wht.date_end, @EndMonth) end) < @EndMonth then (case when isnull(te.date_end,@EndMonth) < isnull(wht.date_end, @EndMonth) then isnull(te.date_end,@EndMonth) else isnull(wht.date_end, @EndMonth) end) else @EndMonth end)
						),
			ndays = isnull(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(wht.link_empl,MONTH(@SCPeriod),YEAR(@SCPeriod))),9999),
			LINK_KBK = isnull(LP.LINK_KBK,te.LINK_KBK),
			lp.LINK, 'STO_LES_PAYS',
			0 as PERC,
			0 -- тип нагрузки
		From
			@STO_W_HOURS_TABLE as wht 
				inner join @tar_empls te on wht.link_tar_empl = te.link
				inner join dbo.STO_LES_PAYS as lp on wht.link_les = lp.link_les  and ( (wht.link_paral = lp.link_paral and wht.t in (1,2)) or wht.t = 4 )
		Where
			(Year(@SCPeriod) * 100 + Month(@SCPeriod))   between (Year(wht.date_begin) * 100 + Month(wht.date_begin)) and (Year(isnull(wht.date_end,@SCPeriod)) * 100 + Month(isnull(wht.date_end,@SCPeriod)))  

	
		Union all
		Select 
			(case when (case when te.date_begin > ap.date_begin then te.date_begin else ap.date_begin end) > @BeginMonth then ap.date_begin else @BeginMonth end),
			(case when (case when isnull(te.date_end,@EndMonth) < isnull(ap.date_end, @EndMonth) then isnull(te.date_end,@EndMonth) else isnull(ap.date_end, @EndMonth) end) < @EndMonth then (case when isnull(te.date_end,@EndMonth) < isnull(ap.date_end, @EndMonth) then isnull(te.date_end,@EndMonth) else isnull(ap.date_end, @EndMonth) end) else @EndMonth end),
			ap.link_empl, 
			AP.link_tar_empl, 
			0, 
			0,
			link_pay, 
			(case when ap.mode_p = 3 then AP.SUMMA 
					else Convert(Numeric(18,2), (case when coalesce(te.fot,2) = 2 then COALESCE(ETS.SUMMA,0) else coalesce(pkg_oklad,0) * coalesce(te.koef,0) end) * isnull(calc_perc,0) / 100) 
			end) * coalesce(te.num_stake,0), 
			0, 
			Summa = 
			(Case when isnull(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(ap.link_empl,MONTH(@SCPeriod),YEAR(@SCPeriod))),9999) > 0 
				then (case when ap.mode_p = 3 then AP.SUMMA else Convert(Numeric(18,2), (case when coalesce(te.fot,2) = 2 then COALESCE(ETS.SUMMA,0) else coalesce(pkg_oklad,0) * coalesce(te.koef,0) end) * isnull(calc_perc,0) / 100) end) 
					* CASE WHEN isnull(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(ap.link_empl,MONTH(@SCPeriod),YEAR(@SCPeriod))),9999) <> 0 
						THEN 1.000000 / isnull(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(ap.link_empl,MONTH(@SCPeriod),YEAR(@SCPeriod))),9999)
						ELSE 0 
					END	
					* (SELECT COUNT(DISTINCT PERIOD) FROM @NORM_DH ND WHERE ND.LINK_EMPL = ap.LINK_EMPL AND ND.PERIOD BETWEEN
						(case when (case when te.date_begin > ap.date_begin then te.date_begin else ap.date_begin end) > @BeginMonth then (case when te.date_begin > ap.date_begin then te.date_begin else ap.date_begin end) else @BeginMonth end)
						AND (case when (case when isnull(te.date_end,@EndMonth) < isnull(ap.date_end, @EndMonth) then isnull(te.date_end,@EndMonth) else isnull(ap.date_end, @EndMonth) end) < @EndMonth then (case when isnull(te.date_end,@EndMonth) < isnull(ap.date_end, @EndMonth) then isnull(te.date_end,@EndMonth) else isnull(ap.date_end, @EndMonth) end) else @EndMonth end)
						)
				else 
					(CASE WHEN ap.link_empl = 0 THEN (case when ap.mode_p = 3 then AP.SUMMA else Convert(Numeric(18,2), isnull(ETS.summa,0) * isnull(calc_perc,0) / 100) end) ELSE 0 END)
			end)  * coalesce(te.num_stake,0),
			wdays = (SELECT COUNT(DISTINCT PERIOD) FROM @NORM_DH ND WHERE ND.LINK_EMPL = ap.LINK_EMPL AND ND.PERIOD BETWEEN
						(case when (case when te.date_begin > ap.date_begin then te.date_begin else ap.date_begin end) > @BeginMonth then (case when te.date_begin > ap.date_begin then te.date_begin else ap.date_begin end) else @BeginMonth end)
						AND (case when (case when isnull(te.date_end,@EndMonth) < isnull(ap.date_end, @EndMonth) then isnull(te.date_end,@EndMonth) else isnull(ap.date_end, @EndMonth) end) < @EndMonth then (case when isnull(te.date_end,@EndMonth) < isnull(ap.date_end, @EndMonth) then isnull(te.date_end,@EndMonth) else isnull(ap.date_end, @EndMonth) end) else @EndMonth end)
						),
			ndays = isnull(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(ap.link_empl,MONTH(@SCPeriod),YEAR(@SCPeriod))),9999),
			ap.LINK_KBK,
			ap.LINK, 'STO_ADD_PAYS',
			0 as PERC,
			0 -- тип нагрузки	
		from 
			@ADD_PAYS ap inner join @tar_empls te on ap.link_tar_empl = te.link
			left join dbo.sa_ets_actual(@date) ETS on ets.link = ap.link_ets and ets.razr = te.razr
			left join (select distinct link_pkg, post_link, pkg_oklad  from dbo.SA_PKG_POST_OKLAD_FN(@date)) pkg on pkg.POST_LINK = te.link_post
		where 
			(ap.mode_p = 3 or ap.mode_p = 1 and ap.ets_only = 1)
			and
			(Year(@SCPeriod) * 100 + Month(@SCPeriod))   between (Year(te.date_begin) * 100 + Month(te.date_begin)) and (Year(isnull(te.date_end,@SCPeriod)) * 100 + Month(isnull(te.date_end,@SCPeriod)))  	

		--Для расчета ФОТ вакансии
		UPDATE @basis_sum SET ndays = wdays WHERE link_empl = 0
	
		/*Данные для расчета: Надбавки тарифируемых работников*/
		declare @empl_add_pay table (date_begin datetime, date_end datetime, link_tar_empl int, link_pay int, calc_perc numeric(18,2), LINK_KBK INT, LINK INT )
		insert into @empl_add_pay 
		Select 
			DATE_BEGIN = (case when AP.DATE_BEGIN > @BeginMonth then AP.DATE_BEGIN else @BeginMonth end),
			DATE_END = (case when isnull(AP.DATE_END, @EndMonth) < @EndMonth then isnull(AP.DATE_END, @EndMonth) else @EndMonth end),
			link_tar_empl, link_pay,  calc_perc, AP.LINK_KBK, AP.LINK 
		from 
			@ADD_PAYS ap  
		where 
			(ap.mode_p in (1,2) and ap.ets_only = 0) 
	
		/*Если заведены дополнительные табеля, то учтем коды начислений по ним*/
		insert into @empl_add_pay 
		select @BeginMonth, @EndMonth, t.link, dt.LINK_PAYS, dt.summa, t.LINK_KBK, 0 
		from @empl_with_add_tabels dt inner join @tar_empls t on dt.LINK_EMPL = t.link_empl

		/*Справочник - Очередь расчета надбавок*/
		declare @order table (ord int /*Номер в очереди*/, lev /*Уровень зависимости*/ int, link_pay int, marker int)
		insert into @order
		Select b.link, b.num_order, b.link_pay, 0 from @decode_base as b
		where 	b.link_base_pay <> 0  and b.link = (  Select max(b2.link) from  @decode_base b2 where b2.link_pay = b.link_pay ) 
	
	
		/*справочник базисов для начислений*/
		declare @basis table (link_pay int, link_base_pay int)
		insert into @basis
		Select distinct link_pay, link_base_pay
		from  @decode_base where link_base_pay <> 0 and marker = 0
		
		/*расчет сумм надбавок последовательно от листьев к корню*/
		While exists (Select * from @order where marker = 0)
		Begin
			/*определение очередной надбавки*/		
			Select @num_order = isnull(Max(ord),0) from @order where marker = 0 
			Select @link_pay = link_pay from @order where ord = @num_order
	
			/*расчте по ней суммы*/
			Insert into @basis_sum
			Select 
				(Case when ap.date_begin > bs.date_begin then ap.date_begin else bs.date_begin end),  
				(Case when ap.date_end < bs.date_end then ap.date_end else bs.date_end end),
				bs.link_empl, 
				bs.link_tar_empl, 
				bs.link_paral, 
				bs.link_les, 
				b.link_pay, 
				summa_base = sum(bs.summa), 
				perc= ap.calc_perc, 
				Summa = 
				(Case when dbo.NORM_DAY_DH(bs.LINK_EMPL, bs.DATE_BEGIN, bs.DATE_END) > 0 OR /* или это для вакансии*/ bs.LINK_EMPL = 0
					then convert(numeric(18,2), 
						sum(bs.summa) *	
								( --Если в периоде действия надбавки есть базовая сумма
									case when (bs.DATE_BEGIN between ap.DATE_BEGIN and ap.DATE_END) or (bs.DATE_END between ap.DATE_BEGIN and ap.DATE_END)  or (bs.DATE_BEGIN < ap.DATE_BEGIN and bs.DATE_END > ap.DATE_END)
									then (ap.calc_perc / 100)
	
								else 0 end))
						* CASE WHEN (SELECT COUNT(DISTINCT PERIOD) FROM @NORM_DH ND WHERE ND.LINK_EMPL = bs.LINK_EMPL AND ND.PERIOD BETWEEN bs.DATE_BEGIN AND bs.DATE_END ) <> 0
							THEN 1.000000 / (SELECT COUNT(DISTINCT PERIOD) FROM @NORM_DH ND WHERE ND.LINK_EMPL = bs.LINK_EMPL AND ND.PERIOD BETWEEN bs.DATE_BEGIN AND bs.DATE_END )
							ELSE 0
						END		
						* (SELECT COUNT(DISTINCT PERIOD) FROM @NORM_DH ND WHERE ND.LINK_EMPL = bs.LINK_EMPL AND ND.PERIOD BETWEEN 
								(case when ap.DATE_BEGIN > bs.DATE_BEGIN then ap.DATE_BEGIN else bs.DATE_BEGIN end) 
								AND (case when ap.DATE_END < bs.DATE_END then ap.DATE_END else bs.DATE_END end) )
					else 0
				end),
				(SELECT COUNT(DISTINCT PERIOD) FROM @NORM_DH ND WHERE ND.LINK_EMPL = bs.LINK_EMPL AND ND.PERIOD BETWEEN 
								(case when ap.DATE_BEGIN > bs.DATE_BEGIN then ap.DATE_BEGIN else bs.DATE_BEGIN end) 
								AND (case when ap.DATE_END < bs.DATE_END then ap.DATE_END else bs.DATE_END end) ),
				(SELECT COUNT(DISTINCT PERIOD) FROM @NORM_DH ND WHERE ND.LINK_EMPL = bs.LINK_EMPL AND ND.PERIOD BETWEEN bs.DATE_BEGIN AND bs.DATE_END),
				AP.LINK_KBK,		
				ap.link, (CASE WHEN ap.link > 0 THEN 'STO_ADD_PAYS' ELSE '' END),
				0, -- Процент оклада
				0 -- тип нагрузки
			from 	
				@empl_add_pay as ap inner join @basis as b on ap.link_pay = b.link_pay 
				inner join @basis_sum as bs on b.link_base_pay = bs.link_pay and ap.link_tar_empl = bs.link_tar_empl
			where  
				b.link_pay = @link_pay 
			group by
				bs.link_empl, bs.link_tar_empl, b.link_pay, bs.link_paral, bs.link_les, ap.calc_perc, ap.DATE_BEGIN, ap.DATE_END, bs.DATE_BEGIN, bs.DATE_END,AP.LINK_KBK,ap.LINK
		
			/*Пометим расчитанную надбавку работника, чтобы к ней больше не возвращаться*/
			Update @order Set marker = 1 where ord = @num_order
		
		End
		
		delete from @basis_sum where summa = 0 and link_pay not in (Select link_pays from @empl_with_add_tabels )
	END -- IF EXISTS (SELECT * FROM dbo.STO_TARIF_EMPL ...
--	END
	/*Расчет окончен*/		
	
	return
end










GO


GRANT SELECT ON dbo.[sa_to_all_pays_all_tar_empls] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[STO_ADD_PAYS_FN]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[STO_ADD_PAYS_FN]

GO

CREATE FUNCTION [DBO].[STO_ADD_PAYS_FN]
(	/*ПОСТОЯННОЕ НАДБАВКИ К НАГРУЗКАМ*/	
	@DATE DATETIME = NULL, --ВЫЧИСЛЯТЬ СТАЖ НА ДАННУЮ ДАТУ	
	@LINK_EMPL INT = -1, -- ССЫЛКА НА СОТРУДНИКА. -1 ЗНАЧИТ НА ВСЕХ	
	@LINK_TAR_EMPL INT = -1, --ССЫЛКА НА ДОП. РАБОТУ. - 1 ЗНАЧИТ НА ВСЕХ	
	@BUFF_ID VARCHAR(20) = NULL, --РАССЧЕТ ДЛЯ СОТРУДНИКОВ ИЗ ЗАДАННОГО СПИСКА, КОТОРЫЙ В ЭТОМ БУФЕРЕ	
	@DEP_LINK INT = NULL, -- ССЫЛКА НА ОРГАНИЗАЦИЮ	
	@MODE TINYINT = 0 -- 1 - ЗНАЧИТ НЕ РАССЧИТЫВАТЬ ПРОЦЕНТ ЗА СТАЖ.
)
RETURNS @RES TABLE
(
		LINK INT,
		LINK_EMPL INT,
		LINK_TAR_EMPL INT,
		LINK_PAY INT,
		DATE_BEGIN DATETIME,
		DATE_END DATETIME,
		MODE_P TINYINT,
		[PERCENT] NUMERIC(12, 4), 
		ETS_ONLY TINYINT,
		SUMMA NUMERIC(18, 2), 
		CALC_PERC NUMERIC(12, 4), 
		COMMENT VARCHAR(100),
		LINK_KBK INT,
		LINK_EXPIR INT,
		EXPIR_NAME VARCHAR(254),
		NO_CALC TINYINT
)

BEGIN

	--@ST
	DECLARE @ST TABLE (LINK_TAREMPL INT, LINK_EMPL INT, EXPIR_LINK INT, MAX_PERC NUMERIC(8,2), PERC NUMERIC(8,2))

	INSERT INTO @ST (LINK_TAREMPL, LINK_EMPL, EXPIR_LINK, MAX_PERC)
	SELECT LINK_TAREMPL, LINK_EMPL, EXPIR_LINK, MAX_PERC FROM dbo.SA_TAREMPL_PERCADDSTAGE(@DATE, @LINK_EMPL, @LINK_TAR_EMPL,@BUFF_ID,@DEP_LINK, @MODE)

	--@EI
	DECLARE @EI TABLE (EMPL_LINK INT, POST_LINK INT, ETS_RAZR TINYINT, LINK_KBK INT, NUM_STAKE NUMERIC(3,2))
	INSERT INTO @EI (EMPL_LINK, POST_LINK, ETS_RAZR, LINK_KBK, NUM_STAKE)
	SELECT EMPL_LINK, POST_LINK, ETS_RAZR, LINK_KBK, NUM_STAKE FROM DBO.SA_EMPLS_INFO(@DATE, @LINK_EMPL) EI
	
	--@sa_ets_actual
	DECLARE @sa_ets_actual TABLE (LINK INT, razr INT, SUMMA NUMERIC(18,2), MIN_VAL NUMERIC(18,2) )
	INSERT INTO @sa_ets_actual (LINK, razr, SUMMA, MIN_VAL)
	SELECT LINK, razr, SUMMA, MIN_VAL
	FROM dbo.sa_ets_actual(@date)

	--@SA_PKG_POST_FN
	--DECLARE @SA_PKG_POST_FN TABLE (LINK INT, OKLAD NUMERIC(18,2) )
	--INSERT INTO @SA_PKG_POST_FN (LINK, OKLAD)
	--SELECT LINK, OKLAD FROM dbo.SA_PKG_POST_FN(@date)	

	INSERT INTO @RES
	SELECT
		AP.LINK,
		AP.LINK_EMPL,
		AP.LINK_TAR_EMPL,
		AP.LINK_PAY,
		AP.DATE_BEGIN,
		AP.DATE_END,
		MODE_P = ISNULL(AP.MODE,0),
		AP.[PERCENT], 
		ETS_ONLY = ISNULL(AP.ETS_ONLY,0), 
		CASE WHEN ISNULL(AP.ETS_ONLY,0) = 0 THEN AP.[SUMMA] ELSE
 			(CASE ISNULL(ISNULL(SOVM.FOT,E.FOT),2)
				WHEN 2 THEN ISNULL(ETS.SUMMA,0)
				WHEN 1 THEN ISNULL(PKG.OKLAD,0) * ISNULL(ISNULL(SOVM.koef,E.koef_PKG),0)
				ELSE 0
			END) * AP.[percent]	/ (CASE WHEN WC.ISPERCENT = 1 THEN 100 ELSE 1 END)
		END,		
		CALC_PERC = (CASE WHEN ISNULL(AP.MODE,0) = 2 THEN ISNULL(ISNULL(ST.MAX_PERC,ST.PERC),0) ELSE AP.[PERCENT] END), 
		AP.COMMENT,
		AP.LINK_KBK,
		AP.LINK_EXPIR,
		EXPIR_NAME = CASE WHEN ISNULL(AP.MODE,0) = 2 THEN ISNULL(X.[NAME],'МАКСИМАЛЬНЫЙ % ИЗ ВЫБРАННЫХ СТАЖЕЙ') ELSE NULL END,
		NO_CALC = ISNULL(AP.NO_CALC,0)
	FROM 
		DBO.WAY_CALC WC
		INNER JOIN DBO.PAYS P WITH (NOLOCK) ON P.WAY_CALC = WC.CODE
		INNER JOIN DBO.STO_ADD_PAYMENT AS AP WITH (NOLOCK) ON P.LINK = AP.LINK_PAY
		INNER JOIN DBO.EMPL E WITH (NOLOCK) ON E.LINK = AP.LINK_EMPL

		--ОСНОВНАЯ ДОЛЖНОСТЬ
		LEFT JOIN @EI EI ON EI.EMPL_LINK = AP.LINK_EMPL
				
		--СОВМЕЩАЕМЫЕ ДОЛЖНОСТИ	
		LEFT JOIN DBO.STO_TARIF_EMPL SOVM ON SOVM.LINK_EMPL = AP.LINK_EMPL AND SOVM.LINK = AP.LINK_TAR_EMPL

		---------
		LEFT JOIN (

			SELECT LINK_POST AS LINK, LINK_PKG, PKG.OKLAD
			FROM
				dbo.[PKG_POST_DATE] PPD
				CROSS APPLY (SELECT MIN(DATE_BEGIN)-1 AS DATE_END FROM dbo.[PKG_POST_DATE] PPD2 WHERE PPD.LINK_POST = PPD2.LINK_POST AND PPD2.DATE_BEGIN > PPD.DATE_BEGIN) D
				CROSS APPLY (SELECT TOP 1 SUMMA AS OKLAD FROM dbo.PKG_OKLAD PO WITH (NOLOCK) WHERE PO.link_up = PPD.LINK_PKG and PO.date_begin <= @date order by PO.date_begin desc) PKG
			WHERE
				@date BETWEEN 	DATE_BEGIN AND ISNULL(D.DATE_END,@date)
			) AS PKG ON PKG.LINK = ISNULL(SOVM.LINK_POST,EI.POST_LINK)
		
		LEFT JOIN @sa_ets_actual ETS ON ETS.LINK = P.LINK_ETS AND ETS.RAZR = ISNULL(SOVM.LINK_ETS +ISNULL(SOVM.INC_ETS1_VALUE,0) +ISNULL(SOVM.INC_ETS2_VALUE,0) +ISNULL(SOVM.INC_ETS3_VALUE,0) , ISNULL(EI.ETS_RAZR,0)+ISNULL(E.INC_ETS1_VALUE,0) +ISNULL(E.INC_ETS2_VALUE,0) +ISNULL(E.INC_ETS3_VALUE,0))
		
		LEFT JOIN DBO.EXPIR X WITH (NOLOCK) ON AP.LINK_EXPIR = X.LINK
		LEFT JOIN @ST ST ON ST.LINK_TAREMPL = AP.LINK_TAR_EMPL AND ST.LINK_EMPL = AP.LINK_EMPL 
					AND (AP.LINK_EXPIR IS NOT NULL AND ST.EXPIR_LINK = AP.LINK_EXPIR OR AP.LINK_EXPIR IS NULL AND ST.MAX_PERC IS NOT NULL)
	WHERE
		WC.[TYPE] = 1
		AND
		P.[OBJECT] = 1
		AND
		(
			(@LINK_EMPL = -1 
			AND 
			(	@BUFF_ID IS NULL
				OR 
				@BUFF_ID IS NOT NULL AND EXISTS (SELECT * FROM DBO.BUFFER B WITH (NOLOCK) WHERE B.ID = @BUFF_ID AND B.LINK = AP.LINK_EMPL)
			))
			OR
			(@LINK_EMPL > 0 AND AP.LINK_EMPL = @LINK_EMPL)
		) 
		AND 
		(@LINK_TAR_EMPL = -1 OR AP.LINK_TAR_EMPL = @LINK_TAR_EMPL)

RETURN

END







GO


GRANT SELECT ON dbo.[STO_ADD_PAYS_FN] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_DGH_AVANCE_SUMM]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_DGH_AVANCE_SUMM]

GO

CREATE  PROC [DBO].SA_DGH_AVANCE_SUMM
	@VARKSCBUFFERCODE VARCHAR(20) = NULL,
	@VARKSNMONTH INT,
	@VARKSNYEAR  INT,
	@LINK_PAY INT,
	@ISNDFL TINYINT, 
	@CALCMODE TINYINT, --1 - ФИКСИРОВАННОЙ СУММОЙ  2 - С УЧЕТОМ САЛЬДО 3 - ТОЛЬКО ЗА МЕСЯЦ 4 - ВЫПЛАТА ПО НАЧИСЛЕНИЯМ 5 - ПРОЦЕНТОМ ОТ СУММЫ
	@FIXVAL NUMERIC(18,2),
	@LINK_VKR INT,
	@LINK_EKR INT = null,
	@DO_DECODE TINYINT = 0,
	@DEP_LINK INT = NULL
AS

DECLARE @PERIOD DATETIME
SET @PERIOD = DBO.CONVERTDMY2DATE(1,@VARKSNMONTH,@VARKSNYEAR)
SET @PERIOD = DBO.DATEENDOFMONTH(@PERIOD)

IF @DEP_LINK IS NULL
	EXEC DBO.XD_WHATS_ZB @DEP_LINK OUTPUT

SET @LINK_VKR = COALESCE(@LINK_VKR,0)
SET @LINK_EKR = COALESCE(@LINK_EKR,0)

DECLARE @VEDOM_OPTIONS_AVANCE_SUM   TINYINT -- Аванс в рублях
SET @VEDOM_OPTIONS_AVANCE_SUM  = COALESCE((SELECT TOP 1 CONVERT(INT,VALUE) FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'VEDOM_OPTIONS_AVANCE_SUM')),0)

DECLARE @VEDOM_OPTIONS_OPT8  TINYINT --Учитывать ранее выплаченный аванс
SET @VEDOM_OPTIONS_OPT8 = COALESCE((SELECT TOP 1 CONVERT(INT,VALUE) FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'VEDOM_OPTIONS_OPT8')),0)

DECLARE @TBL TABLE (
	LINK_EMPL INT, LINK_SFIN INT, LINK_EKR INT, 
	BASE NUMERIC(18,2), PROCENT NUMERIC(18,2), VAL NUMERIC(18,2), SALDO NUMERIC(18,2))

DECLARE	@VARKSRAION NUMERIC(18,2)
SELECT @VARKSRAION = KOEF FROM DBO.MINROT 
WHERE PERIOD = (SELECT MAX(PERIOD) FROM DBO.MINROT WHERE PERIOD <= @PERIOD)
	
---------------------------------------------------------------
SET @VEDOM_OPTIONS_AVANCE_SUM = (CASE WHEN @CALCMODE = 1 THEN 1 ELSE @VEDOM_OPTIONS_AVANCE_SUM END)

DECLARE @NDFL NUMERIC(18,2)
SET @NDFL = (CASE WHEN COALESCE(@ISNDFL,0) = 1 THEN 
			(CASE WHEN COALESCE(@ISNDFL,0)= 1 THEN 
					ISNULL((SELECT TOP 1 [PERCENT] 
							FROM dbo.DICTIONARY_RANGE 
							WHERE TARIF = 1 
								AND LINK_PAYS = (SELECT TOP 1 LINK_PAYS 
												FROM dbo.DICTIONARY_RANGE  DR
												WHERE  TARIF = 1 AND EXISTS (SELECT * FROM dbo.PAYS WHERE link = DR.LINK_PAYS AND [OBJECT] = 2 AND way_calc = 4)
												ORDER BY DATE DESC) 
								AND [DATE] <= @PERIOD
							ORDER BY DATE DESC)
							,0) 
			ELSE 0 END) 
		ELSE 0 END)

-------------------------------------------------------------
DECLARE @CONST_PAY TABLE (
	LINK_DGH INT, LINK_EMPL INT, LINK_PAY INT, CODE_PAY VARCHAR(254), NAME_PAY VARCHAR(254), 
	LINK_EKR INT, CODE_EKR VARCHAR(254), NAME_EKR VARCHAR(254), 
	SUMMA NUMERIC(18,2), AVANCE NUMERIC(18,2), VAL NUMERIC(18,2), WAY_CALC INT)
	
INSERT INTO @CONST_PAY (LINK_DGH, LINK_EMPL, LINK_PAY, CODE_PAY, NAME_PAY, LINK_EKR, CODE_EKR, NAME_EKR, WAY_CALC, SUMMA, AVANCE, VAL)
SELECT 	S.LINK, S.PERS_LINK, S.LINK_PAYS, P.CODE, P.NAME, p.LINK_EKR , EKR.CODE, EKR.NAME, p.WAY_CALC, 
	BASE = S.SUMMA,
	PROCENT = (CASE WHEN @VEDOM_OPTIONS_AVANCE_SUM = 0 THEN S.AVANCE ELSE 0 END), 
	SUMMA = (CASE WHEN @VEDOM_OPTIONS_AVANCE_SUM = 0 THEN (S.SUMMA * (1 - COALESCE(@NDFL,0) / 100 ) * S.AVANCE / 100) 
				ELSE CASE WHEN @CALCMODE = 1 THEN COALESCE(@FIXVAL,0) ELSE COALESCE(S.AVANCE,0) * (1 - COALESCE(@NDFL,0) / 100 ) END
			END) * (CASE WHEN COALESCE(@CALCMODE,0) = 5 THEN COALESCE(@FIXVAL,0)/100 ELSE 1 END)
FROM 
	dbo.REESTR_DGH S WITH (NOLOCK)
	inner join dbo.BUFFER B WITH (NOLOCK) ON S.PERS_LINK = B.LINK 	
	inner join dbo.pays p WITH (NOLOCK) ON p.link = s.LINK_PAYS
	LEFT JOIN dbo.KOSGU EKR WITH (NOLOCK) ON p.LINK_EKR = EKR.LINK 
WHERE 
	S.[DEP_LINK] = @DEP_LINK
	AND RTRIM(LTRIM(B.ID)) = RTRIM(LTRIM(@VARKSCBUFFERCODE)) 
	AND S.PERS_LINK IS not NULL 
	AND P.TYP_PER =1 AND S.SUMMA<>0 
	AND S.DATE1<= DBO.CONVERTDMY2DATE(1,@VARKSNMONTH,@VARKSNYEAR) 
	and  MONTH(S.DATE2)>=@VARKSNMONTH AND YEAR(S.DATE2)>=@VARKSNYEAR 
	AND S.LINK_KBK=@LINK_VKR 
	AND (p.LINK_EKR = ISNULL(@LINK_EKR,0) OR ISNULL(@LINK_EKR,0) = 0)

---------------------------------------------------------------
INSERT INTO @TBL (LINK_EMPL, LINK_SFIN, LINK_EKR, BASE, VAL, PROCENT, SALDO)
SELECT
	LINK_EMPL, @LINK_VKR, LINK_EKR, SUM(SUMMA), SUM(VAL), MAX(AVANCE),
	SALDO = (CASE WHEN COALESCE(@CALCMODE,0) = 2 THEN DBO.SALARY_DGH_SALDO_MONTH_VKR(LINK_EMPL, @PERIOD, @LINK_VKR, LINK_EKR, @DEP_LINK) ELSE 0 END)
FROM
	@CONST_PAY
GROUP BY
	LINK_EMPL, LINK_EKR

---------------------------------------------------------------
IF OBJECT_ID('TEMPDB..#OLD','U') IS NOT NULL
	DROP TABLE #OLD

SELECT LINK_EMPL = CJ.PERS_LINK, LINK_SFIN = LINK_VKR, LINK_EKR, SUM(SUMMA) AS SUMMA
INTO #OLD
FROM DBO.S_J_C_Short CJ INNER JOIN DBO.BUFFER B ON CJ.LINK_EMPL IS NULL AND CJ.PERS_LINK = B.LINK 
WHERE
	CJ.LINK_DEP = @DEP_LINK   
	AND RTRIM(LTRIM(B.ID)) = RTRIM(LTRIM(@VARKSCBUFFERCODE))
	AND @VEDOM_OPTIONS_OPT8 = 1 --УЧТЕМ РАНЕЕ ВЫПЛАЧЕННЫЙ АВАНС
	AND YEAR(PERIOD_BEGIN) = YEAR(@PERIOD) AND MONTH(PERIOD_BEGIN) = MONTH(@PERIOD) 
	AND SUMMA <> 0 
	AND LINK_PAYS = @LINK_PAY 
	AND (LINK_VKR = @LINK_VKR OR @LINK_VKR = 0)
	AND (LINK_EKR = ISNULL(@LINK_EKR,0) OR ISNULL(@LINK_EKR,0) = 0)
GROUP BY 
	CJ.PERS_LINK, LINK_VKR, LINK_EKR

--------------------------------------------------------------
SELECT  
	T.LINK_EMPL,
	T.LINK_SFIN,
	T.LINK_EKR, 
	SALDO = COALESCE(SALDO,0),
	SUMMA_OLD = COALESCE(O.SUMMA,0),
	SUMMA = --Аванса с учетом процентов и НДФЛ
			COALESCE(T.VAL,0)
			+ --остатки
			(CASE WHEN @VEDOM_OPTIONS_AVANCE_SUM <> 0 THEN COALESCE(SALDO,0) * COALESCE(PROCENT,0) / 100 ELSE COALESCE(SALDO,0) END)
			- --за исключением ранее выплаченного аванса
			COALESCE(O.SUMMA,0)
FROM 
	@TBL T LEFT JOIN #OLD O ON T.LINK_EMPL = O.LINK_EMPL AND T.LINK_SFIN = O.LINK_SFIN AND T.LINK_EKR = O.LINK_EKR



IF @DO_DECODE = 1
	SELECT P.*, F.LINK AS LINK_SFIN, F.CODE AS CODE_SFIN FROM @CONST_PAY P INNER JOIN DBO.SAL_SFIN F ON @LINK_VKR = F.LINK

GO


GRANT EXECUTE ON dbo.[SA_DGH_AVANCE_SUMM] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].BB_EXPORT_UF') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_EXPORT_UF]
GO


/*
© Кейсистемс (Keysystems), 2005
*/

CREATE           
PROCEDURE dbo.BB_EXPORT_UF @cBuffId	varchar(30) = ''

AS
DECLARE @iDepLink	int, 
		@cUserFio 	varchar(50), 
		@cUserDol 	varchar(50),
		@cUserPhone	varchar(20),
		@cBuffIdOld	Varchar(30),
		@Curs		CURSOR,
		@iLink		int,
		@iLinkUp	int,
		@iLinkOld	int,
		@iOrder		int


set @iDepLink = isnull(dbo.BK_GetDepZB(),dbo.GetOwnDepLink())

Select 	@cUserFio = EP.NAME_EMPL ,
   		@cUserDol = ep.post_name,
		@cUserPhone = (select TOP 1 case code when '' then '' else '(' + rtrim(CODE) + ') ' end + NUMBER  from KU_EMPL_PHONE where type = 3 and EMPL_LINK = EP.LINK)
FROM dbo.KU_EMPL_PLACING EP 
WHERE EP.LINK = dbo.GetCurrentEmpl()

-- Таблица 2 (FROM)
SELECT 	BUDG_LEVEL  = cast(replace(B.CODE_EL,'0','') as char(1)),
		KOD_UBP 	= BUDG,
		NAME_UBP	= left(rtrim(D.prefix) + rtrim(D.FULL_NAME) + case when charindex('(',D.prefix,0) > 0 then ')' else '' end,254),
		0 as link,
		0 as link_up
from dbo.DEPARTMENTS D
left join dbo.KL_ADMIN_BS V WITH (NOLOCK) on V.LINK = D.VED_LINK
left join dbo.KL_BUDG_TYPE B WITH (NOLOCK) on V.Link_Budg = B.LINK
where D.LINK = @iDepLink


-- Таблица 3 (TO)
SELECT 	KOD_TOFK  = TOFK.CODE,
		NAME_TOFK = TOFK.FULL_NAME,
		0 as link,
		0 as link_up
from dbo.DEPARTMENTS D
inner join dbo.TREASURY TOFK on D.TOFK_LINK = TOFK.LINK
where D.LINK = @iDepLink



-- Таблица 4 (UF)


	SELECT  LINK 		 = G.LINK,
			LINK_UP		 = G.LINK,
			GUID_FK		 = '',
			NOM_UF		 = G.NUMBER,
			DATE_UF		 = G.DATE,
			KOD_UBP		= case when DA.BUDG_LEVEL = '1' then DA.DEP_B_CODE else '' end,
			NAME_UBP	= DA.DEP_FNAME,
			LS_UBP		 = DA.ACC_CODE,
			NAME_GRS	 = DA.GRBS_NAME,
			GLAVA_GRS	 = DA.GRBS_CODE,
			NAME_BUD	 = DA.BUDG_NAME,
			NAME_UBP_FO	 = DA.FO_NAME,
			OKPO_FO		 = DA.FO_OKPO,
			LS_FO		 = '',
			NAME_TOFK	 = DA.TOFK_NAME,
			KOD_TOFK	 = DA.TOFK_CODE,
			FUND_SOURCE  = '',
			NOM_ZF		 = '',
			DATE_ZF		 = '',
			СNAME_PL	 = DA.DEP_FNAME,
			INN_PL		 = DA.DEP_INN,
			KPP_PL		 = DA.DEP_KPP,
			PASP		 = '',
			BS_PL		 = '',
			DOL_RUK		 = B.POST_NAME,
			NAME_RUK	 = B.SHORT_NAME, --case @iLongFio when 1 then rtrim(B.FM) + ' ' + rtrim(B.IM) + ' ' + rtrim(B.OT) else B.SHORT_NAME end,
			DOL_ISP		 = @cUserDol,
			NAME_ISP	 = @cUserFio,
			TEL_ISP		 = @cUserPhone,
 			DATE_POD	 = G.DATE,
			DOL_RUK_TOFK = '',
			NAME_RUK_TOFK= '',
			DOL_ISP_TOFK = '',
			NAME_ISP_TOFK= '',
			TEL_ISP_TOFK = '',
			DATE_TOFK	 = ''
	FROM dbo.G_PROV G
	inner join dbo.BB_DEP_ACC_DOP(NULL) DA on DA.ACC_LINK = G.ACC 
	left join dbo.GetOtvFaceData(@iDepLink, 'Руководитель') B on G.DEP = B.LINK_DEP
	left join dbo.GetOtvFaceData(@iDepLink, 'Главный бухгалтер') GB on G.DEP = GB.LINK_DEP
	where G.LINK in (select LINK from dbo.BufferGetTableByID(@cBuffId))

-- Таблица 5 (UFPP)

	select  LINK		= LINK,
			LINK_UP,
			LINE_NOM	= NUM_REC,
			GUID		= '',
			KOD_DOC		= case DOC_CODE when 'DOCUMENTS_PAY' then 'PP'
									 when 'BB_ZAYAVKA_KR' then 'ZR'
									 when 'BB_UVED_U' then 'UF'
									 when 'DOCUMENTS_RECEPTION_CASH' then 'ZS'
									 else 'SP' end,
			NAME_PP		= DOC_TYPE,
			NOM_PP		= DOC_NUM,
			DATE_PP		= DOC_DATE,
			CNAME_PP	= DEP_NAME,
			INN_PP		= DEP_INN,
			KPP_PP		= DEP_KPP,
			OKATO		= replace(DEP_OKATO,' ',''),
			LS_UBP		= '',
			KBK			= rtrim(replace(KBK_CODE,'.','')) + SGU_CODE,
			TYPE_KBK	= case KBK_TYPE when 1 then '10'
									  when 2 then '20'
									  when 4 then '31'
									  when 8 then '32'
									  else '' end,
			ADD_KLASS	= DCL_CODE,
			SUM_PP		= SUMMA,
			PURPOSE		= TARGET,
			NOM_ZR		= case when DOC_CODE = 'BB_ZAYAVKA_KR' or DOC_CODE = 'BB_UVED_U' then DOC_NUM else '' end,
			DATE_ZR		= case when DOC_CODE = 'BB_ZAYAVKA_KR' or DOC_CODE = 'BB_UVED_U' then DOC_DATE else null end,
			NOTE		= TITLE
	from dbo.BB_UVED_U_DOC
	where LINK_UP in (select LINK from dbo.BufferGetTableByID(@cBuffId))
	ORDER BY NUM_REC


-- Таблица 6 (UFPP_N)
select  LINK 		= T.LINK,
		LINK_UP		= (select top 1 LINK from BB_UVED_U_DOC where LINK_UP = T.LINK_DOC order by NUM_REC desc),
		LINE_NOM	= T.NUM_REC,
		CNAME_UBP	= T.DEP_NAME,
		INN_UBP		= T.DEP_INN,
		KPP_UBP		= T.DEP_KPP,
		OKATO		= replace(T.DEP_OKATO,' ',''),
		LS_UBP		= '',
		KBK			= rtrim(replace(T.KBK_CODE,'.','')) + T.SGU_CODE,
		TYPE_KBK	= case T.KBK_TYPE when 1 then '10'
									  when 2 then '20'
									  when 4 then '31'
									  when 8 then '32'
									  else '' end,
		ADD_KLASS	= T.DCL_CODE,
		SUM			= T.SUMMA,
		PURPOSE		= T.TARGET,
		FUND_SOURCE  = ''			
from dbo.BB_UVED_U_TABLE T
where T.LINK_DOC in (select LINK from dbo.BufferGetTableByID(@cBuffId))
ORDER BY NUM_REC

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant all on dbo.BB_EXPORT_UF to public
GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_U_VEDOM_DGH_SALDO]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_U_VEDOM_DGH_SALDO]

GO



/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE [dbo].SD_U_VEDOM_DGH_SALDO
 @varKSSumma numeric(15,2) OUTPUT, 
 @varKSnLinkEmpl	 int,
 @varKSdDate1	datetime,
 @varKSnMode	int,  		 
 @varKSLinkVKR INT,
 @varKSLinkEKR INT,
 @DEP_LINK INT = NULL
AS  
BEGIN

IF @DEP_LINK IS NULL
	EXEC DBO.XD_WHATS_ZB @DEP_LINK OUTPUT

SET @varKSSumma =
(case WHEN @varKSnMode = 1
			THEN 0
	WHEN @varKSnMode = 2
			THEN DBO.SALARY_DGH_SALDO_MONTH_VKR(@varKSnLinkEmpl, @varKSdDate1,@varKSLinkVKR,@varKSLinkEKR,@DEP_LINK)
	WHEN @varKSnMode = 3
			THEN 0
	ELSE 0
END)

END









GO


GRANT EXECUTE ON dbo.[SD_U_VEDOM_DGH_SALDO] TO PUBLIC

GO




GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RSA_RSV_1_PERS_UCH_SZV]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RSA_RSV_1_PERS_UCH_SZV]

GO

-- Пример вызова exec [dbo].RSA_RSV_1_PERS_UCH_SZV '20140401', '20140630',14716  , 3, 2485
CREATE PROCEDURE dbo.RSA_RSV_1_PERS_UCH_SZV
	@dDate1 DATETIME,
	@dDate2 DATETIME,
	@LINK_DEP int = NULL,
	@REP TINYINT = 0, 
	@VARILSF INT = null
AS BEGIN

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output

	SET @DEP_LINK = COALESCE(@LINK_DEP,@DEP_LINK)
	
	DECLARE @ATR_PERS_UCH INT
	SET @ATR_PERS_UCH  = (SELECT DBO.RN_GET_ATR_VALUE(@VARILSF, 'REPORTS_ATR_PERS_UCH'))

	SELECT * into #docs FROM   dbo.SA_SZV4_PACHKA P 
	WHERE
	p.link_dep = @DEP_LINK and p.link = @ATR_PERS_UCH 
	
	INSERT INTO #docs
	SELECT * 
	FROM   dbo.SA_SZV4_PACHKA P 
	WHERE
	p.link_dep = @DEP_LINK and p.year_begin = year(@dDate1) and month_end = month(@dDate2) and p.type = 1 and vid_kor <> 1
	/*AND p.[per_edt] < p.[per] */AND p.YEAR_EDT >= 2014  AND P.LINK_ISHOD = @ATR_PERS_UCH

	--SELECT * into #docs_kor_otm FROM   dbo.SA_SZV4_PACHKA P 
	--WHERE
	--p.link_dep = @DEP_LINK and p.year_begin =  year(@dDate1) and month_end = month(@dDate2) and p.type = 1 and vid_kor <> 1

	--Округление каждой строчки таблицы
	DECLARE @ROUND_TYPE tinyint, @ROUND_LEN tinyint
	Set @ROUND_TYPE = dbo.sa_get_option_by_code('SA_SZV4_OPT2')
	Set @ROUND_LEN = (case when @ROUND_TYPE <= 1 then 2 else 0 end)
	Set @ROUND_TYPE = (case when @ROUND_TYPE = 3 then 1 else 0 end)

	--Округление только итогов
	DECLARE @IT_ROUND_TYPE tinyint
	Set @IT_ROUND_TYPE = dbo.sa_get_option_by_code('SA_SZV4_OPT5')
	
	----- общие сведения
	Select
		[YEAR] = ISNULL(CASE WHEN year_begin >= 2013 THEN year_begin ELSE NULL END ,0),
		[CODE] = K.CODE,
		[PER] = ISNULL(CASE WHEN year_begin >= 2013 THEN PER ELSE NULL END ,0),
		[PER10] = ISNULL(CASE WHEN year_begin = 2013 THEN PER ELSE NULL END ,0),
		[TYPE] = P.vid_kor,
		[PER_EDT] = ISNULL(PER_EDT,0),
		[YEAR_EDT] = ISNULL(YEAR_EDT,0),
		[ID] = S.orders,
		[NGROUP] = S.pachka,
		[PFNUMBER] = PF_NUM,
		[T_DOG] = s.forma,
		LINK_FACE,
		[FIO] = FIO2,
		[FM],
		[IM],
		[OT],
		[ADDRESS] = ADDRESS,
		[ADDRESS2] = ADDRESS2,
		[INC_M1] = s1.INCOME_M1,
		[B_BEF_M1] = s1.BASE_BEFORE_M1,
		[B_AFT_M1] = s1.BASE_AFTER_M1, 
		[INC_M2] = s1.INCOME_M2,
		[B_BEF_M2] = s1.BASE_BEFORE_M2,
		[B_AFT_M2] = s1.BASE_AFTER_M2,	
		[INC_M3] = s1.INCOME_M3,
		[B_BEF_M3] = s1.BASE_BEFORE_M3,
		[B_AFT_M3] = s1.BASE_AFTER_M3,
		[INC_T1M1] = s1.INCOME_T1_M1,
		[INC_T2M1] = s1.INCOME_T2_M1,
		[INC_T1M2] = s1.INCOME_T1_M2,
		[INC_T2M2] = s1.INCOME_T2_M2,
		[INC_T1M3] = s1.INCOME_T1_M3,
		[INC_T2M3] = s1.INCOME_T2_M3, 
		[INSUR] = COALESCE(S.sum_doh,0), --Это сумма начисленных взносов на страхов. часть
		[INSUR1] = COALESCE(S.INSUR,0), --Это сумма уплаченных взносов на страхов. часть
		[GAIN] = COALESCE(S.GAIN,0), --Это сумма начисленных взносов на накопит. часть
		[GAIN1] = COALESCE(S.DOP,0), --Это сумма уплаченных взносов на накопит. часть
		[DOP] = COALESCE(S.DOP,0),
		[ID_EX] = ST.orders,
		[DATE_BEGIN] = date1,
		[DATE_END] = date2,
		[STR_DIS] = (CASE WHEN coalesce(s.dper_vn_m,0) <> 0 THEN CONVERT(VARCHAR(4),coalesce(s.dper_vn_m,0)) + ' м.' else '' end)
	 			+ (CASE WHEN coalesce(s.dper_vn_d,0) <> 0 THEN CONVERT(VARCHAR(4),coalesce(s.dper_vn_d,0)) + ' дн.' else '' end),
		dper_vn_m = coalesce(s.dper_vn_m,0),
		dper_vn_d = coalesce(s.dper_vn_d,0),
		[STR_VAC2] = (CASE WHEN coalesce(s.dper_oz_m,0) <> 0 THEN CONVERT(VARCHAR(4),coalesce(s.dper_oz_m,0)) + ' м.' else '' end)
	 			+ (CASE WHEN coalesce(s.dper_oz_d,0) <> 0 THEN CONVERT(VARCHAR(4),coalesce(s.dper_oz_d,0)) + ' дн.' else '' end),
		dper_oz_m = coalesce(s.dper_oz_m,0),
		dper_oz_d = coalesce(s.dper_oz_d,0),
		[TU_CODE] = f_ter_usl,
		ter_usl,
		ter_koef,
		[OS_CODE] = f_osob_usl,
		osob_usl,
		osob_spis = RTRIM(LTRIM(COALESCE(osob_k1,''))) + RTRIM(LTRIM(COALESCE(osob_k2,''))) + RTRIM(LTRIM(COALESCE(osob_k3,''))),
		OSOB_SPO = LTRIM(RTRIM(ST.OSOB_SPO)),
		[EX_CODE] = is_osnov,
		is_dop_m,
		is_dop_d,
		is_dop,
		f_is_dop,
		[P_CODE] = ud_osnov,
		ud_dop_m,
		ud_dop_d,
		ud_dop_k,
		f_ud_dop,
		DATE_DOC = [date],
		dep_PFNUM = d.PFNUMBER,
		FNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),year_begin) + '-ORG-' + LTRIM(RTRIM(d.PFNUMBER)) + '-DCK-' + REPLACE(str(S.pachka,5),' ','0') + '-DPT-000000-DCK-00000.XML'	
	INTO #SZV_ALL
	FROM
		dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SA_SZV4_SVEDENIA S ON P.link = S.link
		inner join SZV4_SVEDENIA s1 on s1.link = s.link1
		INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND	
		LEFT JOIN dbo.SA_SZV4_STAZH ST ON S.link1 = ST.link
		inner join departments d on d.link = p.link_dep 
	WHERE
		P.link in (select link from #DOCS)
		and P.proverka = 1
		and p.link_dep = @DEP_LINK
	ORDER BY
		[TYPE] ,K.CODE,  S.pachka, S.orders, ST.orders

--- нумирация пачек исходных и корректирующих сведений
declare @MAX_PACHKA_ISHOD  int,@MIN_PACHKA_ISHOD int,  @MIN_PACHKA_KORR int,  
		@ID int

select @MAX_PACHKA_ISHOD = max(NGROUP),
		@MIN_PACHKA_ISHOD = min(NGROUP),
		@MIN_PACHKA_KORR = (select min(NGROUP) FROM #SZV_ALL WHERE TYPE <> 1)
		FROM #SZV_ALL WHERE TYPE = 1

IF @MIN_PACHKA_ISHOD = @MIN_PACHKA_KORR

BEGIN 
	declare @Cur cursor , @GR int , @FNAME varchar(100)
	set @ID = 1
	SET @Cur = CURSOR FORWARD_ONLY
	FOR 
		select ngroup,FNAME  from #SZV_ALL WHERE TYPE <> 1 group by ngroup,FNAME
	OPEN @Cur
	FETCH NEXT FROM @Cur INTO @GR, @FNAME
	
	WHILE (@@fetch_status <> -1)
	BEGIN
		
		IF (@@fetch_status <> -2)
		BEGIN	

			UPDATE #SZV_ALL
				set NGROUP = @MAX_PACHKA_ISHOD+@ID --, t.[cGRP] =  '00'+ (@MAX_PACHKA_ISHOD+@ID)
			where ngroup = @GR AND FNAME = @FNAME and TYPE <> 1
				
			set @ID = @ID+1	
		end
		FETCH NEXT FROM @Cur INTO @GR , @FNAME
	end

CLOSE @Cur
DEALLOCATE @Cur

END 

UPDATE t
	SET  FNAME=  'PFR-700-Y-' + CONVERT(VARCHAR(4),[year]) + '-ORG-' + LTRIM(RTRIM(dep_PFNUM)) + '-DCK-' + REPLACE(str(NGROUP,5),' ','0') + '-DPT-000000-DCK-00000.XML'	
	from #SZV_ALL t  WHERE TYPE <> 1
-----------------------------------------------------
	
	IF @REP = 0 
	BEGIN 
		SELECT
			CODE = CONVERT(VARCHAR(14), [PFNUMBER]),
			COL1 = CONVERT(VARCHAR(14),[PFNUMBER]),
			COL2 = CONVERT(varchar(100),[FM]),
			COL3 = CONVERT(varchar(100),[IM]),
			COL4 = CONVERT(varchar(100),[OT]),
			COL5 = CONVERT(varchar(14),[PFNUMBER]),
			COL6 = [TYPE],
			COL7 = [NGROUP],
			COL8 = [FNAME],
			COL9 = CONVERT(VARCHAR(10), DATE_DOC, 104)
		FROM
			#SZV_ALL
		GROUP BY [TYPE],[T_DOG],[FM],[IM],[OT],[PFNUMBER], [NGROUP], [FNAME],DATE_DOC
		ORDER BY
			[TYPE],[T_DOG],[FM],[IM],[OT]
		
	END

	IF @REP = 1 
	BEGIN 	

	/*****************************************************/
	-- Собираем информацию по Исходным пачками
	/*****************************************************/
		create table #TMP1(CODE int,col1 int,   COL2 varchar(14), COL3 varchar(100), COL4 varchar (4), COL5 varchar (4), COL6 numeric(18,2), COL7 numeric(18,2), 
						   COL8 numeric(18,2), COL9 numeric(18,2), COL10 varchar(1), COL11 varchar(4), COL12 varchar(15), COL13 varchar(1), COL14 varchar(4),
						   COL15 int, COL16 varchar(100), COL17 varchar(100), COL18 varchar(100), COL19 int, COL20 int, COL21 numeric(18,2), COL22 numeric(18,2), COL23 numeric(18,2),
						   COL24 int, COL25 int, COL26 numeric(18,2), COL27 numeric(18,2), COL28 numeric(18,2),
						   COL29 int, COL30 int, COL31 numeric(18,2), COL32 numeric(18,2), COL33 numeric(18,2),
						   COL34 int, COL35 int, COL36 numeric(18,2), COL37 numeric(18,2), COL38 numeric(18,2),
						   COL39 int, COL40 int, COL41 numeric(18,2), COL42 numeric(18,2), COL43 numeric(18,2), COL44 numeric(18,2))
		
		
		/***************************************/
		-- для подсчета суммы с начала года по конец отчетного периода  
			
			
			------
	
			--- Обьявляем даты
			DECLARE @BYearDate	datetime
			SET @BYearDate = dbo.DateBeginOfYear (@dDate1)

			DECLARE @nYEAR1 INT, @nMONTH_1 INT, @nMONTH_2 INT, @nMONTH_3 INT

			SELECT 
				@nYEAR1 = YEAR(@dDate1),
				@nMONTH_1 = MONTH(@dDate1),
				@nMONTH_2 = MONTH(@dDate1)+1,
				@nMONTH_3 = MONTH(@dDate1)+2
	
			DECLARE @BDate datetime, @EndDate datetime, @EDate DATETIME, @EndYear datetime
			Set @EndYear = dbo.DateEndOfYear(@dDate1)
			SELECT @BDate = @dDate1, @EndDate = @dDate2
			SET @EDate = dateadd(year,1,convert(varchar, YEAR(@BDate))+'0101')
	
			--Фактическая база для договорников
			SELECT 
				GT.PERS_LINK, MONTH(G.[DATE]) AS MONTH_BASE, F.ENVD, SUMMA_BASE = sum(GT.SUMMA_BASE)
			INTO #DGH_FAKT_BASE
			FROM 
				dbo.DOCUMENTS_DGH G INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
				INNER JOIN dbo.SAL_SFIN F on F.LINK = GT.LINK_VKR
			WHERE 
				FLAG_JC = 1
				AND GT.WAY_CALC  = 6
				AND YEAR(G.[DATE]) = @nYEAR1
				AND MONTH(G.[DATE]) <= @nMONTH_3
				--AND LINK_DEP = @DEP_LINK 
			GROUP BY 
				GT.PERS_LINK, MONTH(G.[DATE]), F.ENVD

			SELECT  PERS_LINK, MONTH_BASE, SUMMA_BASE = SUM(SUMMA_BASE)
			INTO #DGH_FAKT_BASE1
			FROM #DGH_FAKT_BASE
			GROUP BY PERS_LINK, MONTH_BASE


			-- Журнал операций 
			CREATE TABLE #CALCULATE_JURNAL (LINK_PAYS INT, PERIOD_BEGIN DATETIME, LINK_DOC INT, PERS_LINK INT, LINK_VKR INT, LINK_EKR INT, LINK_EMPL INT, SUMMA NUMERIC(18,2), WAY_CALC TINYINT , SPECO int)
			INSERT INTO #CALCULATE_JURNAL (LINK_PAYS, PERIOD_BEGIN, LINK_DOC, PERS_LINK, LINK_VKR, LINK_EKR, LINK_EMPL, SUMMA,way_calc , SPECO)
			SELECT CJ.LINK_PAYS, CJ.PERIOD_BEGIN, CJ.LINK_DOC, CJ.PERS_LINK, CJ.LINK_VKR, cj.LINK_EKR, CJ.LINK_EMPL, SUMMA = SUM(CJ.SUMMA), p.way_calc , SPECO
			FROM dbo.CALCULATE_JURNAL CJ INNER JOIN dbo.PAYS P ON  CJ.LINK_PAYS = p.link
			WHERE
				Year(period_begin) = @nYEAR1 
				and Month(period_begin) <= @nMONTH_3 
				and CJ.LINK_DEP = @DEP_LINK
			GROUP BY
				cj.LINK_PAYS, cj.PERIOD_BEGIN, cj.LINK_DOC, cj.PERS_LINK, cj.LINK_VKR, cj.LINK_EKR, cj.LINK_EMPL, P.WAY_CALC,cj.SPECO
						
			--
			Declare @StBase2 table (link int)
			Insert into @StBase2 (link)
			select distinct link_pays from tax_ref where link_tax = (select top 1 link from pays where object = 3 and way_calc = 6)
			
			DECLARE @LINK_EKR213 INT
			SET @LINK_EKR213 = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '213')

			DECLARE @ESN_213 INT --Начислять страховые взносы на доходы с 213 ЭКР                                                    
			SET @ESN_213 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_5')
			
							
			------	у кого была инвалидность в заданном периоде
			SELECT DISTINCT PERS_LINK 
			INTO #PERS_INV
			FROM dbo.PERS_INVALID I
			WHERE COALESCE(I.DATE_BEGIN,@BYearDate) <= @EndYear AND COALESCE(I.DATE_END,@EndYear) >= @BYearDate

			------	у кого есть расчеты по доп тарифам со спец оценками в заданном периоде 
			SELECT DISTINCT sd.LINK, DOP = (CASE when S.COD_POS_SPISOK is NOT NULL then 1 else 2 end) , SPO = isnull(s4.code,'')
			INTO #EMPL_DT
			FROM DBO.KU_EMPL_PLACING SD
				left JOIN (select * from STAFF WHERE dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@nMONTH_3,@nYEAR1)) BETWEEN DATE_BEGIN AND DATE_END  ) S ON S.LINK_up = SD.STAFF_HEAD  AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@nMONTH_3,@nYEAR1 )) BETWEEN S.DATE_BEGIN AND S.DATE_END
				LEFT JOIN SA_SZV4_SPR  s4 ON  s4.link = s.COD_SPO_USL_TRUD  AND s4.spr_code = 'SPO_USL_TRUDA'
				WHERE 
					(S.COD_POS_SPISOK is NOT NULL OR S.COD_POS_SPISOK2 is NOT NULL) 


			--Заготовка для #SALARY_SUM2
			CREATE TABLE #SALARY_SUM_DATA (PERS_LINK INT,t_dog TINYINT, PERIOD_BEGIN DATETIME, SUMMA_ALL NUMERIC(18,2), SUMMA_NO NUMERIC(18,2), SUMMA_ALL_I NUMERIC(18,2), SUMMA_NO_I NUMERIC(18,2), SUMMA_ALL_E NUMERIC(18,2), SUMMA_NO_E NUMERIC(18,2), INV TINYINT 
					, SUMMA_NO_D1 NUMERIC(18,2), SUMMA_NO_D2 NUMERIC(18,2),    
				SUM_NO_D1_O4 NUMERIC(18,2) ,SUM_NO_D1_B34 NUMERIC(18,2) ,SUM_NO_D1_B33 NUMERIC(18,2),SUM_NO_D1_B32 NUMERIC(18,2), SUM_NO_D1_B31 NUMERIC(18,2),
					SUM_NO_D2_O4 NUMERIC(18,2) ,SUM_NO_D2_B34 NUMERIC(18,2) ,SUM_NO_D2_B33 NUMERIC(18,2),SUM_NO_D2_B32 NUMERIC(18,2), SUM_NO_D2_B31 NUMERIC(18,2) 
					)
			--Сотрудники
			INSERT INTO #SALARY_SUM_DATA (PERS_LINK, t_dog, PERIOD_BEGIN, SUMMA_ALL, SUMMA_NO, SUMMA_ALL_I, SUMMA_NO_I, SUMMA_ALL_E, SUMMA_NO_E, INV 
					, SUMMA_NO_D1, SUMMA_NO_D2,SUM_NO_D1_O4,SUM_NO_D1_B34,SUM_NO_D1_B33, SUM_NO_D1_B32, SUM_NO_D1_B31,
					SUM_NO_D2_O4,SUM_NO_D2_B34,SUM_NO_D2_B33, SUM_NO_D2_B32, SUM_NO_D2_B31
					)
			select
				E.PERS_LINK, 
				TDOG = 1,
				CJ.PERIOD_BEGIN,
				SUMMA_ALL = SUM(SUMMA),
				SUMMA_NO = SUM(CASE WHEN B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0 THEN SUMMA ELSE 0 END), --на которые не начисляются страховые взносы
				SUMMA_ALL_I = 0,
				SUMMA_NO_I = 0,
				SUMMA_ALL_E = SUM(CASE WHEN F.ENVD = 1 THEN SUMMA ELSE 0 END),
				SUMMA_NO_E = SUM(CASE WHEN F.ENVD = 1 AND (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) THEN SUMMA ELSE 0 END),
				INV = CASE WHEN I.PERS_LINK IS NULL THEN 0 ELSE 1 END,
				SUMMA_NO_D1 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and ED.DOP = 1 AND isnull(SPO,'') ='' THEN SUMMA ELSE 0 END),
				SUMMA_NO_D2 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and ED.DOP = 2 and  isnull(SPO,'') ='' THEN SUMMA ELSE 0 END),
				SUM_NO_D1_O4 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='О4'  THEN SUMMA ELSE 0 END),
				SUM_NO_D1_B34 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.4' THEN SUMMA ELSE 0 END),
				SUM_NO_D1_B33 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.3' THEN SUMMA ELSE 0 END), 
				SUM_NO_D1_B32 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.2' THEN SUMMA ELSE 0 END), 
				SUM_NO_D1_B31 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.1' THEN SUMMA ELSE 0 END),	
				SUM_NO_D2_O4 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='О4' THEN SUMMA ELSE 0 END),
				SUM_NO_D2_B34 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.4' THEN SUMMA ELSE 0 END),
				SUM_NO_D2_B33 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.3' THEN SUMMA ELSE 0 END), 
				SUM_NO_D2_B32 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.2' THEN SUMMA ELSE 0 END), 
				SUM_NO_D2_B31 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.1' THEN SUMMA ELSE 0 END)
			from 
			#CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
			INNER JOIN dbo.SAL_SFIN F on F.LINK = CJ.LINK_VKR
			INNER JOIN DBO.EMPL E ON E.LINK = CJ.LINK_EMPL
			LEFT JOIN @StBase2 B ON B.LINK = cj.LINK_PAYS
			LEFT JOIN #PERS_INV I ON I.PERS_LINK = E.PERS_LINK
			LEFT JOIN #EMPL_DT ED ON ED.link = CJ.LINK_EMPL
			
			where 	
				P.[OBJECT] = 1
				AND EXISTS(SELECT LINK_FACE FROM #SZV_all WHERE link_face = E.PERS_LINK )
			GROUP BY
				E.PERS_LINK, I.PERS_LINK, CJ.PERIOD_BEGIN

			--Договрники
			INSERT INTO #SALARY_SUM_DATA (PERS_LINK, t_dog, PERIOD_BEGIN, SUMMA_ALL, SUMMA_NO, SUMMA_ALL_I, SUMMA_NO_I, SUMMA_ALL_E, SUMMA_NO_E, INV 
					)
			select
				CJ.PERS_LINK, 
				T_DOG = 2,
				CJ.PERIOD_BEGIN,
				SUMMA_ALL = SUM(SUMMA),
				SUMMA_NO = SUM(SUMMA) - ISNULL((SELECT SUM(B1.SUMMA_BASE) FROM #DGH_FAKT_BASE1 B1 WHERE B1.PERS_LINK = CJ.PERS_LINK AND B1.MONTH_BASE = Month(CJ.PERIOD_BEGIN)),0), --на которые не начисляются страховые взносы
				SUMMA_ALL_I = 0,
				SUMMA_NO_I = 0,
				SUMMA_ALL_E = SUM(CASE WHEN F.ENVD = 1 THEN SUMMA ELSE 0 END),
				SUMMA_NO_E = SUM(CASE WHEN F.ENVD = 1 THEN SUMMA ELSE 0 END)  - ISNULL((SELECT SUM(B.SUMMA_BASE) FROM #DGH_FAKT_BASE B WHERE B.PERS_LINK = CJ.PERS_LINK AND B.MONTH_BASE = Month(CJ.PERIOD_BEGIN) AND B.ENVD = 1),0),
				INV = CASE WHEN I.PERS_LINK IS NULL THEN 0 ELSE 1 END
					
			from 
				#CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
				INNER JOIN dbo.SAL_SFIN F on F.LINK = CJ.LINK_VKR
				INNER JOIN DBO.PERSON P1 ON P1.LINK = CJ.PERS_LINK
				LEFT JOIN #PERS_INV I ON I.PERS_LINK = CJ.PERS_LINK
			where 	
				P.[OBJECT] = 1
			GROUP BY
				CJ.PERS_LINK, I.PERS_LINK, CJ.PERIOD_BEGIN, P1.RESIDENT, p1.birthdate


				--корректировка в соотвествие с тем, в каком есяце кто был инвалидом
			UPDATE D SET 
				SUMMA_ALL_I = (CASE WHEN EXISTS (SELECT * FROM dbo.PERS_INVALID I1 WHERE I1.PERS_LINK = D.PERS_LINK AND dbo.DateEndOfMonth(PERIOD_BEGIN) BETWEEN ISNULL(I1.DATE_BEGIN,PERIOD_BEGIN) AND  ISNULL(I1.DATE_END,dbo.DateEndOfMonth(PERIOD_BEGIN))) THEN SUMMA_ALL ELSE 0 END), 
				SUMMA_NO_I = (CASE WHEN EXISTS (SELECT * FROM dbo.PERS_INVALID I1 WHERE I1.PERS_LINK = D.PERS_LINK AND dbo.DateEndOfMonth(PERIOD_BEGIN) BETWEEN ISNULL(I1.DATE_BEGIN,PERIOD_BEGIN) AND  ISNULL(I1.DATE_END,dbo.DateEndOfMonth(PERIOD_BEGIN))) THEN SUMMA_NO ELSE 0 END), 
				SUMMA_ALL_E = (CASE WHEN NOT EXISTS (SELECT * FROM dbo.PERS_INVALID I1 WHERE I1.PERS_LINK = D.PERS_LINK AND dbo.DateEndOfMonth(PERIOD_BEGIN) BETWEEN ISNULL(I1.DATE_BEGIN,PERIOD_BEGIN) AND  ISNULL(I1.DATE_END,dbo.DateEndOfMonth(PERIOD_BEGIN))) THEN SUMMA_ALL_E ELSE 0 END), 
				SUMMA_NO_E = (CASE WHEN NOT EXISTS (SELECT * FROM dbo.PERS_INVALID I1 WHERE I1.PERS_LINK = D.PERS_LINK AND dbo.DateEndOfMonth(PERIOD_BEGIN) BETWEEN ISNULL(I1.DATE_BEGIN,PERIOD_BEGIN) AND  ISNULL(I1.DATE_END,dbo.DateEndOfMonth(PERIOD_BEGIN))) THEN SUMMA_NO_E ELSE 0 END)

			FROM #SALARY_SUM_DATA D
			WHERE INV = 1 --которые имели инвалидность в каком-то месяце периода	



----------<<<<<<<<< #SPR_ESN для определения скидочной части (кусок ИЗ РСВ)
		create table #SPR_ESN1 ([MONTH_BASE] TINYINT, SUMMA_BASE numeric(12,2) default 0.00, DED_M numeric(12,2) default 0.00, INV_M numeric(12,2) default 0.00, SUMMA numeric(12,2) default 0.00, WAY_CALC int default 0.00, REF_PHYS_PERS int default 0 , PF_NUM VARCHAR (14), FACE_GROUP TINYINT, I TINYINT, E TINYINT , SP VARCHAR(4))

		Insert InTo #SPR_ESN1 ([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS , PF_NUM, FACE_GROUP, I, E, SP)
		Select [MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, p.INSUR_NUM ,
			( CASE WHEN P.RESIDENT = 0 THEN 3 
				   WHEN YEAR(birthdate)<= 1966 THEN 1 
				   WHEN YEAR(birthdate)>= 1967 THEN 2 END ) AS FACE_GROUP, 
			dbo.is_invalid(REF_PHYS_PERS,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH_BASE,@nYEAR1))),
			F.ENVD,
			SP = isnull(s4.code,'')
		from dbo.SA_ESN_VIEW(@nYEAR1, @nMONTH_3, @LINK_DEP, 0) S
			inner join PERSON P on S.REF_PHYS_PERS = P.link
			inner join dbo.SAL_SFIN F on F.LINK = S.LINK_VKR
			LEFT JOIN SA_SZV4_SPR  s4 ON  s4.link = S.SPECO  AND s4.spr_code = 'SPO_USL_TRUDA'
		WHERE  WAY_CALC not in (5)

		--Суммы по договорникам
		INSERT INTO #SPR_ESN1 
			([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, PF_NUM, FACE_GROUP, I, E)
		SELECT 
			MONTH(G.[DATE]) AS MONTH_BASE, GT.SUMMA_BASE, 0, 0, GT.SUMMA, GT.WAY_CALC, GT.PERS_LINK, p.INSUR_NUM ,
			( CASE WHEN P.RESIDENT = 0  THEN 3
				   WHEN YEAR(birthdate)<= 1966 THEN 1 
				   WHEN YEAR(birthdate)>= 1967 THEN 2 END) AS FACE_GROUP , 
			dbo.is_invalid(GT.PERS_LINK,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,G.[MONTH],@nYEAR1))),
			F.ENVD
			
		FROM 
			DOCUMENTS_DGH G INNER JOIN DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
			inner join PERSON P on GT.PERS_LINK = P.link
			inner join dbo.SAL_SFIN F on F.LINK = GT.LINK_VKR
		WHERE 
			FLAG_JC = 1
			AND GT.WAY_CALC  not in (5)
			AND YEAR(G.[DATE]) = @nYEAR1
			AND MONTH(G.[DATE]) <= @nMONTH_3
			AND LINK_DEP = @DEP_LINK


		DELETE FROM #SPR_ESN1
		WHERE  EXISTS (SELECT * FROM dbo.KJ_PERS_PENSION K WHERE K.PERS_LINK = REF_PHYS_PERS  and K.CHECK_SZV = 0)
---------->>>>>>>>>>

		DECLARE @PREDEL NUMERIC(18,2)
		SET @PREDEL = (SELECT TOP 1 PREDEL FROM DICTIONARY_RANGE WHERE TARIF = 1 AND YEAR([DATE]) =  @nYEAR1)

				--Данные о начисленной зарплате
				SELECT 
					PERS_LINK,
					T_DOG,
					/*MON = Month(PERIOD_BEGIN),*/ 
					SUMMA_ALL = SUM(SUMMA_ALL), SUMMA_NO = SUM(SUMMA_NO), 
					SUMMA_ALL_I = SUM(SUMMA_ALL_I), SUMMA_NO_I = SUM(SUMMA_NO_I),
					SUMMA_ALL_E = SUM(SUMMA_ALL_E), SUMMA_NO_E = SUM(SUMMA_NO_E),
					SUMMA_ALL_D =  ISNULL((select SUM(SUMMA_ALL) FROM  #SALARY_SUM_DATA WHERE PERS_LINK = s.PERS_LINK AND t_dog=2 ),0) ,
					SUMMA_ALL_DO = (CASE WHEN SUM(SUMMA_ALL) > @PREDEL THEN  @PREDEL ELSE (SUM(SUMMA_ALL) - SUM(SUMMA_NO)) END ),
					SUMMA_ALL_AFTER = (CASE WHEN SUM(SUMMA_ALL) > @PREDEL THEN  SUM(SUMMA_ALL) - @PREDEL ELSE 0 END )
				
				INTO #SALARY_SUM2
				FROM #SALARY_SUM_DATA s 
				GROUP BY
					pers_link, T_DOG--,Month(PERIOD_BEGIN)


--RSA_RSV_1_PERS_UCH_SZV '20140401', '20140630', 74578 , 1, 2739

				--
				DROP TABLE #SALARY_SUM_DATA	
				DROP TABLE #DGH_FAKT_BASE
				DROP TABLE #PERS_INV 
				DROP TABLE #CALCULATE_JURNAL
				DROP TABLE #EMPL_DT
				
		/***************************************/

		
		DECLARE @Cur1 CURSOR, @CODE varchar(4), @TYPE tinyint , @T_DOG tinyint, @PFNUMBER VARCHAR (14) , @FM VARCHAR(100),@IM VARCHAR(100),@OT VARCHAR(100),
		@pf_num1 VARCHAR(14) , @CODE_old VARCHAR(4), @TYPE_OLD TINYINT, @nom_pp INT
		set @pf_num1 = ''
		set @CODE_old = '' 
		set @TYPE_OLD = 0
		set @nom_pp = 1
		
		SET @Cur1 = CURSOR FORWARD_ONLY
		FOR SELECT  [CODE],[TYPE]/*,[T_DOG]*/,[PFNUMBER], [FM],[IM],[OT] FROM #SZV_ALL where /*T_DOG = 1 and*/ [TYPE] = 1  GROUP BY [FM],[IM],[OT],[PFNUMBER],[TYPE],CODE/*, [T_DOG]*/ ORDER BY [FM],[IM],[OT],[PFNUMBER],[TYPE],CODE/*, [T_DOG]*/
		OPEN @Cur1
		FETCH NEXT FROM @Cur1 INTO  @CODE,@TYPE/*,@T_DOG*/,@PFNUMBER,@FM,@IM,@OT
		WHILE (@@fetch_status <> -1)
		BEGIN

			IF (@@fetch_status <> -2)
			BEGIN
				--- Заполнение информации по первому коду категории сотрудника (нр , оои, пнэд)
				IF (/*@T_DOG = 1 and */ @PFNUMBER <> @pf_num1 ) 
				BEGIN
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18/*,COL19, COL20, COL21,COL22, COL23,COL24, COL25, COL26,COL27, COL28, 
									   COL29, COL30, COL31,COL32, COL33,COL34, COL35, COL36,COL37, COL38,COL39, COL40, COL41,COL42, COL43*/, COL44)
					SELECT CODE =  @nom_pp,
						   COL1 =  @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0),	
						   COL3 = CONVERT(VARCHAR(100), 'Всего с начала расчетного периода, в том числе за последние три месяца отчетного периода:'),
						   COL4 = CONVERT(VARCHAR(4),'400'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = ISNULL(SS.SUMMA_ALL,0),--isnull([INC_M1]+[INC_M2]+[INC_M3],0),
						   COL7 = ISNULL(SS.SUMMA_ALL_DO,0) - ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) ))

						   	
						   	
						   									,--ISNULL([B_BEF_M1]+[B_BEF_M2]+[B_BEF_M3],0),
						   COL8 = ISNULL((CASE WHEN s.T_DOG = 1 OR NOT EXISTS(SELECT T_DOG FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 1 AND PFNUMBER = @PFNUMBER) THEN 
						   						(SELECT TOP 1 SUMMA_ALL_DO FROM #SALARY_SUM2 WHERE /* code = @CODE and [TYPE] = @TYPE and*/ T_DOG = 2 AND PERS_LINK = S.LINK_FACE)
											ELSE 0 END )  ,0),
						   COL9 = CASE WHEN ISNULL(SS.SUMMA_ALL_AFTER,0) > 0 THEN 
						   															(ISNULL(SS.SUMMA_ALL_AFTER,0)  - ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) + (ss.SUMMA_NO - ss.SUMMA_NO_I-SUMMA_NO_E) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) )))
																			ELSE 0 END	/*ISNULL([B_AFT_M1]+[B_AFT_M2]+[B_AFT_M3],0)*/,
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая'end), ''), 
						   COL13 = ISNULL(CONVERT(VARCHAR(1),[per_edt]), ''), 
						   COL14 = ISNULL(CONVERT(VARCHAR(4),[year_edt]), ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT), 
						   /*COL19 = (case when a.id = 1 then k_PER_EDT else null end) ,
						   COL20 = (case when a.id = 1 then  CONVERT(VARCHAR(4),k_YEAR_EDT) else '' end),
						   COL21 = (case when a.id = 1 then (CASE WHEN k_YEAR_EDT >= '2014' THEN k_INSUR ELSE 0 END ) else 0 end),
						   COL22 = (case when a.id = 1 then (CASE WHEN k_YEAR_EDT < '2014' THEN k_INSUR ELSE 0 END ) else 0 end),
						   COL23 = (case when a.id = 1 then (CASE WHEN k_YEAR_EDT < '2014' THEN k_GAIN ELSE 0 END ) else 0 end),
						   COL24 = (case when a.id = 2 then k_PER_EDT else null end), 
						   COL25 = (case when a.id = 2 then  CONVERT(VARCHAR(4),k_YEAR_EDT) else '' end), 
						   COL26 = (case when a.id = 2 then  (CASE WHEN k_YEAR_EDT >= '2014' THEN k_INSUR ELSE 0 END )else 0 end), 
						   COL27 = (case when a.id = 2 then (CASE WHEN k_YEAR_EDT < '2014' THEN k_INSUR ELSE 0 END )else 0 end), 
						   COL28 = (case when a.id = 2 then (CASE WHEN k_YEAR_EDT < '2014' THEN k_GAIN ELSE 0 END )else 0 end),
						   COL29 = (case when a.id = 3 then k_PER_EDT else null end),
						   COL30 = (case when a.id = 3 then CONVERT(VARCHAR(4),k_YEAR_EDT) else '' end),
						   COL31 = (case when a.id = 3 then (CASE WHEN k_YEAR_EDT >= '2014' THEN k_INSUR ELSE 0 END )else 0 end),
						   COL32 = (case when a.id = 3 then (CASE WHEN k_YEAR_EDT < '2014' THEN k_INSUR ELSE 0 END )else 0 end), 
						   COL33 = (case when a.id = 3 then (CASE WHEN k_YEAR_EDT < '2014' THEN k_GAIN ELSE 0 END )else 0 end),
						   COL34 = (case when a.id = 4 then k_PER_EDT else null end),
						   COL35 = (case when a.id = 4 then CONVERT(VARCHAR(4),k_YEAR_EDT) else '' end),
						   COL36 = (case when a.id = 4 then (CASE WHEN k_YEAR_EDT >= '2014' THEN k_INSUR ELSE 0 END )else 0 end),
						   COL37 = (case when a.id = 4 then (CASE WHEN k_YEAR_EDT < '2014' THEN k_INSUR ELSE 0 END) else 0 end),
						   COL38 = (case when a.id = 4 then (CASE WHEN k_YEAR_EDT < '2014' THEN k_GAIN ELSE 0 END )else 0 end),
						   COL39 = (case when a.id = 5 then k_PER_EDT else null end),
						   COL40 = (case when a.id = 5 then CONVERT(VARCHAR(4),k_YEAR_EDT) else '' end),
						   COL41 = (case when a.id = 6 then (CASE WHEN k_YEAR_EDT >= '2014' THEN k_INSUR ELSE 0 END )else 0 end),
						   COL42 = (case when a.id = 7 then (CASE WHEN k_YEAR_EDT < '2014' THEN k_INSUR ELSE 0 END)else 0 end), 
						   COL43 = (case when a.id = 8 then (CASE WHEN k_YEAR_EDT < '2014' THEN k_GAIN ELSE 0 END )else 0 end)
						   */
						   COL44 = isnull([INSUR],0)
					FROM #SZV_ALL s  LEFT JOIN  #SALARY_SUM2 ss ON ss.pers_link = s.link_face AND SS.T_DOG = S.T_DOG
					/*left join (select row_number() over (order by PER_EDT) as ID , [PER_EDT] as k_PER_EDT, YEAR_EDT as k_YEAR_EDT, INSUR as k_INSUR, GAIN  as k_GAIN, PFNUMBER as k_PFNUMBER , FM as k_FM from  #SZV_ALL WHERE  [TYPE] = 2  AND id_ex =1 and FM = @FM) a on a.k_PFNUMBER  = s.PFNUMBER and a.k_FM = s.FM 
					*/WHERE  code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER and FM = @FM
					GROUP BY [TYPE],CODE , S.[T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]/*,k_PER_EDT,k_YEAR_EDT,k_INSUR,k_GAIN,k_FM*/,[INSUR],[INC_M1],[INC_M2],[INC_M3],[B_BEF_M1],[B_BEF_M2],[B_BEF_M3], [B_AFT_M1],[B_AFT_M2],[B_AFT_M3]/* ,a.ID*/, SS.SUMMA_ALL, SS.SUMMA_ALL_DO, SS.PERS_LINK, S.LINK_FACE, SS.SUMMA_ALL_AFTER, SS.SUMMA_NO, SS.SUMMA_NO_I, SS.SUMMA_NO_E

					
					select row_number() over (order by PER_EDT) as ID , 
							[PER_EDT] as k_PER_EDT, 
							YEAR_EDT as k_YEAR_EDT, 
							INSUR as k_INSUR, 
							GAIN  as k_GAIN, 
							PFNUMBER as k_PFNUMBER , 
							FM as k_FM 
					INTO #TMP01
					from  #SZV_ALL  
					WHERE  [TYPE] = 2  AND id_ex =1 and FM = @FM
					
					UPDATE #TMP1
					set COL19 = (SELECT TOP 1 k_PER_EDT FROM #TMP01 where ID=1),
						COL20 = (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=1),
						COL21 = (CASE WHEN (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=1) >= '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=1)  ELSE 0 END ),
						COL22 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=1) < '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=1) ELSE 0 END ),
						COL23 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=1) < '2014' THEN (SELECT TOP 1 k_GAIN FROM #TMP01 where ID=1) ELSE 0 END ), 
						COL24 = (SELECT TOP 1 k_PER_EDT FROM #TMP01 where ID=2),
					    COL25 = (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=2), 
					    COL26 = (CASE WHEN (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=2) >= '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=2)  ELSE 0 END ), 
					    COL27 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=2) < '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=2) ELSE 0 END ), 
					    COL28 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=2) < '2014' THEN (SELECT TOP 1 k_GAIN FROM #TMP01 where ID=2) ELSE 0 END ),
					    COL29 = (SELECT TOP 1 k_PER_EDT FROM #TMP01 where ID=3),
					    COL30 = (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=3), 
					    COL31 = (CASE WHEN (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=3) >= '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=3)  ELSE 0 END ), 
					    COL32 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=3) < '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=3) ELSE 0 END ), 
					    COL33 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=3) < '2014' THEN (SELECT TOP 1 k_GAIN FROM #TMP01 where ID=3) ELSE 0 END ),
					    COL34 = (SELECT TOP 1 k_PER_EDT FROM #TMP01 where ID=4),
					    COL35 = (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=4), 
					    COL36 = (CASE WHEN (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=4) >= '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=4)  ELSE 0 END ), 
					    COL37 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=4) < '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=4) ELSE 0 END ), 
					    COL38 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=4) < '2014' THEN (SELECT TOP 1 k_GAIN FROM #TMP01 where ID=4) ELSE 0 END ),
					    COL39 = (SELECT TOP 1 k_PER_EDT FROM #TMP01 where ID=5),
					    COL40 = (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=5), 
					    COL41 = (CASE WHEN (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=5) >= '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=5)  ELSE 0 END ), 
					    COL42 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=5) < '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=5) ELSE 0 END ), 
					    COL43 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=5) < '2014' THEN (SELECT TOP 1 k_GAIN FROM #TMP01 where ID=5) ELSE 0 END )--,
					
					from #TMP1	
					WHERE #TMP1.COL5 = @CODE 
					and #TMP1.COL12 = ISNULL((case WHEN @TYPE = 1 then 'Исходная' when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end), '') 
					and #TMP1.COL2 = @PFNUMBER and #TMP1.COL16 = @FM

					drop table #TMP01

					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14,COL15, COL16,COL17, COL18 , COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,
						   COL2 = ISNULL([PFNUMBER],0),	
						   COL3 = CONVERT(VARCHAR(100), '1 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'401'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = isnull([INC_M1],0),
						   COL7 = ISNULL([B_BEF_M1],0),
						   COL8 = ISNULL((CASE WHEN T_DOG = 1  OR NOT EXISTS(SELECT T_DOG FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 1 AND PFNUMBER = @PFNUMBER) THEN 
						   					(SELECT TOP 1 [B_BEF_M1] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER)
						   					ELSE 0 END ) ,0),
						   COL9 = ISNULL([B_AFT_M1],0),
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая' end), ''), 
						   COL13 = ISNULL(CONVERT(VARCHAR(1),[per_edt]), ''), 
						   COL14 = ISNULL(CONVERT(VARCHAR(4),[year_edt]), ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [TYPE],CODE, [T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt],[INSUR],[INC_M1],[INC_M2],[INC_M3],[B_BEF_M1], [B_AFT_M1],[B_AFT_M2],[B_AFT_M3]
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0),	
						   COL3 = CONVERT(VARCHAR(100), '2 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'402'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL5 = isnull([INC_M2],0),
						   COL6 = ISNULL([B_BEF_M2],0),
						   COL7 = ISNULL((CASE WHEN T_DOG = 1  OR NOT EXISTS(SELECT T_DOG FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 1 AND PFNUMBER = @PFNUMBER) THEN 
						   				(SELECT TOP 1 [B_BEF_M2] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER)
						   				ELSE 0 END ) ,0),
						   COL8 = ISNULL([B_AFT_M2],0),
						   COL9 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая' end ), ''), 
						   COL13 = ISNULL(CONVERT(VARCHAR(1),[per_edt]), ''), 
						   COL14 = ISNULL(CONVERT(VARCHAR(4),[year_edt]), ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [TYPE],CODE, [T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt],[INSUR],[INC_M1],[INC_M2],[INC_M3],[B_BEF_M2], [B_AFT_M1],[B_AFT_M2],[B_AFT_M3]
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0),	
						   COL3 = CONVERT(VARCHAR(100), '3 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'403'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = isnull([INC_M3],0),
						   COL7 = ISNULL([B_BEF_M3],0),
						   COL8 = ISNULL((CASE WHEN T_DOG = 1  OR NOT EXISTS(SELECT T_DOG FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 1 AND PFNUMBER = @PFNUMBER) THEN 
						   					(SELECT TOP 1 [B_BEF_M3] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER) 
						   					ELSE 0 END ),0),
						   COL9 = ISNULL([B_AFT_M3],0),
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая' end ), ''), 
						   COL13 = ISNULL(CONVERT(VARCHAR(1),[per_edt]), ''), 
						   COL14 = ISNULL(CONVERT(VARCHAR(4),[year_edt]), ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [TYPE],CODE, [T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt],[INSUR],[INC_M1],[INC_M2],[INC_M3],[B_BEF_M3]	, [B_AFT_M1],[B_AFT_M2],[B_AFT_M3]
					
					set @nom_pp = @nom_pp + 1
				END
					
				
				--- Заполнение информации по следующему коду категории сотрудника (если за расчетный период у сотрудника была не одна категория)
				IF /*@T_DOG = 1 and*/  @PFNUMBER = @pf_num1 and @CODE <> @CODE_old	and  @TYPE = @TYPE_OLD
				BEGIN 
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0), 
						   COL3 = CONVERT(VARCHAR(100), 'Всего с начала расчетного периода, в том числе за последние три месяца отчетного периода:'),
						   COL4 = CONVERT(VARCHAR(4),'410'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = ISNULL(SS.SUMMA_ALL,0),--isnull([INC_M1]+[INC_M2]+[INC_M3],0),
						   COL7 = ISNULL(SS.SUMMA_ALL_DO,0) - ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) ))
																	,--ISNULL([B_BEF_M1]+[B_BEF_M2]+[B_BEF_M3],0),
						   COL8 = ISNULL((CASE WHEN s.T_DOG = 1 OR NOT EXISTS(SELECT T_DOG FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 1 AND PFNUMBER = @PFNUMBER) THEN 
						   						(SELECT TOP 1 SUMMA_ALL_DO FROM #SALARY_SUM2 WHERE /* code = @CODE and [TYPE] = @TYPE and*/ T_DOG = 2 AND PERS_LINK = S.LINK_FACE)
											ELSE 0 END )  ,0),
						   COL9 = CASE WHEN ISNULL(SS.SUMMA_ALL_AFTER,0) > 0 THEN 
						   															(ISNULL(SS.SUMMA_ALL_AFTER,0)  - ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) + (ss.SUMMA_NO - ss.SUMMA_NO_I-SUMMA_NO_E) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) )))
																			ELSE 0 END	/*ISNULL([B_AFT_M1]+[B_AFT_M2]+[B_AFT_M3],0)*/,
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая'end), ''), 
						   COL13 = ISNULL([per_edt], ''), 
						   COL14 = ISNULL([year_edt], ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM #SZV_ALL s  LEFT JOIN  #SALARY_SUM2 ss ON ss.pers_link = s.link_face AND SS.T_DOG = S.T_DOG
					/*left join (select row_number() over (order by PER_EDT) as ID , [PER_EDT] as k_PER_EDT, YEAR_EDT as k_YEAR_EDT, INSUR as k_INSUR, GAIN  as k_GAIN, PFNUMBER as k_PFNUMBER , FM as k_FM from  #SZV_ALL WHERE  [TYPE] = 2  AND id_ex =1 and FM = @FM) a on a.k_PFNUMBER  = s.PFNUMBER and a.k_FM = s.FM 
					*/WHERE  code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER and FM = @FM
					GROUP BY [TYPE],CODE , S.[T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]/*,k_PER_EDT,k_YEAR_EDT,k_INSUR,k_GAIN,k_FM*/,[INSUR],[INC_M1],[INC_M2],[INC_M3],[B_BEF_M1],[B_BEF_M2],[B_BEF_M3], [B_AFT_M1],[B_AFT_M2],[B_AFT_M3]/* ,a.ID*/, SS.SUMMA_ALL, SS.SUMMA_ALL_DO, SS.PERS_LINK, S.LINK_FACE, SS.SUMMA_ALL_AFTER, SS.SUMMA_NO, SS.SUMMA_NO_I, SS.SUMMA_NO_E



					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0),
						   COL3 = CONVERT(VARCHAR(100), '1 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'411'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = isnull([INC_M1],0),
						   COL7 = ISNULL([B_BEF_M1],0),
						   COL8 = ISNULL((CASE WHEN T_DOG = 1 OR NOT EXISTS(SELECT T_DOG FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 1 AND PFNUMBER = @PFNUMBER) THEN 
						   					(SELECT TOP 1 [B_BEF_M1] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER)
						   					ELSE 0 END) ,0),
						   COL9 = ISNULL([B_AFT_M1],0),
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая' end), ''), 
						   COL13 = ISNULL([per_edt], ''), 
						   COL14 = ISNULL([year_edt], ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
						   
					FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [TYPE],CODE, [T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt],[INSUR],[INC_M1],[INC_M2],[INC_M3],[B_BEF_M1]	, [B_AFT_M1],[B_AFT_M2],[B_AFT_M3]
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0), 
						   COL3 = CONVERT(VARCHAR(100), '2 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'412'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = isnull([INC_M2],0),
						   COL7 = ISNULL([B_BEF_M2],0),
						   COL8 = ISNULL((CASE WHEN T_DOG = 1  OR NOT EXISTS(SELECT T_DOG FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 1 AND PFNUMBER = @PFNUMBER) THEN 
						   					(SELECT TOP 1 [B_BEF_M2] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER)
											ELSE 0 END) ,0),
						   COL9 = ISNULL([B_AFT_M2],0),
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая' end ), ''), 
						   COL13 = ISNULL([per_edt], ''), 
						   COL14 = ISNULL([year_edt], ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [TYPE],CODE, [T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt],[INSUR],[INC_M1],[INC_M2],[INC_M3],[B_BEF_M2]	, [B_AFT_M1],[B_AFT_M2],[B_AFT_M3]		
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0), 
						   COL3 = CONVERT(VARCHAR(100), '3 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'413'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = isnull([INC_M3],0),
						   COL7 = ISNULL([B_BEF_M3],0),
						   COL8 = ISNULL((CASE WHEN T_DOG = 1 OR NOT EXISTS(SELECT T_DOG FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 1 AND PFNUMBER = @PFNUMBER) THEN 
						   					(SELECT TOP 1 [B_BEF_M3] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER)
						   					ELSE 0 END ) ,0),
						   COL9 = ISNULL([B_AFT_M3],0),
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая' end ), ''), 
						   COL13 = ISNULL([per_edt], ''), 
						   COL14 = ISNULL([year_edt], ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [TYPE],CODE, [T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt],[INSUR],[INC_M1],[INC_M2],[INC_M3],[B_BEF_M3]	, [B_AFT_M1],[B_AFT_M2],[B_AFT_M3]
					
					set @nom_pp = @nom_pp + 1
				END						

				--- заполняем пустые строки '410','411','412','413' 
			
				if not exists (select * from #tmp1 
								where COl2 = @PFNUMBER 
								and COL12 = (case WHEN @TYPE = 1 then 'Исходная' when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end)
								and COL4 = '410' ) AND NOT EXISTS (SELECT * FROM #SZV_ALL WHERE PFNUMBER = @PFNUMBER AND CODE != @CODE AND [TYPE] = 1) 
				begin 
						
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL(@PFNUMBER,''), 
						   COL3 = CONVERT(VARCHAR(100), 'Всего с начала расчетного периода, в том числе за последние три месяца отчетного периода:'),
						   COL4 = CONVERT(VARCHAR(4),'410'),
						   COL5 = CONVERT(VARCHAR(4),''),
						   COL6 = 0,
						   COL7 = 0,
						   COL8 = 0,
						   COL9 = 0,
						   COL10 = ISNULL((SELECT TOP 1 COL10 from #tmp1 where COl2 = @PFNUMBER and COL12 = 'Исходная' and COL4 = '400'),''), 
						   COL11 = ISNULL((select TOP 1 COL11 from #tmp1 where COl2 = @PFNUMBER and COL12 = 'Исходная' and COL4 = '400'),''), 
						   COL12 = ISNULL((case WHEN @TYPE = 1 then 'Исходная' when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end), ''), 
						   COL13 = '', 
						   COL14 = '',
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,
						   COL2 = ISNULL(@PFNUMBER,''),
						   COL3 = CONVERT(VARCHAR(100), '1 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'411'),
						   COL5 = CONVERT(VARCHAR(4),''),
						   COL6 = 0,
						   COL7 = 0,
						   COL8 = 0,
						   COL9 = 0,
						   COL10 = ISNULL((select TOP 1 COL10 from #tmp1 where COl2 = @PFNUMBER and COL12 = 'Исходная' and COL4 = '400'),'') , 
						  COL11 = ISNULL((select TOP 1 COL11 from #tmp1 where COl2 = @PFNUMBER and COL12 = 'Исходная' and COL4 = '400'),''), 
						   COL12 = ISNULL((case WHEN @TYPE = 1 then 'Исходная' when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end), ''), 
						   COL13 = '', 
						   COL14 = '',
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,
						   COL2 = ISNULL(@PFNUMBER,''), 
						 COL3 = CONVERT(VARCHAR(100), '2 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'412'),
						   COL5 = CONVERT(VARCHAR(4),''),
						   COL6 = 0,
						   COL7 = 0,
						   COL8 = 0,
						   COL9 = 0,
						   COL10 = ISNULL((select TOP 1 COL10 from #tmp1 where COl2 = @PFNUMBER and COL12 = 'Исходная' and COL4 = '400'),'') , 
						   COL11 = ISNULL((select TOP 1 COL11 from #tmp1 where COl2 = @PFNUMBER and COL12 = 'Исходная' and COL4 = '400'),''), 
						   COL12 = ISNULL((case WHEN @TYPE = 1 then 'Исходная' when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end), ''), 
						   COL13 = '', 		
						   COL14 = '',
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					
					set @nom_pp = @nom_pp + 1		
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13, COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp, 
						   COL2 = ISNULL(@PFNUMBER,''),
						   COL3 = CONVERT(VARCHAR(100), '3 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'413'),
						   COL5 = CONVERT(VARCHAR(4),''),
						   COL6 = 0,
						   COL7 = 0,
						   COL8 = 0,
						   COL9 = 0,
						   COL10 = ISNULL((select TOP 1 COL10 from #tmp1 where COl2 = @PFNUMBER and COL12 = 'Исходная' and COL4 = '400'),'') , 
						   COL11 = ISNULL((select TOP 1 COL11 from #tmp1 where COl2 = @PFNUMBER and COL12 = 'Исходная' and COL4 = '400'),''), 
						   COL12 = ISNULL((case WHEN @TYPE = 1 then 'Исходная' when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end), ''), 
						   COL13 = '', 
						   COL14 = '',
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					
					set @nom_pp = @nom_pp + 1	
				
				end 

					set @pf_num1 = @PFNUMBER
					set @CODE_old = @CODE
					set @TYPE_OLD = @TYPE
			END

			FETCH NEXT FROM @Cur1 INTO @CODE,@TYPE/*,@T_DOG*/,@PFNUMBER,@FM,@IM,@OT
		END

		CLOSE @Cur1
		DEALLOCATE @Cur1
		
		/*****************************************************/
		-- Собираем информацию по Кореектирующим/Отменяющим
		/*****************************************************/
		--create table #TMP1(CODE int,col1 int,   COL2 varchar(14), COL3 varchar(100), COL4 varchar (4), COL5 varchar (4), COL6 numeric(18,2), COL7 numeric(18,2), COL8 numeric(18,2), COL9 numeric(18,2), COL10 varchar(1), COL11 varchar(4), COL12 varchar(15), COL13 varchar(1), COL14 varchar(4),COL15 int)
	
		DECLARE @Cur2 CURSOR
		set @pf_num1 = ''
		set @CODE_old = '' 
		set @TYPE_OLD = 0
		set @nom_pp = (SELECT MAX(CODE) FROM #TMP1 WHERE COL12= 'Исходная') + 1 
		
		SET @Cur2 = CURSOR FORWARD_ONLY
		FOR SELECT  [CODE],[TYPE]/*,[T_DOG]*/,[PFNUMBER], [FM],[IM],[OT]  FROM #SZV_ALL where /*T_DOG = 1 and*/ [TYPE] != 1  GROUP BY [FM],[IM],[OT],[PFNUMBER],[TYPE],CODE/*, [T_DOG]*/ ORDER BY [FM],[IM],[OT],[PFNUMBER],[TYPE],CODE/*, [T_DOG]*/
		OPEN @Cur2
		FETCH NEXT FROM @Cur2 INTO  @CODE,@TYPE/*,@T_DOG*/,@PFNUMBER,@FM,@IM,@OT
		WHILE (@@fetch_status <> -1)
		BEGIN

			IF (@@fetch_status <> -2)
			BEGIN
				--- Заполнение информации по первому коду категории сотрудника (нр , оои, пнэд)
				IF (/*@T_DOG = 1 and */ @PFNUMBER <> @pf_num1 ) 
				BEGIN
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE =  @nom_pp,
						   COL1 =  @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0),	
						   COL3 = CONVERT(VARCHAR(100), 'Всего с начала расчетного периода, в том числе за последние три месяца отчетного периода:'),
						   COL4 = CONVERT(VARCHAR(4),'400'),
						  COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = ISNULL(SS.SUMMA_ALL,0),--isnull([INC_M1]+[INC_M2]+[INC_M3],0),
						   COL7 = ISNULL(SS.SUMMA_ALL_DO,0) - ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) )),
									--ISNULL([B_BEF_M1]+[B_BEF_M2]+[B_BEF_M3],0),
						   COL8 = ISNULL((CASE WHEN s.T_DOG = 1 OR NOT EXISTS(SELECT T_DOG FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 1 AND PFNUMBER = @PFNUMBER) THEN 
						   						(SELECT TOP 1 SUMMA_ALL_DO FROM #SALARY_SUM2 WHERE /* code = @CODE and [TYPE] = @TYPE and*/ T_DOG = 2 AND PERS_LINK = S.LINK_FACE)
											ELSE 0 END )  ,0),
						   COL9 = CASE WHEN ISNULL(SS.SUMMA_ALL_AFTER,0) > 0 THEN 
						   															(ISNULL(SS.SUMMA_ALL_AFTER,0)  - ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) + (ss.SUMMA_NO - ss.SUMMA_NO_I-SUMMA_NO_E) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) )))
																			ELSE 0 END	/*ISNULL([B_AFT_M1]+[B_AFT_M2]+[B_AFT_M3],0)*/,
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая'end), ''), 
						   COL13 = ISNULL(CONVERT(VARCHAR(1),[per_edt]), ''), 
						   COL14 = ISNULL(CONVERT(VARCHAR(4),[year_edt]), ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   COL44 = isnull([INSUR],0)
					FROM #SZV_ALL s LEFT JOIN  #SALARY_SUM2 ss ON ss.pers_link = s.link_face AND SS.T_DOG = S.T_DOG WHERE  code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER				
					GROUP BY [TYPE],CODE, [T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[per_edt],[year_edt],[INSUR],[INC_M1],[INC_M2],[INC_M3],[B_BEF_M1],[B_BEF_M2],[B_BEF_M3], [B_AFT_M1],[B_AFT_M2],[B_AFT_M3], SS.SUMMA_ALL, SS.SUMMA_ALL_DO, SS.PERS_LINK, S.LINK_FACE, SS.SUMMA_NO, SS.SUMMA_NO_I, SS.SUMMA_NO_E


					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14,COL15, COL16,COL17, COL18 , COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,
						   COL2 = ISNULL([PFNUMBER],0),	
						   COL3 = CONVERT(VARCHAR(100), '1 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'401'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = isnull([INC_M1],0),
						   COL7 = ISNULL([B_BEF_M1],0),
						   COL8 = ISNULL((CASE WHEN T_DOG = 1  OR NOT EXISTS(SELECT T_DOG FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 1 AND PFNUMBER = @PFNUMBER) THEN 
						   					(SELECT TOP 1 [B_BEF_M1] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER)
						   					ELSE 0 END ) ,0),
						   COL9 = ISNULL([B_AFT_M1],0),
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая' end), ''), 
						   COL13 = ISNULL(CONVERT(VARCHAR(1),[per_edt]), ''), 
						   COL14 = ISNULL(CONVERT(VARCHAR(4),[year_edt]), ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [TYPE],CODE, [T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[per_edt],[year_edt],[INSUR],[INC_M1],[INC_M2],[INC_M3],[B_BEF_M1],[B_BEF_M2],[B_BEF_M3], [B_AFT_M1],[B_AFT_M2],[B_AFT_M3]
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0),	
						   COL3 = CONVERT(VARCHAR(100), '2 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'402'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = isnull([INC_M2],0),
						   COL7 = ISNULL([B_BEF_M2],0),
						   COL8 = ISNULL((CASE WHEN T_DOG = 1  OR NOT EXISTS(SELECT T_DOG FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 1 AND PFNUMBER = @PFNUMBER) THEN 
						   				(SELECT TOP 1 [B_BEF_M2] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER)
						   				ELSE 0 END ) ,0),
						   COL9 = ISNULL([B_AFT_M2],0),
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая' end ), ''), 
						   COL13 = ISNULL(CONVERT(VARCHAR(1),[per_edt]), ''), 
						   COL14 = ISNULL(CONVERT(VARCHAR(4),[year_edt]), ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [TYPE],CODE, [T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[per_edt],[year_edt],[INSUR],[INC_M1],[INC_M2],[INC_M3],[B_BEF_M1],[B_BEF_M2],[B_BEF_M3], [B_AFT_M1],[B_AFT_M2],[B_AFT_M3]
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0),	
						   COL3 = CONVERT(VARCHAR(100), '3 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'403'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = isnull([INC_M3],0),
						   COL7 = ISNULL([B_BEF_M3],0),
						   COL8 = ISNULL((CASE WHEN T_DOG = 1  OR NOT EXISTS(SELECT T_DOG FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 1 AND PFNUMBER = @PFNUMBER) THEN 
						   					(SELECT TOP 1 [B_BEF_M3] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER) 
						   					ELSE 0 END ),0),
						   COL9 = ISNULL([B_AFT_M3],0),
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая' end ), ''), 
						   COL13 = ISNULL(CONVERT(VARCHAR(1),[per_edt]), ''), 
						   COL14 = ISNULL(CONVERT(VARCHAR(4),[year_edt]), ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [TYPE],CODE, [T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[per_edt],[year_edt],[INSUR],[INC_M1],[INC_M2],[INC_M3],[B_BEF_M1],[B_BEF_M2],[B_BEF_M3], [B_AFT_M1],[B_AFT_M2],[B_AFT_M3]	
					
					set @nom_pp = @nom_pp + 1
				END
					
				
				--- Заполнение информации по следующему коду категории сотрудника (если за расчетный период у сотрудника была не одна категория)
				IF /*@T_DOG = 1 and*/  @PFNUMBER = @pf_num1 and @CODE <> @CODE_old	and  @TYPE = @TYPE_OLD
				BEGIN 
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0), 
						   COL3 = CONVERT(VARCHAR(100), 'Всего с начала расчетного периода, в том числе за последние три месяца отчетного периода:'),
						   COL4 = CONVERT(VARCHAR(4),'410'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = ISNULL(SS.SUMMA_ALL,0),--isnull([INC_M1]+[INC_M2]+[INC_M3],0),
						   COL7 = ISNULL(SS.SUMMA_ALL_DO,0) - ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) )),
								  --ISNULL([B_BEF_M1]+[B_BEF_M2]+[B_BEF_M3],0),
						   COL8 = ISNULL((CASE WHEN s.T_DOG = 1 OR NOT EXISTS(SELECT T_DOG FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 1 AND PFNUMBER = @PFNUMBER) THEN 
						   						(SELECT TOP 1 SUMMA_ALL_DO FROM #SALARY_SUM2 WHERE /* code = @CODE and [TYPE] = @TYPE and*/ T_DOG = 2 AND PERS_LINK = S.LINK_FACE)
											ELSE 0 END )  ,0),
						   COL9 = CASE WHEN ISNULL(SS.SUMMA_ALL_AFTER,0) > 0 THEN 
						   															(ISNULL(SS.SUMMA_ALL_AFTER,0)  - ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) + (ss.SUMMA_NO - ss.SUMMA_NO_I-SUMMA_NO_E) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) )))
																			ELSE 0 END	/*ISNULL([B_AFT_M1]+[B_AFT_M2]+[B_AFT_M3],0)*/,
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая'end), ''), 
						   COL13 = ISNULL([per_edt], ''), 
						   COL14 = ISNULL([year_edt], ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM #SZV_ALL s  LEFT JOIN  #SALARY_SUM2 ss ON ss.pers_link = s.link_face AND SS.T_DOG = S.T_DOG
					WHERE  code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [TYPE],CODE, [T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[per_edt],[year_edt],[INSUR],[INC_M1],[INC_M2],[INC_M3],[B_BEF_M1],[B_BEF_M2],[B_BEF_M3], [B_AFT_M1],[B_AFT_M2],[B_AFT_M3], SS.SUMMA_NO, SS.SUMMA_NO_I, SS.SUMMA_NO_E
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0),
						   COL3 = CONVERT(VARCHAR(100), '1 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'411'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = isnull([INC_M1],0),
						   COL7 = ISNULL([B_BEF_M1],0),
						   COL8 = ISNULL((CASE WHEN T_DOG = 1 OR NOT EXISTS(SELECT T_DOG FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 1 AND PFNUMBER = @PFNUMBER) THEN 
						   					(SELECT TOP 1 [B_BEF_M1] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER)
						   					ELSE 0 END) ,0),
						   COL9 = ISNULL([B_AFT_M1],0),
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая' end), ''), 
						   COL13 = ISNULL([per_edt], ''), 
						   COL14 = ISNULL([year_edt], ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [TYPE],CODE, [T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[per_edt],[year_edt],[INSUR],[INC_M1],[INC_M2],[INC_M3],[B_BEF_M1],[B_BEF_M2],[B_BEF_M3], [B_AFT_M1],[B_AFT_M2],[B_AFT_M3]
					
					set @nom_pp = @nom_pp + 1
			
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0), 
						   COL3 = CONVERT(VARCHAR(100), '2 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'412'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = isnull([INC_M2],0),
						   COL7 = ISNULL([B_BEF_M2],0),
						   COL8 = ISNULL((CASE WHEN T_DOG = 1  OR NOT EXISTS(SELECT T_DOG FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 1 AND PFNUMBER = @PFNUMBER) THEN 
						   					(SELECT TOP 1 [B_BEF_M2] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER)
											ELSE 0 END) ,0),
						   COL9 = ISNULL([B_AFT_M2],0),
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая' end ), ''), 
						   COL13 = ISNULL([per_edt], ''), 
						   COL14 = ISNULL([year_edt], ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [TYPE],CODE, [T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[per_edt],[year_edt],[INSUR],[INC_M1],[INC_M2],[INC_M3],[B_BEF_M1],[B_BEF_M2],[B_BEF_M3], [B_AFT_M1],[B_AFT_M2],[B_AFT_M3]		
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0), 
						   COL3 = CONVERT(VARCHAR(100), '3 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'413'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = isnull([INC_M3],0),
						   COL7 = ISNULL([B_BEF_M3],0),
						   COL8 = ISNULL((CASE WHEN T_DOG = 1 OR NOT EXISTS(SELECT T_DOG FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 1 AND PFNUMBER = @PFNUMBER) THEN 
						   					(SELECT TOP 1 [B_BEF_M3] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER)
						   					ELSE 0 END ) ,0),
						   COL9 = ISNULL([B_AFT_M3],0),
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая' end ), ''), 
						   COL13 = ISNULL([per_edt], ''), 
						   COL14 = ISNULL([year_edt], ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [TYPE],CODE, [T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[per_edt],[year_edt],[INSUR],[INC_M1],[INC_M2],[INC_M3],[B_BEF_M1],[B_BEF_M2],[B_BEF_M3], [B_AFT_M1],[B_AFT_M2],[B_AFT_M3]	
					
					set @nom_pp = @nom_pp + 1
				END						

				--- заполняем пустые строки '410','411','412','413' 
			
				if not exists (select * from #tmp1 
								where COL2 = @PFNUMBER 
								and COL12 = (case WHEN @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end)
								and COL4 = '410' ) AND NOT EXISTS (SELECT * FROM #SZV_ALL WHERE PFNUMBER = @PFNUMBER AND CODE != @CODE AND [TYPE] = 1) 
				begin 
						
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL(@PFNUMBER,''), 
						   COL3 = CONVERT(VARCHAR(100), 'Всего с начала расчетного периода, в том числе за последние три месяца отчетного периода:'),
						   COL4 = CONVERT(VARCHAR(4),'410'),
						   COL5 = CONVERT(VARCHAR(4),''),
						   COL6 = 0,
						   COL7 = 0,
						   COL8 = 0,
						   COL9 = 0,
						   COL10 = ISNULL((select TOP 1 COL10 from #tmp1 where COl2 = @PFNUMBER and COL12 = (case when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end) and COL4 = '400'),''), 
						   COL11 = ISNULL((select TOP 1 COL11 from #tmp1 where COl2 = @PFNUMBER and COL12 = (case when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end) and COL4 = '400'),''), 
						   COL12 = ISNULL((case WHEN @TYPE = 1 then 'Исходная' when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end), ''), 
						   COL13 = ISNULL((select TOP 1 COL13 from #tmp1 where COl2 = @PFNUMBER and COL12 = (case when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end) and COL4 = '400'),''), 
						   COL14 = ISNULL((select TOP 1 COL14 from #tmp1 where COl2 = @PFNUMBER and COL12 = (case when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end) and COL4 = '400'),''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,
						   COL2 = ISNULL(@PFNUMBER,''),
						   COL3 = CONVERT(VARCHAR(100), '1 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'411'),
						   COL5 = CONVERT(VARCHAR(4),''),
						   COL6 = 0,
						   COL7 = 0,
						   COL8 = 0,
						   COL9 = 0,
						   COL10 = ISNULL((select TOP 1 COL10 from #tmp1 where COl2 = @PFNUMBER and COL12 = (case when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end) and COL4 = '400'),''), 
						   COL11 = ISNULL((select TOP 1 COL11 from #tmp1 where COl2 = @PFNUMBER and COL12 = (case when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end) and COL4 = '400'),''), 
						   COL12 = ISNULL((case WHEN @TYPE = 1 then 'Исходная' when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end), ''), 
						   COL13 = ISNULL((select TOP 1 COL13 from #tmp1 where COl2 = @PFNUMBER and COL12 = (case when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end) and COL4 = '400'),''), 
						   COL14 = ISNULL((select TOP 1 COL14 from #tmp1 where COl2 = @PFNUMBER and COL12 = (case when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end) and COL4 = '400'),''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,
						   COL2 = ISNULL(@PFNUMBER,''), 
						   COL3 = CONVERT(VARCHAR(100), '2 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'412'),
						   COL5 = CONVERT(VARCHAR(4),''),
						   COL6 = 0,
						   COL7 = 0,
						   COL8 = 0,
						   COL9 = 0,
						   COL10 = ISNULL((select TOP 1 COL10 from #tmp1 where COl2 = @PFNUMBER and COL12 = (case when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end) and COL4 = '400'),''), 
						   COL11 = ISNULL((select TOP 1 COL11 from #tmp1 where COl2 = @PFNUMBER and COL12 = (case when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end) and COL4 = '400'),''), 
						   COL12 = ISNULL((case WHEN @TYPE = 1 then 'Исходная' when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end), ''), 
						   COL13 = ISNULL((select TOP 1 COL13 from #tmp1 where COl2 = @PFNUMBER and COL12 = (case when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end) and COL4 = '400'),''), 		
						   COL14 = ISNULL((select TOP 1 COL14 from #tmp1 where COl2 = @PFNUMBER and COL12 = (case when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end) and COL4 = '400'),''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					
					set @nom_pp = @nom_pp + 1		
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13, COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp, 
						   COL2 = ISNULL(@PFNUMBER,''),
						   COL3 = CONVERT(VARCHAR(100), '3 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'413'),
						   COL5 = CONVERT(VARCHAR(4),''),
						   COL6 = 0,
						   COL7 = 0,
						   COL8 = 0,
						   COL9 = 0,
						   COL10 = ISNULL((select TOP 1 COL10 from #tmp1 where COl2 = @PFNUMBER and COL12 = (case when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end) and COL4 = '400'),''), 
						   COL11 = ISNULL((select TOP 1 COL11 from #tmp1 where COl2 = @PFNUMBER and COL12 = (case when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end) and COL4 = '400'),''), 
						   COL12 = ISNULL((case WHEN @TYPE = 1 then 'Исходная' when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end), ''), 
						   COL13 = ISNULL((select TOP 1 COL13 from #tmp1 where COl2 = @PFNUMBER and COL12 = (case when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end) and COL4 = '400'),''), 
						   COL14 = ISNULL((select TOP 1 COL14 from #tmp1 where COl2 = @PFNUMBER and COL12 = (case when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end) and COL4 = '400'),''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
						   
					
					set @nom_pp = @nom_pp + 1	
				
				end 

					set @pf_num1 = @PFNUMBER
					set @CODE_old = @CODE
					set @TYPE_OLD = @TYPE
			END

			FETCH NEXT FROM @Cur2 INTO @CODE,@TYPE/*,@T_DOG*/,@PFNUMBER,@FM,@IM,@OT
		END

		CLOSE @Cur2
		DEALLOCATE @Cur2
		
	 
        
		SELECT DISTINCT * FROM #TMP1 where col5 <> '' ORDER BY  CODE/*, col2, col4 */, COL15

		

				
		drop table #TMP1

	END  
	IF @REP = 2 
	BEGIN 	
		/*Информация по раздеру 6.6 Информация о корректирующих сведениях*/
		/*К Исходным  заполняется в формах  с типом сведений «исходная» в случае, если в последние три месяца отчетного периода плательщиком страховых взносов 
		* корректируются данные, представленные в предыдущие отчетные периоды.При наличии данных в подразделе 6.6 дополнительно, 
		* в обязательном порядке предоставляются корректирующие (отменяющие)  разделы 6 и (или)  формы СЗВ-6-1, и (или) СЗВ-6-2, и (или) СЗВ-6-4.
		*/
		/*Заполняются в исходных , если есть по ним корректирующие */
		
		create table #TMP2(CODE int identity(1,1) ,col1 int,   COL2 tinyint, COL3 varchar(4), COL4 numeric(18,2), COL5 numeric(18,2), COL6 numeric(18,2), COL7 VARCHAR(14), COL8 INT)

		INSERT INTO #TMP2 (COL2, COL3, COL4, COL5, COL6, COL7)
		SELECT 
			   COL2 = [PER_EDT], 
			   COL3 = CONVERT(VARCHAR(4),YEAR_EDT),
			   COL4 = (CASE WHEN YEAR_EDT = '2014' THEN INSUR ELSE 0 END ),
			   COL5 = (CASE WHEN YEAR_EDT < '2014' THEN INSUR ELSE 0 END ),
			   COL6 = (CASE WHEN YEAR_EDT < '2014' THEN GAIN ELSE 0 END ),
			   COL7 = CONVERT(VARCHAR(14),PFNUMBER)
		FROM #SZV_ALL WHERE  [TYPE] = 2  AND id_ex =1 
		ORDER BY [FM],[IM],[OT],[PFNUMBER]
		
		UPDATE #TMP2 
			SET col1 = CODE , COL8 = CODE 

		
		SELECT * FROM #TMP2 ORDER BY CODE
		
		drop table #TMP2
		--GROUP BY [TYPE],CODE, [T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[per_edt],[year_edt]	
		
	END	
		
	IF @REP = 3 
	BEGIN 	
		/*Информация по раздеру 6.7 Сведения о сумме выплат и иных вознаграждений в пользу физического лица, занятого на соответствующих видах работ, 
		* с которых начислены страховые взносы по дополнительному тарифу для отдельных категорий плательщиков страховых взносов, указанных в частях 1, 2 и 2.1 статьи 58.3 
		* Федерального закона от 24 июля 2009 г. № 212-ФЗ */

	/*****************************************************/
	-- Собираем информацию по Исходным пачками
	/*****************************************************/
			
	   DECLARE @nYEAR INT, @nMONTH1 INT, @nMONTH2 INT, @nMONTH3 INT

		
		SELECT 
			@nYEAR = YEAR(@dDATE1),
			@nMONTH1 = MONTH(@dDATE1),
			@nMONTH2 = MONTH(@dDATE1)+1,
			@nMONTH3 = MONTH(@dDATE1)+2

		DECLARE @BYear_Date	datetime
			SET @BYear_Date = dbo.DateBeginOfYear (@dDate1)

		create table #SPR_ESN ([MONTH_BASE] TINYINT, SUMMA_BASE numeric(12,2) default 0.00, DED_M numeric(12,2) default 0.00, INV_M numeric(12,2) default 0.00, SUMMA numeric(12,2) default 0.00, WAY_CALC int default 0.00, REF_PHYS_PERS int default 0 , PF_NUM VARCHAR (14), FACE_GROUP TINYINT, I TINYINT, E TINYINT , SP VARCHAR(4))

		Insert InTo #SPR_ESN ([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS , PF_NUM, FACE_GROUP, I, E, SP)
		Select [MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, p.INSUR_NUM ,
			( CASE WHEN P.RESIDENT = 0 THEN 3 
				   WHEN YEAR(birthdate)<= 1966 THEN 1 
				   WHEN YEAR(birthdate)>= 1967 THEN 2 END ) AS FACE_GROUP, 
			dbo.is_invalid(REF_PHYS_PERS,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH_BASE,@nYEAR))),
			F.ENVD,
			SP = isnull(s4.code,'')
		from dbo.SA_ESN_VIEW(@nYEAR, @nMONTH3, @LINK_DEP, 0) S
			inner join PERSON P on S.REF_PHYS_PERS = P.link
			inner join dbo.SAL_SFIN F on F.LINK = S.LINK_VKR
			LEFT JOIN SA_SZV4_SPR  s4 ON  s4.link = S.SPECO  AND s4.spr_code = 'SPO_USL_TRUDA'
		WHERE  WAY_CALC not in (5)

		--Суммы по договорникам
		INSERT INTO #SPR_ESN 
			([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, PF_NUM, FACE_GROUP, I, E)
		SELECT 
			MONTH(G.[DATE]) AS MONTH_BASE, GT.SUMMA_BASE, 0, 0, GT.SUMMA, GT.WAY_CALC, GT.PERS_LINK, p.INSUR_NUM ,
			( CASE WHEN P.RESIDENT = 0  THEN 3
				   WHEN YEAR(birthdate)<= 1966 THEN 1 
				   WHEN YEAR(birthdate)>= 1967 THEN 2 END) AS FACE_GROUP , 
			dbo.is_invalid(GT.PERS_LINK,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,G.[MONTH],@nYEAR))),
			F.ENVD
			
		FROM 
			DOCUMENTS_DGH G INNER JOIN DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
			inner join PERSON P on GT.PERS_LINK = P.link
			inner join dbo.SAL_SFIN F on F.LINK = GT.LINK_VKR
		WHERE 
			FLAG_JC = 1
			AND GT.WAY_CALC  not in (5)
			AND YEAR(G.[DATE]) = @nYEAR
			AND MONTH(G.[DATE]) <= @nMONTH3
			AND LINK_DEP = @DEP_LINK


		DELETE FROM #SPR_ESN
		WHERE  EXISTS (SELECT * FROM dbo.KJ_PERS_PENSION K WHERE K.PERS_LINK = REF_PHYS_PERS  and K.CHECK_SZV = 0)

	
		UPDATE #SZV_ALL
			SET [OSOB_SPO] =  SP 
			FROM #SPR_ESN  WHERE pf_num = #SZV_ALL.[PFNUMBER] AND WAY_CALC IN (10,11) AND MONTH_BASE = @nMONTH3   and SUMMA_BASE <> 0        



		create table #TMP3(CODE int,col1 int,   COL2 varchar(100), COL3 varchar(4), COL4 varchar (4), COL5 numeric(18,2), COL6 numeric(18,2), COL7 VARCHAR(14), COL8 int, COL9 int, 
							COL10 VARCHAR(10), COL11 VARCHAR(10), COL12 VARCHAR(10),COL13 VARCHAR(20), COL14 VARCHAR(10), COL15 VARCHAR(100), COL16 VARCHAR(10),COL17 VARCHAR(100),
							COL18 VARCHAR(10), COL19 VARCHAR(10), COL20 VARCHAR(10),COL21 VARCHAR(20), COL22 VARCHAR(10), COL23 VARCHAR(100), COL24 VARCHAR(10), COL25 VARCHAR(100), 
							COL26 VARCHAR(10), COL27 VARCHAR(10), COL28 VARCHAR(10),COL29 VARCHAR(20), COL30 VARCHAR(10), COL31 VARCHAR(100), COL32 VARCHAR(10), COL33 VARCHAR(100),
							COL34 VARCHAR(10), COL35 VARCHAR(10), COL36 VARCHAR(10), COL37 VARCHAR(20), COL38 VARCHAR(10), COL39 VARCHAR(100), COL40 VARCHAR(10), COL41 VARCHAR(100), COL42 varchar(100), COL43 varchar(100), COL44 varchar(100))


		
		DECLARE @Cur3 CURSOR, @CODE1 varchar(4), @TYPE1 tinyint , @PFNUMBER1 VARCHAR (14) , @FM1 VARCHAR(100),@IM1 VARCHAR(100),@OT1 VARCHAR(100),
		@pf_num11 VARCHAR(14) ,@TYPE_OLD1 TINYINT, @nom_pp1 INT, @OSOB_SPO VARCHAR(4), @OSOB_SPO_old VARCHAR(4),
		@DateM1B DATETIME, @DateM2B DATETIME, @DateM3B DATETIME, @DateM1E DATETIME, @dateM2E DATETIME, @dateM3E DATETIME
		set @pf_num11 = ''
		set @OSOB_SPO_old = NULL 
		set @TYPE_OLD1 = 0
		set @nom_pp1 = 1
		
		SELECT @DateM1B = @dDate1,
			   @DateM2B =  dbo.ConvertDMY2Date(1,month(@dDate1)+1,YEAR(@dDate1)), 	
			   @DateM3B =  dbo.ConvertDMY2Date(1,month(@dDate1)+2,YEAR(@dDate1)), 
			   @DateM1E =  dbo.DateEndOfMonth(@DateM1B),
			   @DateM2E =  dbo.DateEndOfMonth(@DateM2B), 	
			   @DateM3E =  @dDate2
	
	
		SET @Cur3 = CURSOR FORWARD_ONLY
		FOR SELECT  [CODE],[TYPE],[PFNUMBER], [FM],[IM],[OT], [OSOB_SPO]  FROM #SZV_ALL where /*T_DOG = 1 and*/ [TYPE] = 1  GROUP BY [FM],[IM],[OT],[PFNUMBER],[TYPE],CODE, [OSOB_SPO] ORDER BY [FM],[IM],[OT],[PFNUMBER],[TYPE],CODE, [OSOB_SPO]
		OPEN @Cur3
		FETCH NEXT FROM @Cur3 INTO  @CODE1,@TYPE1,@PFNUMBER1,@FM1,@IM1,@OT1, @OSOB_SPO
		WHILE (@@fetch_status <> -1)
		BEGIN

			IF (@@fetch_status <> -2)
			BEGIN
				
				SELECT @OSOB_SPO = ISNULL(@OSOB_SPO, '')
				select @OSOB_SPO_old = ISNULL(@OSOB_SPO_old, '')
				--- Заполнение информации по первому коду категории сотрудника (нр , оои, пнэд)
				IF (ltrim(rtrim(@PFNUMBER1)) <> ltrim(rtrim(@pf_num11)) ) 
				BEGIN

					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42, COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), 'Всего с начала расчетного периода, в том числе за последние три месяца отчетного периода:'),	
						   COL3 = CONVERT(VARCHAR(4),'700'),
						   COL4 = CONVERT(VARCHAR(4),ISNULL(s.OSOB_SPO,'')),
						   COL5 = CASE WHEN PER = 1 THEN  ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																+ (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																+ (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  ,0)
										WHEN PER = 2 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																 + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																 + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  ,0)
										WHEN PER = 3 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																 + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																 + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)) 
																 + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																 + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)) ,0)
													ELSE ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																+ (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																+ (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																+ (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																+ (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)) 
																+ (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																+ (sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 10 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 10 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 11 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 11 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 12 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 12 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)),0)
									END ,
						   COL6 = CASE WHEN PER = 1 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))  ,0)
									   WHEN PER = 2 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))  ,0)
									   WHEN PER = 3 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   ,0)  
													ELSE ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END)) 
															   + (sum(CASE WHEN MONTH_BASE= 10 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 10 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 11 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 11 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 12 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 12 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   ,0)  
								  END,
						   COL7 = ISNULL([PFNUMBER],0),
						   COL8 = @nom_pp1,
						   COL9 = [TYPE], 
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
						   
					FROM #SZV_ALL s
					left JOIN #SPR_ESN  e ON 	e.PF_NUM = s.PFNUMBER AND ISNULL(e.SP,'') = ISNULL(s.OSOB_SPO,'') AND e.WAY_CALC IN (10,11)					
					WHERE  s.code = @CODE1 and s.[TYPE] = @TYPE1 AND s.PFNUMBER = @PFNUMBER1 AND ISNULL(s.OSOB_SPO,'') = @OSOB_SPO  AND s.ID_EX = 1
					GROUP BY [TYPE],CODE,[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt], INC_T1M1,INC_T1M2,INC_T1M3, INC_T2M1,INC_T2M2,INC_T2M3 ,s.OSOB_SPO,E.SP, e.PF_NUM 
		
					SELECT  @nom_pp1 = @nom_pp1 + 1
					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '1 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'701'),
						   COL4 = CONVERT(VARCHAR(4),ISNULL(s.OSOB_SPO,'')),
						   COL5 = ISNULL( (sum(CASE WHEN MONTH_BASE= month(@DateM1E) AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END)- sum(CASE WHEN MONTH_BASE= month(@DateM1E) AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   ,0),
						   COL6 = ISNULL( (sum(CASE WHEN MONTH_BASE= month(@DateM1E) AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END)- sum(CASE WHEN MONTH_BASE= month(@DateM1E) AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))  ,0),
						   COL7 = ISNULL([PFNUMBER],0),
						   COL8 = @nom_pp1,
						   COL9 = [TYPE],
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					FROM #SZV_ALL s
					left JOIN #SPR_ESN  e ON 	e.PF_NUM = s.PFNUMBER AND ISNULL(e.SP,'') = ISNULL(s.OSOB_SPO,'') AND e.WAY_CALC IN (10,11)		
					WHERE  code = @CODE1 and [TYPE] = @TYPE1 AND PFNUMBER = @PFNUMBER1 AND ISNULL(OSOB_SPO,'') = @OSOB_SPO AND s.ID_EX = 1
					GROUP BY [TYPE],CODE,[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt], INC_T1M1,INC_T1M2,INC_T1M3, INC_T2M1,INC_T2M2,INC_T2M3,s.OSOB_SPO,E.SP, e.PF_NUM 
					
				




					
					set @nom_pp1 = @nom_pp1 + 1
					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '2 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'702'),
						   COL4 = CONVERT(VARCHAR(4),ISNULL(s.OSOB_SPO,'')),
						   COL5 = ISNULL( (sum(CASE WHEN MONTH_BASE= month(@DateM2E) AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= month(@DateM2E) AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   ,0),
						   COL6 = ISNULL( (sum(CASE WHEN MONTH_BASE= month(@DateM2E) AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= month(@DateM2E) AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))  ,0),
						   COL7 = ISNULL([PFNUMBER],0),
						   COL8 = @nom_pp1,
						   COL9 = [TYPE],
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					FROM #SZV_ALL s
					left JOIN #SPR_ESN  e ON 	e.PF_NUM = s.PFNUMBER AND ISNULL(e.SP,'') = ISNULL(s.OSOB_SPO,'') AND e.WAY_CALC IN (10,11)	
					WHERE  code = @CODE1 and [TYPE] = @TYPE1  AND PFNUMBER = @PFNUMBER1 AND ISNULL(OSOB_SPO,'') = @OSOB_SPO AND s.ID_EX = 1
					GROUP BY [TYPE],CODE,[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt], INC_T1M1,INC_T1M2,INC_T1M3, INC_T2M1,INC_T2M2,INC_T2M3,s.OSOB_SPO,E.SP, e.PF_NUM 
					
					set @nom_pp1 = @nom_pp1 + 1

					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '3 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'703'),
						   COL4 = CONVERT(VARCHAR(4),ISNULL(s.OSOB_SPO,'')),
						   COL5 = ISNULL((sum(CASE WHEN MONTH_BASE= month(@DateM3E) AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= month(@DateM3E) AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  ,0),
						   COL6 = ISNULL( ( sum(CASE WHEN MONTH_BASE= month(@DateM3E) AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= month(@dateM3E) AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))  ,0),
						   COL7 = ISNULL([PFNUMBER],0),
						   COL8 = @nom_pp1,
						   COL9 = [TYPE],
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					FROM #SZV_ALL s
					left JOIN #SPR_ESN  e ON 	e.PF_NUM = s.PFNUMBER AND ISNULL(e.SP,'') = ISNULL(s.OSOB_SPO,'') AND e.WAY_CALC IN (10,11)	
					WHERE  code = @CODE1 and [TYPE] = @TYPE1 AND PFNUMBER = @PFNUMBER1 AND ISNULL(OSOB_SPO,'') = @OSOB_SPO AND s.ID_EX = 1
					GROUP BY [TYPE],CODE,[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt], INC_T1M1,INC_T1M2,INC_T1M3, INC_T2M1,INC_T2M2,INC_T2M3	,s.OSOB_SPO,E.SP, e.PF_NUM 
					
					set @nom_pp1 = @nom_pp1 + 1
				
				END
					
				
				--- Заполнение информации по следующему коду категории сотрудника (если за расчетный период у сотрудника была не одна категория)
				IF @PFNUMBER1 = @pf_num11 and @OSOB_SPO <> @OSOB_SPO_old
				BEGIN 
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), 'Всего с начала расчетного периода, в том числе за последние три месяца отчетного периода:'),	
						   COL3 = CONVERT(VARCHAR(4),'710'),
						   COL4 = CONVERT(VARCHAR(4),ISNULL(s.OSOB_SPO,'')),
						   COL5 = CASE WHEN PER = 1 THEN  ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																+ (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																+ (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  ,0)
										WHEN PER = 2 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																 + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																 + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  ,0)
										WHEN PER = 3 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																 + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																 + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)) 
																 + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																 + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)) ,0)
													ELSE ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																+ (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																+ (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																+ (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																+ (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)) 
																+ (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																+ (sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 10 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 10 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 11 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 11 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 12 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 12 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)),0)
									END ,
						   COL6 = CASE WHEN PER = 1 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))  ,0)
									   WHEN PER = 2 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))  ,0)
									   WHEN PER = 3 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   ,0)  
													ELSE ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END)) 
															   + (sum(CASE WHEN MONTH_BASE= 10 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 10 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 11 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 11 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 12 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 12 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   ,0)  
								  END,
						   COL7 = ISNULL([PFNUMBER],0),
						   COL8 = @nom_pp1,
						   COL9 = [TYPE],
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					FROM #SZV_ALL s
					left JOIN #SPR_ESN  e ON 	e.PF_NUM = s.PFNUMBER AND ISNULL(e.SP,'') = ISNULL(s.OSOB_SPO,'') AND e.WAY_CALC IN (10,11)	
					WHERE  code = @CODE1 and [TYPE] = @TYPE1 AND PFNUMBER = @PFNUMBER1 AND ISNULL(OSOB_SPO,'') = @OSOB_SPO AND s.ID_EX = 1
					GROUP BY [TYPE],CODE,[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt], INC_T1M1,INC_T1M2,INC_T1M3, INC_T2M1,INC_T2M2,INC_T2M3,date_end,s.OSOB_SPO,E.SP, e.PF_NUM 
					
					set @nom_pp1 = @nom_pp1 + 1
					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '1 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'711'),
						   COL4 = CONVERT(VARCHAR(4),ISNULL(s.OSOB_SPO,'')),
						   COL5 = ISNULL((sum(CASE WHEN MONTH_BASE= month(@DateM1E) AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END)- sum(CASE WHEN MONTH_BASE= month(@DateM1E) AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)),0),
						   COL6 = ISNULL( ( sum(CASE WHEN MONTH_BASE= month(@DateM1E) AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END)- sum(CASE WHEN MONTH_BASE= month(@DateM1E) AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END)),0),
						   COL7 = ISNULL([PFNUMBER],0),
						   COL8 = @nom_pp1,
						   COL9 = [TYPE],
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					FROM #SZV_ALL s
					left JOIN #SPR_ESN  e ON 	e.PF_NUM = s.PFNUMBER AND ISNULL(e.SP,'') = ISNULL(s.OSOB_SPO,'') AND e.WAY_CALC IN (10,11)	
					WHERE  code = @CODE1 and [TYPE] = @TYPE1  AND PFNUMBER = @PFNUMBER1 AND ISNULL(OSOB_SPO,'') = @OSOB_SPO AND s.ID_EX = 1
					GROUP BY [TYPE],CODE,[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt], INC_T1M1,INC_T1M2,INC_T1M3, INC_T2M1,INC_T2M2,INC_T2M3,date_end,s.OSOB_SPO,E.SP, e.PF_NUM 
					
					set @nom_pp1 = @nom_pp1 + 1
					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '2 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'712'),
						   COL4 = CONVERT(VARCHAR(4),ISNULL(s.OSOB_SPO,'')),
						   COL5 = ISNULL((sum(CASE WHEN MONTH_BASE= month(@DateM2E) AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= month(@DateM2E) AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)),0),
						   COL6 = ISNULL( ( sum(CASE WHEN MONTH_BASE= month(@DateM2E) AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= month(@DateM2E) AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END)),0),
						   COL7 = ISNULL([PFNUMBER],0),
						   COL8 = @nom_pp1,
						   COL9 = [TYPE],
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					FROM #SZV_ALL  s
					left JOIN #SPR_ESN  e ON 	e.PF_NUM = s.PFNUMBER AND ISNULL(e.SP,'') = ISNULL(s.OSOB_SPO,'') AND e.WAY_CALC IN (10,11)	
					WHERE  code = @CODE1 and [TYPE] = @TYPE1 AND PFNUMBER = @PFNUMBER1 AND ISNULL(OSOB_SPO,'') = @OSOB_SPO AND s.ID_EX = 1
					GROUP BY [TYPE],CODE,[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt],INC_T1M1,INC_T1M2,INC_T1M3, INC_T2M1,INC_T2M2,INC_T2M3,date_end	,s.OSOB_SPO,E.SP, e.PF_NUM 	
					
					set @nom_pp1 = @nom_pp1 + 1
					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '3 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'713'),
						   COL4 = CONVERT(VARCHAR(4),ISNULL(s.OSOB_SPO,'')),
						   COL5 = ISNULL((sum(CASE WHEN MONTH_BASE= month(@DateM3E) AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END)- sum(CASE WHEN MONTH_BASE= month(@DateM3E) AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)),0),
						   COL6 = ISNULL( ( sum(CASE WHEN MONTH_BASE= month(@DateM3E) AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= month(@DateM3E) AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END)),0),
						   COL7 = ISNULL([PFNUMBER],0),
						   COL8 = @nom_pp1,
						   COL9 = [TYPE],
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					FROM #SZV_ALL s
					left JOIN #SPR_ESN  e ON 	e.PF_NUM = s.PFNUMBER AND ISNULL(e.SP,'') = ISNULL(s.OSOB_SPO,'') AND e.WAY_CALC IN (10,11)	
					WHERE  code = @CODE1 and [TYPE] = @TYPE1 AND PFNUMBER = @PFNUMBER1 AND ISNULL(OSOB_SPO,'') = @OSOB_SPO AND s.ID_EX = 1
					GROUP BY [TYPE],CODE,[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt],INC_T1M1,INC_T1M2,INC_T1M3, INC_T2M1,INC_T2M2,INC_T2M3,date_end,s.OSOB_SPO,E.SP, e.PF_NUM 
					
					set @nom_pp1 = @nom_pp1 + 1
				END						

				--- заполняем пустые строки '410','411','412','413' 
		
				if not exists (select * from #tmp3 
								where COL7 = @PFNUMBER1 
								and COL9 = @TYPE1
								and COL4 = '710' ) AND NOT EXISTS (SELECT * FROM #SZV_ALL WHERE PFNUMBER = @PFNUMBER1 AND ISNULL(OSOB_SPO,'') != ISNULL(@OSOB_SPO,'') AND [TYPE] = 1) 
				begin 
						
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT 
						   CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), 'Всего с начала расчетного периода, в том числе за последние три месяца отчетного периода:'),	
						   COL3 = CONVERT(VARCHAR(4),'710'),
						   COL4 = CONVERT(VARCHAR(4),''),
						   COL5 = 0,
						   COL6 = 0,
						   COL7 = ISNULL(@PFNUMBER1,''),
						   COL8 = @nom_pp1,
						   COL9 = @TYPE1,
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					
					
					set @nom_pp1 = @nom_pp1 + 1
					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '1 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'711'),
						   COL4 = CONVERT(VARCHAR(4),''),
						   COL5 = 0,
						   COL6 = 0,
						   COL7 = ISNULL(@PFNUMBER1,''),
						   COL8 = @nom_pp1,
						   COL9 = @TYPE1,
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					
					set @nom_pp1 = @nom_pp1 + 1
					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '2 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'712'),
						   COL4 = CONVERT(VARCHAR(4),''),
						   COL5 = 0,
						   COL6 = 0,
						   COL7 = ISNULL(@PFNUMBER1,''),
						   COL8 = @nom_pp1,
						   COL9 = @TYPE1,
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					
					set @nom_pp1 = @nom_pp1 + 1		
					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '3 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'713'),
						   COL4 = CONVERT(VARCHAR(4),''),
						   COL5 = 0,
						   COL6 = 0,
						   COL7 = ISNULL(@PFNUMBER1,''),
						   COL8 = @nom_pp1,
						   COL9 = @TYPE1,
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					
					set @nom_pp1 = @nom_pp1 + 1	
				end 

					select	row_number() over (order by DATE_BEGIN) as ID ,
							FM1 = [FM]  ,
							IM1 = [IM],
							OT1 = [OT],
							PFNUMBER1 = [PFNUMBER], 
							T_DOG1= T_DOG,
							TYPE1 = [TYPE], 
							DATE_BEGIN1 = [DATE_BEGIN], 
							DATE_END1 = (CASE WHEN [DATE_END]> @dDate2 THEN @dDate2 ELSE [DATE_END] end) , 
							TU_CODE1 = [TU_CODE], 
							OS_CODE1 = [OS_CODE], 
							EX_CODE1 = [EX_CODE], 
							f_is_dop1 = [f_is_dop], 
							P_CODE1 = [P_CODE], 
							f_ud_dop1 = [f_ud_dop] 
					into #TMP03
					FROM #SZV_ALL  WHERE  id_ex IS NOT NULL  AND YEAR(@dDate1)<=YEAR(Date_END) and MONTH(@dDate2) >= MONTH(Date_END) and MONTH(@dDate2) >= MONTH(Date_BEGIN) and [TYPE] = @TYPE1 AND PFNUMBER = @PFNUMBER1 and fm = @FM1 and T_DOG = 1
					GROUP BY [FM],[IM],[OT],[PFNUMBER], T_DOG,[TYPE], [DATE_BEGIN], [DATE_END] , [TU_CODE], [OS_CODE], [EX_CODE], [f_is_dop], [P_CODE], [f_ud_dop]
					ORDER BY  [FM],[IM],[OT],[PFNUMBER], T_DOG,[TYPE]
					
					
					UPDATE #TMP3
					set COL10 = (SELECT distinct convert(varchar(10),DATE_BEGIN1,104 ) FROM #TMP03 where ID=1 and FM1= @FM1),
						COL11 = (SELECT distinct convert(varchar(10),DATE_END1,104 ) FROM #TMP03 where ID=1 and FM1= @FM1),
						COL12 = (SELECT distinct convert(varchar(10),TU_CODE1 ) FROM #TMP03 where ID=1 and FM1= @FM1) ,
						COL13 = (SELECT distinct convert(varchar(20),OS_CODE1 ) FROM #TMP03 where ID=1 and FM1= @FM1),
						COL14 = (SELECT distinct convert(varchar(10),EX_CODE1 ) FROM #TMP03 where ID=1 and FM1= @FM1), 
						COL15 = (SELECT distinct convert(varchar(100),f_is_dop1 ) FROM #TMP03 where ID=1 and FM1= @FM1),
					    COL16 = (SELECT distinct convert(varchar(10),P_CODE1) FROM #TMP03 where ID=1 and FM1= @FM1), 
					    COL17 = (SELECT distinct convert(varchar(100),f_ud_dop1) FROM #TMP03 where ID=1 and FM1= @FM1), 
					    COL18 = (SELECT distinct convert(varchar(10),DATE_BEGIN1,104 ) FROM #TMP03 where ID=2 and FM1= @FM1), 
					    COL19 = (SELECT distinct convert(varchar(10),DATE_END1,104 ) FROM #TMP03 where ID=2 and FM1= @FM1),
					    COL20 = (SELECT distinct convert(varchar(10),TU_CODE1 ) FROM #TMP03 where ID=2 and FM1= @FM1),
					    COL21 = (SELECT distinct convert(varchar(20),OS_CODE1 ) FROM #TMP03 where ID=2 and FM1= @FM1),
						COL22 = (SELECT distinct convert(varchar(10),EX_CODE1 ) FROM #TMP03 where ID=2 and FM1= @FM1), 
						COL23 = (SELECT distinct convert(varchar(100),f_is_dop1 ) FROM #TMP03 where ID=2 and FM1= @FM1),
					    COL24 = (SELECT distinct convert(varchar(10),P_CODE1) FROM #TMP03 where ID=2 and FM1= @FM1), 
					    COL25 = (SELECT distinct convert(varchar(100),f_ud_dop1) FROM #TMP03 where ID=2 and FM1= @FM1),
					    COL26 = (SELECT distinct convert(varchar(10),DATE_BEGIN1,104 ) FROM #TMP03 where ID=3 and FM1= @FM1), 
					    COL27 = (SELECT distinct convert(varchar(10),DATE_END1,104 ) FROM #TMP03 where ID=3 and FM1= @FM1),
					    COL28 = (SELECT distinct convert(varchar(10),TU_CODE1 ) FROM #TMP03 where ID=3 and FM1= @FM1),
					    COL29 = (SELECT distinct convert(varchar(20),OS_CODE1 ) FROM #TMP03 where ID=3 and FM1= @FM1),
						COL30 = (SELECT distinct convert(varchar(10),EX_CODE1 ) FROM #TMP03 where ID=3 and FM1= @FM1), 
						COL31 = (SELECT distinct convert(varchar(100),f_is_dop1 ) FROM #TMP03 where ID=3 and FM1= @FM1),
					    COL32 = (SELECT distinct convert(varchar(10),P_CODE1) FROM #TMP03 where ID=3 and FM1= @FM1), 
					    COL33 = (SELECT distinct convert(varchar(100),f_ud_dop1) FROM #TMP03 where ID=3 and FM1= @FM1),
					    COL34 = (SELECT distinct convert(varchar(10),DATE_BEGIN1,104 ) FROM #TMP03 where ID=4 and FM1= @FM1), 
					    COL35 = (SELECT distinct convert(varchar(10),DATE_END1,104 ) FROM #TMP03 where ID=4 and FM1= @FM1),
					    COL36 = (SELECT distinct convert(varchar(10),TU_CODE1 ) FROM #TMP03 where ID=4 and FM1= @FM1),
					    COL37 = (SELECT distinct convert(varchar(20),OS_CODE1 ) FROM #TMP03 where ID=4 and FM1= @FM1),
						COL38 = (SELECT distinct convert(varchar(10),EX_CODE1 ) FROM #TMP03 where ID=4 and FM1= @FM1), 
						COL39 = (SELECT distinct convert(varchar(100),f_is_dop1 ) FROM #TMP03 where ID=4 and FM1= @FM1),
					    COL40 = (SELECT distinct convert(varchar(10),P_CODE1) FROM #TMP03 where ID=4 and FM1= @FM1), 
					    COL41 = (SELECT distinct convert(varchar(100),f_ud_dop1) FROM #TMP03 where ID=4 and FM1= @FM1)
					from #TMP3	
					WHERE #TMP3.COL9 = @TYPE1 
					and #TMP3.COL7 = @PFNUMBER1  and #TMP3.COL3 = '700' /*and #TMP3.CODE =  @nom_pp1*/

					drop table #TMP03				

					set @pf_num11 = @PFNUMBER1
					set @OSOB_SPO_old = @OSOB_SPO
					set @TYPE_OLD1 = @TYPE1
					
			
			END

			FETCH NEXT FROM @Cur3 INTO @CODE1,@TYPE1,@PFNUMBER1,@FM1,@IM1,@OT1, @OSOB_SPO
		END

		CLOSE @Cur3
		DEALLOCATE @Cur3
		
		
		
		
		/*****************************************************/
		-- Собираем информацию по Кореектирующим/Отменяющим
		/*****************************************************/
		--create table #TMP1(CODE int,col1 int,   COL2 varchar(14), COL3 varchar(100), COL4 varchar (4), COL5 varchar (4), COL6 numeric(18,2), COL7 numeric(18,2), COL8 numeric(18,2), COL9 numeric(18,2), COL10 varchar(1), COL11 varchar(4), COL12 varchar(15), COL13 varchar(1), COL14 varchar(4),COL15 int)
	
		DECLARE @Cur4 CURSOR
		set @pf_num11 = ''
		set @OSOB_SPO_old = ''  
		set @TYPE_OLD1 = 0
		set @nom_pp1 = (SELECT MAX(CODE) FROM #TMP3 WHERE COL9 = 1) + 1 
		
		SET @Cur4 = CURSOR FORWARD_ONLY
		FOR SELECT  [CODE],[TYPE],[PFNUMBER], [FM],[IM],[OT], [OSOB_SPO]  FROM #SZV_ALL where /*T_DOG = 1 and */[TYPE] != 1  GROUP BY [CODE],[TYPE],[PFNUMBER], [FM],[IM],[OT], [OSOB_SPO]ORDER BY [CODE],[TYPE],[PFNUMBER], [FM],[IM],[OT], [OSOB_SPO]
		OPEN @Cur4
		FETCH NEXT FROM @Cur4 INTO  @CODE1,@TYPE1,@PFNUMBER1,@FM1,@IM1,@OT1, @OSOB_SPO
		WHILE (@@fetch_status <> -1)
		BEGIN

			IF (@@fetch_status <> -2)
			BEGIN
				
				SELECT @OSOB_SPO = ISNULL(@OSOB_SPO, '')
				select @OSOB_SPO_old = ISNULL(@OSOB_SPO_old, '')	
				--- Заполнение информации по первому коду категории сотрудника (нр , оои, пнэд)
				IF (@PFNUMBER1 <> @pf_num11 ) 
				BEGIN
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), 'Всего с начала расчетного периода, в том числе за последние три месяца отчетного периода:'),	
						   COL3 = CONVERT(VARCHAR(4),'700'),
						   COL4 = CONVERT(VARCHAR(4),ISNULL(s.OSOB_SPO,'')),
						   COL5 = CASE WHEN PER = 1 THEN  ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																+ (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																+ (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  ,0)
										WHEN PER = 2 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																 + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																 + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  ,0)
										WHEN PER = 3 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																 + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																 + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)) 
																 + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																 + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)) ,0)
													ELSE ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																+ (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																+ (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																+ (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																+ (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)) 
																+ (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																+ (sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 10 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 10 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 11 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 11 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 12 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 12 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)),0)
									END ,
						   COL6 = CASE WHEN PER = 1 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))  ,0)
									   WHEN PER = 2 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))  ,0)
									   WHEN PER = 3 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   ,0)  
													ELSE ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END)) 
															   + (sum(CASE WHEN MONTH_BASE= 10 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 10 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 11 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 11 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 12 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 12 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   ,0)  
								  END,

						   COL7 = ISNULL([PFNUMBER],0),
						   COL8 = @nom_pp1,
						   COL9 = [TYPE],
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					FROM #SZV_ALL s
					left JOIN #SPR_ESN  e ON 	e.PF_NUM = s.PFNUMBER AND ISNULL(e.SP,'') = ISNULL(s.OSOB_SPO,'') AND e.WAY_CALC IN (10,11)	
					WHERE  code = @CODE1 and [TYPE] = @TYPE1 AND PFNUMBER = @PFNUMBER1 AND ISNULL(OSOB_SPO,'') = @OSOB_SPO  AND s.ID_EX = 1
					GROUP BY [TYPE],CODE,[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt], INC_T1M1,INC_T1M2,INC_T1M3, INC_T2M1,INC_T2M2,INC_T2M3 , date_end,s.OSOB_SPO,E.SP, e.PF_NUM 
					

					set @nom_pp1 = @nom_pp1 + 1
					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '1 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'701'),
						   COL4 = CONVERT(VARCHAR(4),ISNULL(s.OSOB_SPO,'')),
						   COL5 = ISNULL((sum(CASE WHEN MONTH_BASE= month(@DateM1E) AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END)- sum(CASE WHEN MONTH_BASE= month(@DateM1E) AND e.WAY_CALC = 10 THEN DED_M + INV_M  ELSE 0 END)),0),
						   COL6 = ISNULL( ( sum(CASE WHEN MONTH_BASE= month(@DateM1E) AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END)- sum(CASE WHEN MONTH_BASE= month(@DateM1E) AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END)),0),
						   COL7 = ISNULL([PFNUMBER],0),
						   COL8 = @nom_pp1,
						   COL9 = [TYPE],
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					FROM #SZV_ALL s
					left JOIN #SPR_ESN  e ON 	e.PF_NUM = s.PFNUMBER AND ISNULL(e.SP,'') = ISNULL(s.OSOB_SPO,'') AND e.WAY_CALC IN (10,11)	
					WHERE  code = @CODE1 and [TYPE] = @TYPE1 AND PFNUMBER = @PFNUMBER1 AND ISNULL(OSOB_SPO,'') = @OSOB_SPO AND s.ID_EX = 1
					GROUP BY [TYPE],CODE,[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt],INC_T1M1,INC_T1M2,INC_T1M3, INC_T2M1,INC_T2M2,INC_T2M3,date_end ,s.OSOB_SPO,E.SP, e.PF_NUM 	
					
					set @nom_pp1 = @nom_pp1 + 1
					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '2 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'702'),
						   COL4 = CONVERT(VARCHAR(4),ISNULL(s.OSOB_SPO,'')),
						   COL5 = ISNULL((sum(CASE WHEN MONTH_BASE= month(@DateM2E) AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END)- sum(CASE WHEN MONTH_BASE= month(@DateM2E) AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)),0),
						   COL6 = ISNULL( ( sum(CASE WHEN MONTH_BASE= month(@DateM2E) AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END)- sum(CASE WHEN MONTH_BASE= month(@DateM2E) AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END)),0),
						   COL7 = ISNULL([PFNUMBER],0),
						   COL8 = @nom_pp1,
						   COL9 = [TYPE],
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					FROM #SZV_ALL s
					left JOIN #SPR_ESN  e ON 	e.PF_NUM = s.PFNUMBER AND ISNULL(e.SP,'') = ISNULL(s.OSOB_SPO,'') AND e.WAY_CALC IN (10,11)	
					WHERE  code = @CODE1 and [TYPE] = @TYPE1 AND PFNUMBER = @PFNUMBER1 AND ISNULL(OSOB_SPO,'') = @OSOB_SPO AND s.ID_EX = 1
					GROUP BY [TYPE],CODE,[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt],INC_T1M1,INC_T1M2,INC_T1M3, INC_T2M1,INC_T2M2,INC_T2M3,date_end	,s.OSOB_SPO,E.SP, e.PF_NUM 
					
					set @nom_pp1 = @nom_pp1 + 1
					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '3 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'703'),
						   COL4 = CONVERT(VARCHAR(4),ISNULL(s.OSOB_SPO,'')),
						   COL5 = ISNULL((sum(CASE WHEN MONTH_BASE= month(@DateM3E) AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END)- sum(CASE WHEN MONTH_BASE= month(@DateM3E) AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)),0),
						   COL6 = ISNULL( ( sum(CASE WHEN MONTH_BASE= month(@DateM3E) AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END)- sum(CASE WHEN MONTH_BASE= month(@DateM3E) AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END)),0),
						   COL7 = ISNULL([PFNUMBER],0),
						   COL8 = @nom_pp1,
						   COL9 = [TYPE],
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					FROM #SZV_ALL s
					left JOIN #SPR_ESN  e ON 	e.PF_NUM = s.PFNUMBER AND ISNULL(e.SP,'') = ISNULL(s.OSOB_SPO,'') AND e.WAY_CALC IN (10,11)	
					WHERE  code = @CODE1 and [TYPE] = @TYPE1 AND PFNUMBER = @PFNUMBER1 AND ISNULL(OSOB_SPO,'') = @OSOB_SPO AND s.ID_EX = 1
					GROUP BY [TYPE],CODE,[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]	,INC_T1M1,INC_T1M2,INC_T1M3, INC_T2M1,INC_T2M2,INC_T2M3,date_end,s.OSOB_SPO,E.SP, e.PF_NUM 		
					
					set @nom_pp1 = @nom_pp1 + 1
				END
					
				
				--- Заполнение информации по следующему коду категории сотрудника (если за расчетный период у сотрудника была не одна категория)
				IF @PFNUMBER1 = @pf_num11 and @OSOB_SPO <> @OSOB_SPO_old
				BEGIN 
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), 'Всего с начала расчетного периода, в том числе за последние три месяца отчетного периода:'),	
						   COL3 = CONVERT(VARCHAR(4),'710'),
						   COL4 = CONVERT(VARCHAR(4),ISNULL(s.OSOB_SPO,'')),
						   COL5 = CASE WHEN PER = 1 THEN  ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																+ (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																+ (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  ,0)
										WHEN PER = 2 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																 + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																 + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  ,0)
										WHEN PER = 3 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																 + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																 + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)) 
																 + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																 + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																 + (sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)) ,0)
													ELSE ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																+ (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																+ (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))  
																+ (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																+ (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)) 
																+ (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))   
																+ (sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 10 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 10 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 11 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 11 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END))
																+ (sum(CASE WHEN MONTH_BASE= 12 AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 12 AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)),0)
									END ,
						   COL6 = CASE WHEN PER = 1 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))  ,0)
									   WHEN PER = 2 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))  ,0)
									   WHEN PER = 3 THEN ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   ,0)  
													ELSE ISNULL( (sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 1 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 2 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 3 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 4 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 5 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 6 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))
															   + (sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 7 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 8 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 9 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END)) 
															   + (sum(CASE WHEN MONTH_BASE= 10 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 10 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))    
															   + (sum(CASE WHEN MONTH_BASE= 11 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 11 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   
															   + (sum(CASE WHEN MONTH_BASE= 12 AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END) - sum(CASE WHEN MONTH_BASE= 12 AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END))   ,0)  
								  END,						   COL7 = ISNULL([PFNUMBER],0),
						   COL8 = @nom_pp1,
						   COL9 = [TYPE],
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					FROM #SZV_ALL s
					left JOIN #SPR_ESN  e ON 	e.PF_NUM = s.PFNUMBER AND ISNULL(e.SP,'') = ISNULL(s.OSOB_SPO,'') AND e.WAY_CALC IN (10,11)		
					WHERE  code = @CODE1 and [TYPE] = @TYPE1 AND PFNUMBER = @PFNUMBER1 AND ISNULL(OSOB_SPO,'') = @OSOB_SPO AND s.ID_EX = 1
					GROUP BY [TYPE],CODE,[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt],INC_T1M1,INC_T1M2,INC_T1M3, INC_T2M1,INC_T2M2,INC_T2M3,date_end	,s.OSOB_SPO,E.SP, e.PF_NUM 	
					
					set @nom_pp1 = @nom_pp1 + 1
					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '1 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'711'),
						   COL4 = CONVERT(VARCHAR(4),ISNULL(s.OSOB_SPO,'')),
						   COL5 = ISNULL((sum(CASE WHEN MONTH_BASE= month(@DateM1E) AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END)- sum(CASE WHEN MONTH_BASE= month(@DateM1E) AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)),0),
						   COL6 = ISNULL( ( sum(CASE WHEN MONTH_BASE= month(@DateM1E) AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END)- sum(CASE WHEN MONTH_BASE= month(@DateM1E) AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END)),0),
						   COL7 = ISNULL([PFNUMBER],0),
						   COL8 = @nom_pp1,
						   COL9 = [TYPE],
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					FROM #SZV_ALL s
					left JOIN #SPR_ESN  e ON 	e.PF_NUM = s.PFNUMBER AND ISNULL(e.SP,'') = ISNULL(s.OSOB_SPO,'') AND e.WAY_CALC IN (10,11)	
					WHERE  code = @CODE1 and [TYPE] = @TYPE1 AND PFNUMBER = @PFNUMBER1 AND ISNULL(OSOB_SPO,'') = @OSOB_SPO AND s.ID_EX = 1
					GROUP BY [TYPE],CODE,[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt],INC_T1M1,INC_T1M2,INC_T1M3, INC_T2M1,INC_T2M2,INC_T2M3,date_end,s.OSOB_SPO,E.SP, e.PF_NUM 		
					
					set @nom_pp1 = @nom_pp1 + 1
					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '2 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'712'),
						   COL4 = CONVERT(VARCHAR(4),ISNULL(s.OSOB_SPO,'')),
						   COL5 = ISNULL((sum(CASE WHEN MONTH_BASE= month(@DateM2E) AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END)- sum(CASE WHEN MONTH_BASE= month(@DateM2E) AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)),0),
						   COL6 = ISNULL( ( sum(CASE WHEN MONTH_BASE= month(@DateM2E) AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END)- sum(CASE WHEN MONTH_BASE= month(@DateM2E) AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END)),0),
						   COL7 = ISNULL([PFNUMBER],0),
						   COL8 = @nom_pp1,
						   COL9 = [TYPE],
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					FROM #SZV_ALL s
					left JOIN #SPR_ESN  e ON 	e.PF_NUM = s.PFNUMBER AND ISNULL(e.SP,'') = ISNULL(s.OSOB_SPO,'') AND e.WAY_CALC IN (10,11)		
					WHERE  code = @CODE1 and [TYPE] = @TYPE1 AND PFNUMBER = @PFNUMBER1 AND ISNULL(OSOB_SPO,'') = @OSOB_SPO AND s.ID_EX = 1
					GROUP BY [TYPE],CODE,[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt],INC_T1M1,INC_T1M2,INC_T1M3, INC_T2M1,INC_T2M2,INC_T2M3,date_end,s.OSOB_SPO,E.SP, e.PF_NUM 			
					
					set @nom_pp1 = @nom_pp1 + 1
					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '3 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'713'),
						   COL4 = CONVERT(VARCHAR(4),ISNULL(s.OSOB_SPO,'')),
						   COL5 = ISNULL((sum(CASE WHEN MONTH_BASE= month(@DateM3E) AND e.WAY_CALC = 10	 THEN SUMMA_BASE ELSE 0 END)- sum(CASE WHEN MONTH_BASE= month(@DateM3E) AND e.WAY_CALC = 10	 THEN DED_M + INV_M  ELSE 0 END)),0),
						   COL6 = ISNULL( ( sum(CASE WHEN MONTH_BASE= month(@DateM3E) AND e.WAY_CALC = 11	 THEN SUMMA_BASE ELSE 0 END)- sum(CASE WHEN MONTH_BASE= month(@DateM3E) AND e.WAY_CALC = 11	 THEN DED_M + INV_M  ELSE 0 END)),0),
						   COL7 = ISNULL([PFNUMBER],0),
						   COL8 = @nom_pp1,
						   COL9 = [TYPE],
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					FROM #SZV_ALL s
					left JOIN #SPR_ESN  e ON 	e.PF_NUM = s.PFNUMBER AND ISNULL(e.SP,'') = ISNULL(s.OSOB_SPO,'') AND e.WAY_CALC IN (10,11)	
					WHERE  code = @CODE1 and [TYPE] = @TYPE1 AND PFNUMBER = @PFNUMBER1 AND ISNULL(OSOB_SPO,'') = @OSOB_SPO AND s.ID_EX = 1
					GROUP BY [TYPE],CODE,[FM],[IM],[OT],[PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt],INC_T1M1,INC_T1M2,INC_T1M3, INC_T2M1,INC_T2M2,INC_T2M3,date_end	,s.OSOB_SPO,E.SP, e.PF_NUM  		
					
					set @nom_pp1 = @nom_pp1 + 1
				END						

				--- заполняем пустые строки '710','711','712','713' 
			
				if not exists (select * from #tmp3 
								where COL7 = @PFNUMBER1 
								and COL9 = @TYPE1
								and COL4 = '710' ) AND NOT EXISTS (SELECT * FROM #SZV_ALL WHERE PFNUMBER = @PFNUMBER1 AND ISNULL(OSOB_SPO,'') != @OSOB_SPO AND [TYPE] = 2) 
				begin 
						
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), 'Всего с начала расчетного периода, в том числе за последние три месяца отчетного периода:'),	
						   COL3 = CONVERT(VARCHAR(4),'710'),
						   COL4 = CONVERT(VARCHAR(4),''),
						   COL5 = 0,
						   COL6 = 0,
						   COL7 = ISNULL(@PFNUMBER1,''),
						   COL8 = @nom_pp1,
						   COL9 = @TYPE1,
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					
					set @nom_pp1 = @nom_pp1 + 1
					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '1 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'711'),
						   COL4 = CONVERT(VARCHAR(4),''),
						   COL5 = 0,
						   COL6 = 0,
						   COL7 = ISNULL(@PFNUMBER1,''),
						   COL8 = @nom_pp1,
						   COL9 = @TYPE1,
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					
					set @nom_pp1 = @nom_pp1 + 1
					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '2 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'712'),
						   COL4 = CONVERT(VARCHAR(4),''),
						   COL5 = 0,
						   COL6 = 0,
						   COL7 = ISNULL(@PFNUMBER1,''),
						   COL8 = @nom_pp1,
						   COL9 = @TYPE1,
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					
					set @nom_pp1 = @nom_pp1 + 1		
					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '3 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'713'),
						   COL4 = CONVERT(VARCHAR(4),''),
						   COL5 = 0,
						   COL6 = 0,
						   COL7 = ISNULL(@PFNUMBER1,''),
						   COL8 = @nom_pp1,
						   COL9 = @TYPE1,
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
					
					set @nom_pp1 = @nom_pp1 + 1	
				
				end 


					select	row_number() over (order by DATE_BEGIN) as ID ,
							FM1 = [FM]  ,
							IM1 = [IM],
							OT1 = [OT],
							PFNUMBER1 = [PFNUMBER], 
							T_DOG1= T_DOG,
							TYPE1 = [TYPE], 
							DATE_BEGIN1 = [DATE_BEGIN], 
							DATE_END1 = (CASE WHEN [DATE_END] > @dDate2 THEN @dDate2 ELSE  [DATE_END] END )  , 
							TU_CODE1 = [TU_CODE], 
							OS_CODE1 = [OS_CODE], 
							EX_CODE1 = [EX_CODE], 
							f_is_dop1 = [f_is_dop], 
							P_CODE1 = [P_CODE], 
							f_ud_dop1 = [f_ud_dop] 
					into #TMP04
					FROM #SZV_ALL  WHERE  id_ex IS NOT NULL  AND YEAR(@dDate1)<=YEAR(Date_END) and MONTH(@dDate2) >= MONTH(Date_END) and MONTH(@dDate2) >= MONTH(Date_BEGIN) and [TYPE] = @TYPE1 AND PFNUMBER = @PFNUMBER1 and fm = @FM1 and T_DOG = 1
					GROUP BY [FM],[IM],[OT],[PFNUMBER], T_DOG,[TYPE], [DATE_BEGIN], [DATE_END] , [TU_CODE], [OS_CODE], [EX_CODE], [f_is_dop], [P_CODE], [f_ud_dop]
					ORDER BY  [FM],[IM],[OT],[PFNUMBER], T_DOG,[TYPE]
				

					UPDATE #TMP3
					set COL10 = (SELECT distinct convert(varchar(10),DATE_BEGIN1, 104 ) FROM #TMP04 where ID=1 and FM1= @FM1),
						COL11 = (SELECT distinct convert(varchar(10),DATE_END1, 104 ) FROM #TMP04 where ID=1 and FM1= @FM1),
						COL12 = (SELECT distinct convert(varchar(10),TU_CODE1 ) FROM #TMP04 where ID=1 and FM1= @FM1) ,
						COL13 = (SELECT distinct convert(varchar(20),OS_CODE1 ) FROM #TMP04 where ID=1 and FM1= @FM1),
						COL14 = (SELECT distinct convert(varchar(10),EX_CODE1 ) FROM #TMP04 where ID=1 and FM1= @FM1), 
						COL15 = (SELECT distinct convert(varchar(100),f_is_dop1 ) FROM #TMP04 where ID=1 and FM1= @FM1),
					    COL16 = (SELECT distinct convert(varchar(10),P_CODE1) FROM #TMP04 where ID=1 and FM1= @FM1), 
					    COL17 = (SELECT distinct convert(varchar(100),f_ud_dop1) FROM #TMP04 where ID=1 and FM1= @FM1), 
					    COL18 = (SELECT distinct convert(varchar(10),DATE_BEGIN1 , 104 ) FROM #TMP04 where ID=2 and FM1= @FM1), 
					    COL19 = (SELECT distinct convert(varchar(10),DATE_END1, 104 ) FROM #TMP04 where ID=2 and FM1= @FM1),
					    COL20 = (SELECT distinct convert(varchar(10),TU_CODE1 ) FROM #TMP04 where ID=2 and FM1= @FM1),
					    COL21 = (SELECT distinct convert(varchar(20),OS_CODE1 ) FROM #TMP04 where ID=2 and FM1= @FM1),
						COL22 = (SELECT distinct convert(varchar(10),EX_CODE1 ) FROM #TMP04 where ID=2 and FM1= @FM1), 
						COL23 = (SELECT distinct convert(varchar(100),f_is_dop1 ) FROM #TMP04 where ID=2 and FM1= @FM1),
					    COL24 = (SELECT distinct convert(varchar(10),P_CODE1) FROM #TMP04 where ID=2 and FM1= @FM1), 
					    COL25 = (SELECT distinct convert(varchar(100),f_ud_dop1) FROM #TMP04 where ID=2 and FM1= @FM1),
					    COL26 = (SELECT distinct convert(varchar(10),DATE_BEGIN1, 104 ) FROM #TMP04 where ID=3 and FM1= @FM1), 
					    COL27 = (SELECT distinct convert(varchar(10),DATE_END1, 104 ) FROM #TMP04 where ID=3 and FM1= @FM1),
					    COL28 = (SELECT distinct convert(varchar(10),TU_CODE1 ) FROM #TMP04 where ID=3 and FM1= @FM1),
					    COL29 = (SELECT distinct convert(varchar(20),OS_CODE1 ) FROM #TMP04 where ID=3 and FM1= @FM1),
						COL30 = (SELECT distinct convert(varchar(10),EX_CODE1 ) FROM #TMP04 where ID=3 and FM1= @FM1), 
						COL31 = (SELECT distinct convert(varchar(100),f_is_dop1 ) FROM #TMP04 where ID=3 and FM1= @FM1),
					    COL32 = (SELECT distinct convert(varchar(10),P_CODE1) FROM #TMP04 where ID=3 and FM1= @FM1), 
					    COL33 = (SELECT distinct convert(varchar(100),f_ud_dop1) FROM #TMP04 where ID=3 and FM1= @FM1),
					    COL34 = (SELECT distinct convert(varchar(10),DATE_BEGIN1, 104 ) FROM #TMP04 where ID=4 and FM1= @FM1), 
					    COL35 = (SELECT distinct convert(varchar(10),DATE_END1, 104 ) FROM #TMP04 where ID=4 and FM1= @FM1),
					    COL36 = (SELECT distinct convert(varchar(10),TU_CODE1 ) FROM #TMP04 where ID=4 and FM1= @FM1),
					    COL37 = (SELECT distinct convert(varchar(20),OS_CODE1 ) FROM #TMP04 where ID=4 and FM1= @FM1),
						COL38 = (SELECT distinct convert(varchar(10),EX_CODE1 ) FROM #TMP04 where ID=4 and FM1= @FM1), 
						COL39 = (SELECT distinct convert(varchar(100),f_is_dop1 ) FROM #TMP04 where ID=4 and FM1= @FM1),
					    COL40 = (SELECT distinct convert(varchar(10),P_CODE1) FROM #TMP04 where ID=4 and FM1= @FM1), 
					    COL41 = (SELECT distinct convert(varchar(100),f_ud_dop1) FROM #TMP04 where ID=4 and FM1= @FM1)
					from #TMP3	
					WHERE #TMP3.COL9 = @TYPE1 
					and #TMP3.COL7 = @PFNUMBER1 and  #TMP3.COL3 = '700'

					drop table #TMP04	


					set @pf_num11 = @PFNUMBER1
					set @OSOB_SPO_old = @OSOB_SPO
					set @TYPE_OLD1 = @TYPE1
					
			END

			FETCH NEXT FROM @Cur4 INTO @CODE1,@TYPE1,@PFNUMBER1,@FM1,@IM1,@OT1, @OSOB_SPO
		END

		CLOSE @Cur4
		DEALLOCATE @Cur4
		
		
		SELECT DISTINCT * FROM #TMP3 where col5 <> 0 or col6 <> 0  or  ISNULL(COL10,'') <> '' ORDER BY  CODE/*, col2, col4 */, COL8
	

		drop table #TMP3
	
	END		
	
	IF @REP = 4 
	BEGIN 	
		/*Заполнение подраздела 6.8 «Период работы за последние три месяца отчетного периода» раздела 6 Расчета*/
		create table #TMP4(CODE int identity(1,1) ,col1 int,   COL2 VARCHAR(10), COL3 VARCHAR(10), COL4 VARCHAR(10), COL5 VARCHAR(20), COL6 VARCHAR(10), COL7 varchar(100), COL8 VARCHAR(10), COL9 varchar(100), COL10 VARCHAR(14), COL11 INT , COL12 INT, COL13 VARCHAR(100), COL14 varchar(100), COL15 VARCHAR(100) )

		INSERT INTO #TMP4 (COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL12, COL13, COL14, COL15 )
		SELECT 
			   COL2 = convert(varchar(10),(CASE WHEN [DATE_BEGIN] > @dDate2 THEN @dDate2 ELSE [DATE_BEGIN] END) , 104), 
			   COL3 = CONVERT(varchar(10),[DATE_END] , 104),
			   COL4 = CONVERT(VARCHAR(10),ISNULL([TU_CODE],'')),
			   COL5 = CONVERT(VARCHAR(20),ISNULL([OS_CODE],'')),
			   COL6 = CONVERT(VARCHAR(10),ISNULL([EX_CODE],'')),
			   COL7 = CONVERT(VARCHAR(100),ISNULL([f_is_dop],'')),
			   COL8 = CONVERT(VARCHAR(10),ISNULL([P_CODE],'')),
			   COL9 = CONVERT(VARCHAR(100),ISNULL([f_ud_dop],'')),
			   COL10 = CONVERT(VARCHAR(100),ISNULL([PFNUMBER],'')),
			   COL12 = ISNULL([TYPE],0),
			   COL13 = CONVERT(varchar(100),FM),
			   COL14 = CONVERT(varchar(100),IM),
			   COL15 = CONVERT(varchar(100),OT)
		FROM #SZV_ALL  WHERE  id_ex IS NOT NULL  AND  YEAR(@dDate1)<=YEAR(Date_END) and MONTH(@dDate2) >= MONTH(Date_END) and MONTH(@dDate2) >= MONTH(Date_BEGIN)
		GROUP BY [FM],[IM],[OT],[PFNUMBER]/*, T_DOG*/,[TYPE], [DATE_BEGIN], [DATE_END] , [TU_CODE], [OS_CODE], [EX_CODE], [f_is_dop], [P_CODE], [f_ud_dop]
		ORDER BY  [FM],[IM],[OT],[PFNUMBER]/*, T_DOG*/,[TYPE]


		UPDATE #TMP4 
			SET col1 = CODE , COL11 = CODE 

		SELECT * FROM #TMP4 ORDER BY CODE
		drop table #TMP4
		--GROUP BY [TYPE],CODE, [T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[per_edt],[year_edt]	
		
	END	
	
	
		
		drop table #SZV_ALL
		--drop table #docs_kor_otm
		drop table #docs

END











GO


GRANT EXECUTE ON dbo.[RSA_RSV_1_PERS_UCH_SZV] TO PUBLIC

GO




GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SS_PROV_EXPORT]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SS_PROV_EXPORT]

GO

CREATE PROCEDURE [dbo].SS_PROV_EXPORT (
@buffer varchar(20) /*Ссылка на расчет*/
) AS




CREATE TABLE #OUTPUT (ID int identity(1,1), F_NAME VARCHAR(254), OUT_TEXT TEXT)

SET NOCOUNT ON

CREATE TABLE #DOC(LINK INT)


INSERT INTO #DOC (LINK)
SELECT LINK FROM dbo.BUFFER WITH (NOLOCK) WHERE ID = @BUFFER AND SID = SUSER_SID()

--ЗАПИСИ по проводкам

CREATE TABLE #PROV_DOC (
G_PROV_LINK INT ,
G_PROV_NUMBER VARCHAR (25),
G_PROV_DATE DATETIME,
G_PROV_OBJECT INT,
S_OBJECTS_CODE CHAR(30), 
S_OBJECTS_NAME VARCHAR(254),
G_PROV_DATE_PROV DATETIME,
G_PROV_SUMMA NUMERIC(19,2),
G_PROV_COMMENT VARCHAR(254),
G_PROV_GET_STORE TINYINT,
G_PROV_DEP INT,
G_PROV_ACC INT,
department_accounts_CODE VARCHAR(20),
DEPARTMENT_ACCOUNTS_TYPE TINYINT, 

G_PROV1_LINK INT,
G_PROV1_LINK_UP INT,
G_PROV1_OPER INT,
G_PROV1_G_PROV1_NAME_OPER VARCHAR(250),
G_PROV1_NAME_OPER VARCHAR(250),
G_PROV1_ORDERS INT,

G_PROV2_LINK INT,
G_PROV2_LINK_UP INT,
G_PROV2_SUMMA NUMERIC (19,2) ,
G_PROV2_QUANTITY NUMERIC (19,4) ,
G_PROV2_STORNO TINYINT,
G_PROV2_LINK_SELF INT,
G_PROV2_G_PROV2_NAME VARCHAR(254),
G_PROV2_NAME VARCHAR(254),
G_PROV2_ORDERS SMALLINT,
G_PROV2_ECON_OPER INT,
XOZ_OPER_CODE CHAR(2),
XOZ_OPER_NAME VARCHAR(254),

G_PROV_AP_D_LINK_UP INT,
G_PROV_AP_D_DB_KR TINYINT,
G_PROV_AP_D_ACCOUNT INT,
G_PROV_AP_D_KBK INT,
G_PROV_AP_D_EKR INT,
G_PROV_AP_D_DEP INT,
G_PROV_AP_D_SUB INT,
G_PROV_AP_D_EMP INT,
G_PROV_AP_D_NOMEN INT,
G_PROV_AP_D_INV INT,
G_PROV_AP_D_KAU INT,
G_PROV_AP_D_DEP_ACC INT,
G_PROV_AP_D_TMC INT,
G_PROV_AP_D_INDATE DATETIME,
G_PROV_AP_D_SGU INT,
G_PROV_AP_D_AP1 INT,
G_PROV_AP_D_AP2 INT,
G_PROV_AP_D_AP3 INT,


G_PROV_AP_K_LINK_UP INT,
G_PROV_AP_K_DB_KR INT,
G_PROV_AP_K_ACCOUNT INT,
G_PROV_AP_K_KBK INT,
G_PROV_AP_K_EKR INT,
G_PROV_AP_K_DEP INT, 
G_PROV_AP_K_SUB INT,
G_PROV_AP_K_EMP INT,
G_PROV_AP_K_NOMEN INT,
G_PROV_AP_K_INV INT,
G_PROV_AP_K_KAU INT,
G_PROV_AP_K_DEP_ACC INT,
G_PROV_AP_K_TMC INT,
G_PROV_AP_K_INDATE DATETIME,
G_PROV_AP_K_SGU INT,
G_PROV_AP_K_AP1 INT,
G_PROV_AP_K_AP2 INT,
G_PROV_AP_K_AP3 INT)





CREATE TABLE #DEP_INFO (
	DEP_LINK INT,
	DEP_CODE VARCHAR(10),
	DEP_NAME varchar(256),
	DEP_FNAME varchar(256),
	INN VARCHAR(12),
	KPP VARCHAR(9))


CREATE TABLE #G_PROV_AP_FULL	( G_PROV_LINK INT,
	G_PROV_AP_D_LINK_UP INT,
	G_PROV_AP_D_DB_KR TINYINT,
	G_PROV_AP_D_ACCOUNT INT,
	s_accounts_D_name VARCHAR(150),
	s_accounts_D_CODE VARCHAR(13),
	s_accounts_D_cSource VARCHAR(1),
	s_accounts_D_cSinth VARCHAR(3),
	s_accounts_D_cAnalit VARCHAR(2),
	
	G_PROV_AP_D_KBK INT,
	KL_KBK_D_type TINYINT,KL_KBK_D_code CHAR(20),KL_KBK_D_NAME VARCHAR(250),
	
	G_PROV_AP_D_EKR INT,
	KOSGU_EKR_D_code CHAR(3),	KOSGU_EKR_D_NAME VARCHAR(250), KOSGU_EKR_D_ls_ekr TINYINT,

	G_PROV_AP_D_DEP INT,
	DEP_D_CODE VARCHAR(10),
	DEP_D_NAME varchar(256),
	DEP_D_FNAME varchar(256),
	DEP_D_INN VARCHAR(12),
	DEP_D_KPP VARCHAR(9),
	
	G_PROV_AP_D_SUB INT,
	SUBDIV_D_code VARCHAR(5), 
	SUBDIV_D_NAME VARCHAR(254), 
	SUBDIV_D_lim int , 
	SUBDIV_D_obosob TINYINT, 
	SUBDIV_D_o_okato VARCHAR(14), 
	SUBDIV_D_o_okpp VARCHAR(9), 
	SUBDIV_D_o_oktmo  VARCHAR(11),
	
	G_PROV_AP_D_EMP INT,
	SD_EMPL_D_tab VARCHAR(10), 
	SD_EMPL_D_fm VARCHAR(100), 
	SD_EMPL_D_im VARCHAR(100), 
	SD_EMPL_D_ot VARCHAR(100), 
	SD_EMPL_D_FIO VARCHAR(105), 
	SD_EMPL_D_INSUR_NUM VARCHAR(14), 
	SD_EMPL_D_INN VARCHAR(12), 
	SD_EMPL_D_date_begin datetime, 
	SD_EMPL_D_date_end DATETIME, 
	
	G_PROV_AP_D_NOMEN INT,
	NOMENCLATURE_D_CODE VARCHAR(20),NOMENCLATURE_D_NAME VARCHAR(254),
	
	G_PROV_AP_D_INV INT,
	INVENTORY_D_code VARCHAR(20),	INVENTORY_D_NAME VARCHAR(254),
	
	G_PROV_AP_D_KAU INT,
	KAU_D_code VARCHAR(20), KAU_D_name VARCHAR(100), KAU_D_thema VARCHAR(50),
	
	G_PROV_AP_D_DEP_ACC INT,
	DEPARTMENT_ACCOUNTS_D_code VARCHAR(20), DEPARTMENT_ACCOUNTS_D_TYPE TINYINT,
	
	G_PROV_AP_D_TMC INT,
	DICTION_D_NAME VARCHAR(254), DICTION_D_code VARCHAR(20) ,
	
	G_PROV_AP_D_INDATE DATETIME,
	G_PROV_AP_D_SGU INT,
	KOSGU_SGU_D_code CHAR(3) , KOSGU_SGU_D_NAME VARCHAR(250), KOSGU_SGU_D_ls_ekr tinyint , 
	
	G_PROV_AP_D_AP1 INT,
	OSNOV_AP1_D_TYPE_LINK int , OSNOV_AP1_D_doc_link  INT , G_PROV_AP1_D_NUMBER VARCHAR (25), G_PROV_AP1_D_DATE DATETIME, S_OBJECTS_AP1_D_CODE CHAR(30), S_OBJECTS_AP1_D_NAME VARCHAR(254),
					G_PROV_AP1_D_DATE_PROV DATETIME, G_PROV_AP1_D_SUMMA NUMERIC(19,2), G_PROV_AP1_D_COMMENT VARCHAR(254), G_PROV_AP1_D_GET_STORE TINYINT,department_accounts_AP1_D_CODE VARCHAR(20),
	
	G_PROV_AP_D_AP2 INT,
	DOP_CLASSIF_D_code VARCHAR(20), DOP_CLASSIF_D_NAME VARCHAR(150),
	G_PROV_AP_D_AP3 INT,


	G_PROV_AP_K_LINK_UP INT,
	G_PROV_AP_K_DB_KR TINYINT,
	G_PROV_AP_K_ACCOUNT INT,
	s_accounts_K_name VARCHAR(150),
	s_accounts_K_CODE VARCHAR(13),
	s_accounts_K_cSource VARCHAR(1),
	s_accounts_K_cSinth VARCHAR(3),
	s_accounts_K_cAnalit VARCHAR(2),
	
	G_PROV_AP_K_KBK INT,
	KL_KBK_K_type TINYINT,KL_KBK_K_code CHAR(20),KL_KBK_K_NAME VARCHAR(250),
	
	G_PROV_AP_K_EKR INT,
	KOSGU_EKR_K_code CHAR(3),	KOSGU_EKR_K_NAME VARCHAR(250), KOSGU_EKR_K_ls_ekr TINYINT,

	G_PROV_AP_K_DEP INT,
	DEP_K_CODE VARCHAR(10),
	DEP_K_NAME varchar(256),
	DEP_K_FNAME varchar(256),
	DEP_K_INN VARCHAR(12),
	DEP_K_KPP VARCHAR(9),
	
	G_PROV_AP_K_SUB INT,
	SUBDIV_K_code VARCHAR(5), 
	SUBDIV_K_NAME VARCHAR(254), 
	SUBDIV_K_lim int , 
	SUBDIV_K_obosob TINYINT, 
	SUBDIV_K_o_okato VARCHAR(14), 
	SUBDIV_K_o_okpp VARCHAR(9), 
	SUBDIV_K_o_oktmo  VARCHAR(11),
	
	G_PROV_AP_K_EMP INT,
	SD_EMPL_K_tab VARCHAR(10), 
	SD_EMPL_K_fm VARCHAR(100), 
	SD_EMPL_K_im VARCHAR(100), 
	SD_EMPL_K_ot VARCHAR(100), 
	SD_EMPL_K_FIO VARCHAR(105), 
	SD_EMPL_K_INSUR_NUM VARCHAR(14), 
	SD_EMPL_K_INN VARCHAR(12), 
	SD_EMPL_K_date_begin datetime, 
	SD_EMPL_K_date_end DATETIME, 
	
	G_PROV_AP_K_NOMEN INT,
	NOMENCLATURE_K_CODE VARCHAR(20),NOMENCLATURE_K_NAME VARCHAR(254),
	
	G_PROV_AP_K_INV INT,
	INVENTORY_K_code VARCHAR(20),	INVENTORY_K_NAME VARCHAR(254),
	
	G_PROV_AP_K_KAU INT,
	KAU_K_code VARCHAR(20), KAU_K_name VARCHAR(100), KAU_K_thema VARCHAR(50),
	
	G_PROV_AP_K_DEP_ACC INT,
	DEPARTMENT_ACCOUNTS_K_code VARCHAR(20), DEPARTMENT_ACCOUNTS_K_TYPE TINYINT,
	
	G_PROV_AP_K_TMC INT,
	DICTION_K_NAME VARCHAR(254), DICTION_K_code VARCHAR(20) ,
	
	G_PROV_AP_K_INDATE DATETIME,
	G_PROV_AP_K_SGU INT,
	KOSGU_SGU_K_code CHAR(3) , KOSGU_SGU_K_NAME VARCHAR(250), KOSGU_SGU_K_ls_ekr tinyint , 
	
	G_PROV_AP_K_AP1 INT,
	OSNOV_AP1_K_TYPE_LINK int , OSNOV_AP1_K_doc_link int  , G_PROV_AP1_K_NUMBER VARCHAR (25), G_PROV_AP1_K_DATE DATETIME, S_OBJECTS_AP1_K_CODE CHAR(30), S_OBJECTS_AP1_K_NAME VARCHAR(254),
	G_PROV_AP1_K_DATE_PROV DATETIME, G_PROV_AP1_K_SUMMA NUMERIC(19,2), G_PROV_AP1_K_COMMENT VARCHAR(254), G_PROV_AP1_K_GET_STORE TINYINT,department_accounts_AP1_K_CODE VARCHAR(20),
	
	G_PROV_AP_K_AP2 INT,
	DOP_CLASSIF_K_code VARCHAR(20), DOP_CLASSIF_K_NAME VARCHAR(150),
	G_PROV_AP_K_AP3 INT) 
	
INSERT into #PROV_DOC ( G_PROV_LINK,G_PROV_NUMBER,G_PROV_DATE,G_PROV_OBJECT,
								S_OBJECTS_CODE,S_OBJECTS_NAME,
						G_PROV_DATE_PROV,G_PROV_SUMMA,
						G_PROV_COMMENT,G_PROV_GET_STORE,G_PROV_DEP,G_PROV_ACC,
								department_accounts_CODE, DEPARTMENT_ACCOUNTS_TYPE,
						G_PROV1_LINK,G_PROV1_LINK_UP,G_PROV1_OPER,G_PROV1_G_PROV1_NAME_OPER,G_PROV1_NAME_OPER,G_PROV1_ORDERS,
						G_PROV2_LINK,G_PROV2_LINK_UP,G_PROV2_SUMMA,G_PROV2_QUANTITY,G_PROV2_STORNO,G_PROV2_LINK_SELF,G_PROV2_G_PROV2_NAME,G_PROV2_NAME,G_PROV2_ORDERS,G_PROV2_ECON_OPER,
								XOZ_OPER_CODE,XOZ_OPER_NAME,
						G_PROV_AP_D_LINK_UP,G_PROV_AP_D_DB_KR,G_PROV_AP_D_ACCOUNT,G_PROV_AP_D_KBK,G_PROV_AP_D_EKR,G_PROV_AP_D_DEP,G_PROV_AP_D_SUB,G_PROV_AP_D_EMP,G_PROV_AP_D_NOMEN,
						G_PROV_AP_D_INV,G_PROV_AP_D_KAU,G_PROV_AP_D_DEP_ACC, G_PROV_AP_D_TMC,G_PROV_AP_D_INDATE,G_PROV_AP_D_SGU,G_PROV_AP_D_AP1,G_PROV_AP_D_AP2,G_PROV_AP_D_AP3,
						G_PROV_AP_K_LINK_UP,G_PROV_AP_K_DB_KR,G_PROV_AP_K_ACCOUNT,G_PROV_AP_K_KBK,G_PROV_AP_K_EKR,G_PROV_AP_K_DEP,G_PROV_AP_K_SUB,G_PROV_AP_K_EMP,G_PROV_AP_K_NOMEN,
						G_PROV_AP_K_INV,G_PROV_AP_K_KAU,G_PROV_AP_K_DEP_ACC,G_PROV_AP_K_TMC,G_PROV_AP_K_INDATE,G_PROV_AP_K_SGU,G_PROV_AP_K_AP1,G_PROV_AP_K_AP2,G_PROV_AP_K_AP3)

SELECT  G.LINK,G.NUMBER,G.[DATE],G.[OBJECT],
		G.S_OBJECTS_CODE,G.S_OBJECTS_NAME,
	    G.DATE_PROV,G.SUMMA,G.COMMENT,G.GET_STORE,G.DEP,G.ACC,
		G.department_accounts_CODE,G.DEPARTMENT_ACCOUNTS_TYPE,
		G1.LINK,G1.LINK_UP,G1.OPER,G1.G_PROV1_NAME_OPER,G1.NAME_OPER,G1.ORDERS,
		G2.LINK,G2.LINK_UP,G2.SUMMA,G2.QUANTITY,G2.STORNO,
		G2.LINK_SELF,G2.G_PROV2_NAME,G2.NAME,G2.ORDERS,
		G2.ECON_OPER,G2.XOZ_OPER_CODE,G2.XOZ_OPER_NAME,
		GAP1.LINK_UP,GAP1.DB_KR,GAP1.ACCOUNT,GAP1.KBK,GAP1.EKR,GAP1.DEP,GAP1.SUB,GAP1.EMP,GAP1.NOMEN,
		GAP1.INV,GAP1.KAU,GAP1.DEP_ACC, GAP1.TMC,GAP1.INDATE,GAP1.SGU,GAP1.AP1,GAP1.AP2,GAP1.AP3,
		GAP2.LINK_UP,GAP2.DB_KR,GAP2.ACCOUNT,GAP2.KBK,GAP2.EKR,GAP2.DEP,GAP2.SUB,GAP2.EMP,GAP2.NOMEN,
		GAP2.INV,GAP2.KAU,GAP2.DEP_ACC,GAP2.TMC,GAP2.INDATE,GAP2.SGU,GAP2.AP1,GAP2.AP2,GAP2.AP3
FROM
	(select GG.LINK,GG.NUMBER,GG.[DATE],GG.[OBJECT],
			S_OBJECTS_CODE = S.CODE,S_OBJECTS_NAME = S.NAME, 
			GG.DATE_PROV,GG.SUMMA, GG.COMMENT,
			GG.GET_STORE,GG.DEP,GG.ACC,	
			department_accounts_CODE = da.CODE, 
			DEPARTMENT_ACCOUNTS_TYPE = DA.[TYPE] 
	from dbo.G_PROV GG 
	INNER JOIN  s_objects s ON s.LINK = GG.[OBJECT]
	LEFT JOIN DEPARTMENT_ACCOUNTS da ON da.LINK = GG.ACC) G
INNER JOIN (SELECT GG1.LINK,GG1.LINK_UP,GG1.OPER,
					   G_PROV1_NAME_OPER = GGG1.NAME_OPER,
					   GG1.NAME_OPER,GG1.ORDERS 
				from dbo.G_PROV1 gg1 
				LEFT JOIN dbo.G_PROV1 ggg1 ON ggg1.LINK = gg1.OPER ) G1  ON G1.LINK_UP = G.LINK
INNER JOIN (SELECT 	GG2.LINK,GG2.LINK_UP,
					GG2.SUMMA,GG2.QUANTITY,
					GG2.STORNO,GG2.LINK_SELF,
					G_PROV2_NAME = GGG2.NAME, 
					GG2.NAME,GG2.ORDERS,GG2.ECON_OPER,
					XOZ_OPER_CODE = XO.CODE,XOZ_OPER_NAME = XO.NAME
	            from dbo.G_PROV2 GG2 
	            INNER JOIN XOZ_OPER xo ON xo.LINK = GG2.ECON_OPER
				LEFT JOIN dbo.G_PROV2 GGG2 ON GGG2.LINK = GG2.LINK_SELF ) G2 ON G2.LINK_UP = G1.LINK
INNER JOIN dbo.G_PROV_AP GAP1 ON GAP1.LINK_UP = G2.LINK
INNER JOIN dbo.G_PROV_AP GAP2 ON GAP2.LINK_UP = G2.LINK
WHERE
	GAP1.DB_KR = 0
	AND
	GAP2.DB_KR = 1
	AND
	G2.LINK IN ( SELECT link FROM #DOC  )
		
		
	


INSERT #DEP_INFO ( DEP_LINK, DEP_CODE, DEP_NAME, DEP_FNAME, INN, KPP)
SELECT DISTINCT link , code , NAME , FULL_name , inn , kpp
FROM  #PROV_DOC g  
	INNER JOIN departments d ON g.G_PROV_DEP = d.link
	
	

INSERT INTO #G_PROV_AP_FULL	(  G_PROV_LINK,
	G_PROV_AP_D_LINK_UP,
	G_PROV_AP_D_DB_KR,
	G_PROV_AP_D_ACCOUNT,
	s_accounts_D_name,
	s_accounts_D_CODE,
	s_accounts_D_cSource,
	s_accounts_D_cSinth,
	s_accounts_D_cAnalit,
	
	G_PROV_AP_D_KBK,
	KL_KBK_D_type,KL_KBK_D_code,KL_KBK_D_NAME,
	
	G_PROV_AP_D_EKR, 
	KOSGU_EKR_D_code,	KOSGU_EKR_D_NAME, KOSGU_EKR_D_ls_ekr,

	G_PROV_AP_D_DEP,
	DEP_D_CODE,
	DEP_D_NAME,
	DEP_D_FNAME,
	DEP_D_INN,
	DEP_D_KPP,
	
	G_PROV_AP_D_SUB,
	SUBDIV_D_code, 
	SUBDIV_D_NAME, 
	SUBDIV_D_lim, 
	SUBDIV_D_obosob, 
	SUBDIV_D_o_okato, 
	SUBDIV_D_o_okpp, 
	SUBDIV_D_o_oktmo,
	
	G_PROV_AP_D_EMP,
	SD_EMPL_D_tab, 
	SD_EMPL_D_fm, 
	SD_EMPL_D_im, 
	SD_EMPL_D_ot, 
	SD_EMPL_D_FIO, 
	SD_EMPL_D_INSUR_NUM, 
	SD_EMPL_D_INN, 
	SD_EMPL_D_date_begin, 
	SD_EMPL_D_date_end, 
	
	G_PROV_AP_D_NOMEN,
	NOMENCLATURE_D_CODE,NOMENCLATURE_D_NAME,
	
	G_PROV_AP_D_INV,
	INVENTORY_D_code,	INVENTORY_D_NAME,
	
	G_PROV_AP_D_KAU,
	KAU_D_code, KAU_D_name, KAU_D_thema,
	
	G_PROV_AP_D_DEP_ACC,
	DEPARTMENT_ACCOUNTS_D_code, DEPARTMENT_ACCOUNTS_D_TYPE,
	
	G_PROV_AP_D_TMC,
	DICTION_D_NAME, DICTION_D_code,
	
	G_PROV_AP_D_INDATE,
	G_PROV_AP_D_SGU,
	KOSGU_SGU_D_code, KOSGU_SGU_D_NAME, KOSGU_SGU_D_ls_ekr, 
	
	G_PROV_AP_D_AP1,
	OSNOV_AP1_D_TYPE_LINK, OSNOV_AP1_D_doc_link, G_PROV_AP1_D_NUMBER, G_PROV_AP1_D_DATE, S_OBJECTS_AP1_D_CODE, S_OBJECTS_AP1_D_NAME,
					G_PROV_AP1_D_DATE_PROV, G_PROV_AP1_D_SUMMA , G_PROV_AP1_D_COMMENT , G_PROV_AP1_D_GET_STORE ,department_accounts_AP1_D_CODE ,
	
	G_PROV_AP_D_AP2,
	DOP_CLASSIF_D_code, DOP_CLASSIF_D_NAME,
	G_PROV_AP_D_AP3,


	G_PROV_AP_K_LINK_UP,
	G_PROV_AP_K_DB_KR,
	G_PROV_AP_K_ACCOUNT,
	s_accounts_K_name,
	s_accounts_K_CODE,
	s_accounts_K_cSource,
	s_accounts_K_cSinth,
	s_accounts_K_cAnalit,
	
	G_PROV_AP_K_KBK,
	KL_KBK_K_type,KL_KBK_K_code,KL_KBK_K_NAME,
	
	G_PROV_AP_K_EKR,
	KOSGU_EKR_K_code,	KOSGU_EKR_K_NAME, KOSGU_EKR_K_ls_ekr,

	G_PROV_AP_K_DEP,
	DEP_K_CODE,
	DEP_K_NAME,
	DEP_K_FNAME,
	DEP_K_INN,
	DEP_K_KPP,
	
	G_PROV_AP_K_SUB,
	SUBDIV_K_code, 
	SUBDIV_K_NAME, 
	SUBDIV_K_lim, 
	SUBDIV_K_obosob, 
	SUBDIV_K_o_okato, 
	SUBDIV_K_o_okpp, 
	SUBDIV_K_o_oktmo,
	
	G_PROV_AP_K_EMP,
	SD_EMPL_K_tab, 
	SD_EMPL_K_fm, 
	SD_EMPL_K_im, 
	SD_EMPL_K_ot, 
	SD_EMPL_K_FIO, 
	SD_EMPL_K_INSUR_NUM, 
	SD_EMPL_K_INN, 
	SD_EMPL_K_date_begin, 
	SD_EMPL_K_date_end, 
	
	G_PROV_AP_K_NOMEN,
	NOMENCLATURE_K_CODE,NOMENCLATURE_K_NAME,
	
	G_PROV_AP_K_INV,
	INVENTORY_K_code,	INVENTORY_K_NAME,
	
	G_PROV_AP_K_KAU,
	KAU_K_code, KAU_K_name, KAU_K_thema,
	
	G_PROV_AP_K_DEP_ACC,
	DEPARTMENT_ACCOUNTS_K_code, DEPARTMENT_ACCOUNTS_K_TYPE,
	
	G_PROV_AP_K_TMC,
	DICTION_K_NAME, DICTION_K_code,
	
	G_PROV_AP_K_INDATE,
	G_PROV_AP_K_SGU,
	KOSGU_SGU_K_code, KOSGU_SGU_K_NAME, KOSGU_SGU_K_ls_ekr, 
	
	G_PROV_AP_K_AP1,
	OSNOV_AP1_K_TYPE_LINK, OSNOV_AP1_K_doc_link, G_PROV_AP1_K_NUMBER, G_PROV_AP1_K_DATE, S_OBJECTS_AP1_K_CODE, S_OBJECTS_AP1_K_NAME,
	G_PROV_AP1_K_DATE_PROV, G_PROV_AP1_K_SUMMA, G_PROV_AP1_K_COMMENT, G_PROV_AP1_K_GET_STORE,department_accounts_AP1_K_CODE,
	
	G_PROV_AP_K_AP2,
	DOP_CLASSIF_K_code, DOP_CLASSIF_K_NAME,
	G_PROV_AP_K_AP3)

SELECT G.G_PROV_LINK,
	   G.G_PROV_AP_D_LINK_UP,
	   G.G_PROV_AP_D_DB_KR,
	   /*G_PROV_AP_D_ACCOUNT*/
	   G.G_PROV_AP_D_ACCOUNT, s_accounts_D_name = s.NAME, s_accounts_D_CODE = s.CODE, s_accounts_D_cSource = s.cSource, s_accounts_D_cSinth = s.cSinth, s_accounts_D_cAnalit = s.cAnalit,
	   /*G_PROV_AP_D_KBK*/
	   G.G_PROV_AP_D_KBK, KL_KBK_D_type = K.[TYPE], KL_KBK_D_code = K.CODE,KL_KBK_D_NAME = k.NAME,
	   /*G_PROV_AP_D_EKR*/
	   G.G_PROV_AP_D_EKR, KOSGU_EKR_D_code = ko.CODE, KOSGU_EKR_D_NAME = ko.NAME, KOSGU_EKR_D_ls_ekr = ko.Is_Ekr,
	   /*G_PROV_AP_D_DEP*/
	   G.G_PROV_AP_D_DEP, DEP_D_CODE = d.CODE, DEP_D_NAME = d.NAME, DEP_D_FNAME = d.FULL_NAME, DEP_D_INN = d.INN, DEP_D_KPP = d.KPP,
	   /*G_PROV_AP_D_SUB*/
	   G.G_PROV_AP_D_SUB, SUBDIV_D_code = su.CODE, SUBDIV_D_NAME = su.NAME, SUBDIV_D_lim = su.LIM, SUBDIV_D_obosob = su.OBOSOB, SUBDIV_D_o_okato = su.O_OKATO, SUBDIV_D_o_okpp = su.O_KPP, SUBDIV_D_o_oktmo = su.O_OKTMO,
	   /*G_PROV_AP_D_EMP*/
	   G.G_PROV_AP_D_EMP,  SD_EMPL_D_tab = sd.TAB, SD_EMPL_D_fm = sd.FM, SD_EMPL_D_im = sd.IM, SD_EMPL_D_ot = sd.OT, SD_EMPL_D_FIO = sd.FIO, SD_EMPL_D_INSUR_NUM = sd.INSUR_NUM, SD_EMPL_D_INN = sd.INN, SD_EMPL_D_date_begin = sd.DATE_BEGIN, SD_EMPL_D_date_end = sd.DATE_END, 
	   /*G_PROV_AP_D_NOMEN*/
	   G.G_PROV_AP_D_NOMEN, NOMENCLATURE_D_CODE = n.CODE, NOMENCLATURE_D_NAME = n.NAME,
	   /*G_PROV_AP_D_INV*/
	   G.G_PROV_AP_D_INV, INVENTORY_D_code = i.CODE, INVENTORY_D_NAME = i.NAME,
	   /*G_PROV_AP_D_KAU*/
	   G.G_PROV_AP_D_KAU, KAU_D_code = ka.CODE, KAU_D_name = ka.NAME, KAU_D_thema = KA.THEMA,
	   /*G_PROV_AP_D_DEP_ACC*/
	   G.G_PROV_AP_D_DEP_ACC, DEPARTMENT_ACCOUNTS_D_code = da.CODE, DEPARTMENT_ACCOUNTS_D_TYPE = da.[TYPE], 
	   /*G_PROV_AP_D_TMC*/
	   G.G_PROV_AP_D_TMC, DICTION_D_NAME = di.NAME, DICTION_D_code = di.CODE,
	   G.G_PROV_AP_D_INDATE, 
	   /*G_PROV_AP_D_SGU*/
	   G.G_PROV_AP_D_SGU, KOSGU_SGU_D_code = KOO.CODE, KOSGU_SGU_D_NAME = KOO.NAME, KOSGU_SGU_D_ls_ekr = KOO.Is_Ekr, 
	   /*G_PROV_AP_D_AP1*/
	   G.G_PROV_AP_D_AP1, O.OSNOV_AP1_D_TYPE_LINK, O.OSNOV_AP1_D_doc_link, O.G_PROV_AP1_D_NUMBER, O.G_PROV_AP1_D_DATE, O.S_OBJECTS_AP1_D_CODE, O.S_OBJECTS_AP1_D_NAME,
							O.G_PROV_AP1_D_DATE_PROV, O.G_PROV_AP1_D_SUMMA , O.G_PROV_AP1_D_COMMENT , O.G_PROV_AP1_D_GET_STORE ,O.department_accounts_AP1_D_CODE ,
	   G.G_PROV_AP_D_AP2, DOP_CLASSIF_D_code = do.CODE, DOP_CLASSIF_D_NAME = do.NAME,
	   G.G_PROV_AP_D_AP3,
	   
	   G.G_PROV_AP_K_LINK_UP,
	   G.G_PROV_AP_K_DB_KR,
	   /*G_PROV_AP_K_ACCOUNT*/
	   G.G_PROV_AP_K_ACCOUNT, s_accounts_K_name = s1.NAME, s_accounts_K_CODE = s1.CODE, s_accounts_K_cSource = s1.cSource, s_accounts_K_cSinth = s1.cSinth, s_accounts_K_cAnalit = s1.cAnalit,
	   /*G_PROV_AP_K_KBK*/
	   G.G_PROV_AP_K_KBK, KL_KBK_K_type = K1.[TYPE], KL_KBK_K_code = K1.CODE,KL_KBK_K_NAME = k1.NAME,
	   /*G_PROV_AP_K_EKR*/
	   G.G_PROV_AP_K_EKR, KOSGU_EKR_K_code = ko1.CODE, KOSGU_EKR_K_NAME = ko1.NAME, KOSGU_EKR_K_ls_ekr = ko1.Is_Ekr,
	   /*G_PROV_AP_K_DEP*/
	   G.G_PROV_AP_K_DEP, DEP_K_CODE = d1.CODE, DEP_K_NAME = d1.NAME, DEP_K_FNAME = d1.FULL_NAME, DEP_K_INN = d1.INN, DEP_K_KPP = d1.KPP,
	   /*G_PROV_AP_K_SUB*/
	   G.G_PROV_AP_K_SUB, SUBDIV_K_code = su1.CODE, SUBDIV_K_NAME = su1.NAME, SUBDIV_K_lim = su1.LIM, SUBDIV_K_obosob = su1.OBOSOB, SUBDIV_K_o_okato = su1.O_OKATO, SUBDIV_K_o_okpp = su1.O_KPP, SUBDIV_K_o_oktmo = su1.O_OKTMO,
	   /*G_PROV_AP_K_EMP*/
	   G.G_PROV_AP_K_EMP,  SD_EMPL_K_tab = sd1.TAB, SD_EMPL_K_fm = sd1.FM, SD_EMPL_K_im = sd1.IM, SD_EMPL_K_ot = sd1.OT, SD_EMPL_K_FIO = sd1.FIO, SD_EMPL_K_INSUR_NUM = sd1.INSUR_NUM, SD_EMPL_K_INN = sd1.INN, SD_EMPL_K_date_begin = sd1.DATE_BEGIN, SD_EMPL_K_date_end = sd1.DATE_END, 
	   /*G_PROV_AP_K_NOMEN*/
	   G.G_PROV_AP_K_NOMEN, NOMENCLATURE_K_CODE = n1.CODE, NOMENCLATURE_K_NAME = n1.NAME,
	   /*G_PROV_AP_K_INV*/
	   G.G_PROV_AP_K_INV, INVENTORY_K_code = i1.CODE, INVENTORY_K_NAME = i1.NAME,
	   /*G_PROV_AP_K_KAU*/
	   G.G_PROV_AP_K_KAU, KAU_K_code = ka1.CODE, KAU_K_name = ka1.NAME, KAU_K_thema = KA1.THEMA,
	   /*G_PROV_AP_K_DEP_ACC*/
	   G.G_PROV_AP_K_DEP_ACC, DEPARTMENT_ACCOUNTS_K_code = da1.CODE, DEPARTMENT_ACCOUNTS_K_TYPE = da1.[TYPE], 
	   /*G_PROV_AP_K_TMC*/
	   G.G_PROV_AP_K_TMC, DICTION_K_NAME = di1.NAME, DICTION_K_code = di1.CODE,
	   G.G_PROV_AP_K_INDATE, 
	   /*G_PROV_AP_K_SGU*/
	   G.G_PROV_AP_K_SGU, KOSGU_SGU_K_code = KOO1.CODE, KOSGU_SGU_K_NAME = KOO1.NAME, KOSGU_SGU_K_ls_ekr = KOO1.Is_Ekr, 
	   /*G_PROV_AP_K_AP1*/
	   G.G_PROV_AP_K_AP1, O1.OSNOV_AP1_K_TYPE_LINK, O1.OSNOV_AP1_K_doc_link, O1.G_PROV_AP1_K_NUMBER, O1.G_PROV_AP1_K_DATE, O1.S_OBJECTS_AP1_K_CODE, O1.S_OBJECTS_AP1_K_NAME,
							O1.G_PROV_AP1_K_DATE_PROV, O1.G_PROV_AP1_K_SUMMA , O1.G_PROV_AP1_K_COMMENT , O1.G_PROV_AP1_K_GET_STORE ,O1.department_accounts_AP1_K_CODE ,
	   G.G_PROV_AP_K_AP2, DOP_CLASSIF_K_code = do1.CODE, DOP_CLASSIF_K_NAME = do1.NAME,
	   G.G_PROV_AP_K_AP3
FROM
	#PROV_DOC G
	LEFT JOIN dbo.S_ACCOUNTS		  S ON S.LINK = G.G_PROV_AP_D_ACCOUNT
	LEFT JOIN dbo.KL_KBK			  K ON  k.link = G.G_PROV_AP_D_KBK
	LEFT JOIN dbo.KOSGU				  KO ON KO.LINK = G.G_PROV_AP_D_EKR
	LEFT JOIN dbo.departments		  d ON d.link = G.G_PROV_AP_D_DEP
	LEFT JOIN dbo.SUBDIV			  su ON su.link =  G.G_PROV_AP_D_SUB
	LEFT JOIN dbo.SD_EMPL			  sd ON sd.link =  G.G_PROV_AP_D_EMP
	LEFT JOIN dbo.NOMENCLATURE		  N ON n.LINK = G.G_PROV_AP_D_NOMEN
	LEFT JOIN dbo.INVENTORY			  I ON   I.link =  G.G_PROV_AP_D_INV
	LEFT JOIN dbo.KAU				  KA ON ka.link = G.G_PROV_AP_D_KAU
	LEFT JOIN dbo.DEPARTMENT_ACCOUNTS da ON da.link = G.G_PROV_AP_D_DEP_ACC
	LEFT JOIN dbo.DICTION			  di ON di.link = G.G_PROV_AP_D_TMC
	LEFT JOIN dbo.KOSGU				  KOO ON  KOO.LINK = G.G_PROV_AP_D_SGU	
	LEFT JOIN (SELECT oo.link,
					  OSNOV_AP1_D_TYPE_LINK = oo.TYPE_LINK ,
					  OSNOV_AP1_D_doc_link = oo.DOC_LINK,
					  G_PROV_AP1_D_NUMBER = GP.NUMBER ,
					  G_PROV_AP1_D_DATE = GP.[DATE],
					  S_OBJECTS_AP1_D_CODE = s.CODE,
					  S_OBJECTS_AP1_D_NAME = S.NAME,
					  G_PROV_AP1_D_DATE_PROV = GP.DATE_PROV,
					  G_PROV_AP1_D_SUMMA = GP.SUMMA,
					  G_PROV_AP1_D_COMMENT = GP.COMMENT,
					  G_PROV_AP1_D_GET_STORE = GP.GET_STORE,
					  department_accounts_AP1_D_CODE = d_ACc.CODE
			   from dbo.OSNOV oo 
			   LEFT JOIN dbo.G_PROV GP ON GP.LINK = oo.DOC_LINK
			   LEFT JOIN dbo.S_OBJECTS S ON s.link = GP.[OBJECT]	
			   LEFT JOIN department_accounts d_ACc ON d_acc.LINK = GP.ACC  )o ON o.LINK = G.G_PROV_AP_D_AP1
	LEFT JOIN dbo.DOP_CLASSIF		  do ON do.LINK = G.G_PROV_AP_D_AP1
	
	LEFT JOIN dbo.S_ACCOUNTS		  S1 ON S1.LINK = G.G_PROV_AP_K_ACCOUNT
	LEFT JOIN dbo.KL_KBK			  K1 ON  k1.link = G.G_PROV_AP_K_KBK
	LEFT JOIN dbo.KOSGU				  KO1 ON KO1.LINK = G.G_PROV_AP_K_EKR
	LEFT JOIN dbo.departments		  d1 ON d1.link = G.G_PROV_AP_K_DEP
	LEFT JOIN dbo.SUBDIV			  su1 ON su1.link =  G.G_PROV_AP_K_SUB
	LEFT JOIN dbo.SD_EMPL			  sd1 ON sd1.link =  G.G_PROV_AP_K_EMP
	LEFT JOIN dbo.NOMENCLATURE		  N1 ON n1.LINK = G.G_PROV_AP_K_NOMEN
	LEFT JOIN dbo.INVENTORY			  I1 ON   I1.link =  G.G_PROV_AP_K_INV
	LEFT JOIN dbo.KAU				  KA1 ON ka1.link = G.G_PROV_AP_K_KAU
	LEFT JOIN dbo.DEPARTMENT_ACCOUNTS da1 ON da1.link = G.G_PROV_AP_K_DEP_ACC
	LEFT JOIN dbo.DICTION			  di1 ON di1.link = G.G_PROV_AP_K_TMC
	LEFT JOIN dbo.KOSGU				  KOO1 ON  KOO1.LINK = G.G_PROV_AP_K_SGU	
	LEFT JOIN (SELECT oo.link,
					  OSNOV_AP1_K_TYPE_LINK = oo.TYPE_LINK ,
					  OSNOV_AP1_K_doc_link = oo.DOC_LINK,
					  G_PROV_AP1_K_NUMBER = GP.NUMBER ,
					  G_PROV_AP1_K_DATE = GP.[DATE],
					  S_OBJECTS_AP1_K_CODE = s.CODE,
					  S_OBJECTS_AP1_K_NAME = S.NAME,
					  G_PROV_AP1_K_DATE_PROV = GP.DATE_PROV,
					  G_PROV_AP1_K_SUMMA = GP.SUMMA,
					  G_PROV_AP1_K_COMMENT = GP.COMMENT,
					  G_PROV_AP1_K_GET_STORE = GP.GET_STORE,
					  department_accounts_AP1_K_CODE = d_ACc.CODE
			   from dbo.OSNOV oo 
			   LEFT JOIN dbo.G_PROV GP ON GP.LINK = oo.DOC_LINK
			   LEFT JOIN dbo.S_OBJECTS S ON s.link = GP.[OBJECT]	
			   LEFT JOIN department_accounts d_ACc ON d_acc.LINK = GP.ACC  )  o1 ON o1.LINK = G.G_PROV_AP_K_AP1
	LEFT JOIN dbo.DOP_CLASSIF		  do1 ON do1.LINK = G.G_PROV_AP_K_AP1





--Строка заголовка
CREATE TABLE #TASK_PROP (ID int identity(1,1), VAL VARCHAR (254))

INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MAJOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MINOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_FIX',1

declare @NAME_PROG varchar(254), @VERS_PROG VARCHAR(254)
Select @NAME_PROG = UPPER(RTRIM(LTRIM([NAME]))), 
	@VERS_PROG = (SELECT RTRIM(LTRIM(VAL)) FROM #TASK_PROP WHERE [ID] = 1)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 2)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 3)
from dbo.DICTIONARY_TASK where CODE = 'SALARY'
--------------------------------------------

declare @DEP_LINK int, @lcFNAME VARCHAR(254)/*, @ID INT, @EGRUL varchar(13)*/

--exec dbo.xd_whats_zb @DEP_LINK output
--select @EGRUL = LTRIM(RTRIM(EGRUL)) from DICTIONARY_DEPARTMENT where link = @DEP_LINK 
	
DECLARE @Cur1 CURSOR, @NGROUP int /*Номер пачки*/ , @GPROV_LINK int
set @NGROUP = 0
DECLARE @Cur2 CURSOR , @N_STR int /*Номер строки*/

-- ШАПОЧНАЯ ЧАСТЬ ФАЙЛА
-----
SELECT @lcFNAME = 'EXCH_PROV.XML' 

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
 SELECT @lcFNAME, 'OEM' --Имя файла 
		UNION ALL SELECT @lcFNAME, SPACE(0) + '<?xml version="1.0" encoding="Windows-1251" ?>' 
		UNION ALL SELECT @lcFNAME, SPACE(0) + '<Exchange version ="1.0">' 
		--UNION ALL SELECT @lcFNAME, SPACE(0) + '<File>' 
 		UNION ALL SELECT @lcFNAME, SPACE(1) + '<FileName>' + RTRIM(LTRIM(@lcFNAME)) + '</FileName>'
		 

SET @Cur1 = CURSOR FORWARD_ONLY
FOR select DEP_LINK from #DEP_INFO ORDER BY DEP_LINK
	
OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @DEP_LINK

WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN	
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)			 
		 SELECT @lcFNAME, SPACE(1) + '<Org>'
		 UNION ALL SELECT @lcFNAME, SPACE(2) + '<INN>'+RTRIM(LTRIM(COALESCE(INN,'')))+'</INN>'
		 FROM #DEP_INFO WHERE dep_link = @DEP_LINK	
		 UNION ALL SELECT @lcFNAME, SPACE(2) + '<KPP>'+RTRIM(LTRIM(COALESCE(KPP,'')))+'</KPP>'
		 FROM #DEP_INFO WHERE dep_link = @DEP_LINK	
		 UNION ALL SELECT @lcFNAME, SPACE(2) + '<CODE>'+RTRIM(LTRIM(COALESCE(DEP_CODE,'')))+'</CODE>'
		 FROM #DEP_INFO WHERE dep_link = @DEP_LINK	
		 UNION ALL SELECT @lcFNAME, SPACE(2) + '<Name>'+RTRIM(LTRIM(COALESCE(DEP_FNAME,'')))+'</Name>'
		 FROM #DEP_INFO WHERE dep_link = @DEP_LINK	
			
	--
	-- ПЕРЕЧИСЛЕНИЕ ПРОВОДОК
	---
		SET @N_STR = 0 
		SET @Cur2 = CURSOR FORWARD_ONLY
		FOR select G_PROV_LINK from #PROV_DOC WHERE G_PROV_DEP = @DEP_LINK
		
		OPEN @Cur2
		FETCH NEXT FROM @Cur2 INTO @GPROV_LINK

		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
					SELECT @lcFNAME,					
					SPACE(3) + '<NOM_PP>'+ CONVERT(VARCHAR(20),@N_STR+1) +'</NOM_PP>' + CHAR(10)
					/*таблица G_PROV*/
					+ SPACE(3) + '<G_PROV>' + CHAR(10)
					 + SPACE(4) + '<G_PROV_NUMBER>'+ P.G_PROV_NUMBER +'</G_PROV_NUMBER>' + CHAR(10)
					 + SPACE(4) + '<G_PROV_DATE>'+ convert(varchar(10),P.G_PROV_DATE,104) +'</G_PROV_DATE>' + CHAR(10)
					 /*поле OBJECT - линк таблицы S_OBJECTS */
					 + SPACE(4) + '<G_PROV_OBJECT>' + CHAR(10)
						+ SPACE(5) + '<S_OBJECTS_CODE>' + ltrim(rtrim(P.S_OBJECTS_CODE)) + '</S_OBJECTS_CODE>' + CHAR(10) 
						+ SPACE(5) + '<S_OBJECTS_NAME>' + UPPER(ltrim(rtrim(P.S_OBJECTS_NAME))) + '</S_OBJECTS_NAME>' + CHAR(10)
					 + SPACE(4) + '</G_PROV_OBJECT>' + CHAR(10) 
					 + SPACE(4) + '<G_PROV_DATE_PROV>'+ convert(varchar(10),P.G_PROV_DATE_PROV,104) +'</G_PROV_DATE_PROV>' + CHAR(10)
					 + SPACE(4) + '<G_PROV_SUMMA>'+ RTRIM(LTRIM(STR(COALESCE(P.G_PROV_SUMMA,0),18,2))) +'</G_PROV_SUMMA>' + CHAR(10)
					 + SPACE(4) + '<G_PROV_COMMENT>'+ RTRIM(LTRIM(COALESCE(P.G_PROV_COMMENT,''))) +'</G_PROV_COMMENT>' + CHAR(10)
					 + SPACE(4) + '<G_PROV_GET_STORE>'+ RTRIM(LTRIM(STR(COALESCE(P.G_PROV_GET_STORE,0)))) +'</G_PROV_GET_STORE>' + CHAR(10)
					 /*Поле DEP - линт таблицы #DEP_INFO*/
					 + SPACE(4) + '<G_PROV_DEP>' + CHAR(10)
						+ SPACE(5) + '<INN>' + (select RTRIM(LTRIM(COALESCE(INN,''))) FROM #DEP_INFO WHERE DEP_LINK = P.G_PROV_DEP ) + '</INN>' + CHAR(10)
						+ SPACE(5) + '<KPP>' + (select RTRIM(LTRIM(COALESCE(KPP,''))) FROM #DEP_INFO WHERE DEP_LINK = P.G_PROV_DEP ) + '</KPP>' + CHAR(10)
						+ SPACE(5) + '<DEP_NAME>'+ (select RTRIM(LTRIM(COALESCE(DEP_NAME,''))) FROM #DEP_INFO WHERE DEP_LINK = P.G_PROV_DEP ) +'</DEP_NAME>' + CHAR(10)
					 + SPACE(4) + '</G_PROV_DEP>' + CHAR(10)
					 /*поле ACC - линк таблицы department_accounts*/
					 + SPACE(4) + '<G_PROV_ACC>' + CHAR(10)
						+ SPACE(5) + '<department_accounts_CODE>' + ltrim(rtrim(iSnULL(P.department_accounts_CODE,''))) + '</department_accounts_CODE>' + CHAR(10)
						+ SPACE(5) + '<DEPARTMENT_ACCOUNTS_TYPE>' + RTRIM(LTRIM(STR(COALESCE(P.DEPARTMENT_ACCOUNTS_TYPE,0)))) + '</DEPARTMENT_ACCOUNTS_TYPE>' + CHAR(10)
					 + SPACE(4) + '</G_PROV_ACC>' + CHAR(10)
					 + SPACE(3) + '</G_PROV>' + CHAR(10)
					 /*Таблица G_PROV1*/
					 + SPACE(3) + '<G_PROV1>' + CHAR(10)
 						/*Поле OPER - линк таблицы G_PROV1*/
 						+ SPACE(4) + '<G_PROV1_OPER>' + RTRIM(LTRIM(STR(COALESCE(P.G_PROV1_OPER,0)))) + '</G_PROV1_OPER>'  + CHAR(10)
							+ SPACE(5) + '<G_PROV1_G_PROV1_NAME_OPER>' + RTRIM(LTRIM(ISNULL(P.G_PROV1_G_PROV1_NAME_OPER, ''))) + '</G_PROV1_G_PROV1_NAME_OPER>' + CHAR(10)
						+ SPACE(4) + '<G_PROV1_NAME_OPER>' + RTRIM(LTRIM(ISNULL(P.G_PROV1_NAME_OPER, ''))) + '</G_PROV1_NAME_OPER>'  + CHAR(10)
						+ SPACE(4) + '<G_PROV1_ORDERS>' + RTRIM(LTRIM(ISNULL(P.G_PROV1_ORDERS, ''))) + '</G_PROV1_ORDERS>'  + CHAR(10)
					 + SPACE(3) + '</G_PROV1>' + CHAR(10)
					 /*Таблица G_PROV2*/
					 + SPACE(3) + '<G_PROV2>' + CHAR(10)
 						+ SPACE(4) + '<G_PROV2_SUMMA>' + RTRIM(LTRIM(STR(COALESCE(P.[G_PROV2_SUMMA],0),18,2))) + '</G_PROV2_SUMMA>'  + CHAR(10)
						+ SPACE(4) + '<G_PROV2_QUANTITY>' + RTRIM(LTRIM(STR(COALESCE(P.[G_PROV2_QUANTITY],0),18,4))) + '</G_PROV2_QUANTITY>' + CHAR(10)
						+ SPACE(4) + '<G_PROV2_STORNO>' + RTRIM(LTRIM(STR(COALESCE(P.G_PROV2_STORNO,'')))) + '</G_PROV2_STORNO>'  + CHAR(10)
						/* ПОЛЕ LINK_SELF - link таблицы G_PROV2*/
						+ SPACE(4) + '<G_PROV2_LINK_SELF>' + RTRIM(LTRIM(STR(COALESCE(P.G_PROV2_LINK_SELF,'')))) + '</G_PROV2_LINK_SELF>'  + CHAR(10)
							+ SPACE(5) + '<G_PROV2_G_PROV2_NAME>' + RTRIM(LTRIM(ISNULL(P.G_PROV2_G_PROV2_NAME, ''))) + '</G_PROV2_G_PROV2_NAME>'  + CHAR(10)
						+ SPACE(4) + '<G_PROV2_NAME>' + RTRIM(LTRIM(ISNULL(P.G_PROV2_NAME, ''))) + '</G_PROV2_NAME>'  + CHAR(10)
						+ SPACE(4) + '<G_PROV2_ORDERS>' + RTRIM(LTRIM(STR(COALESCE(P.G_PROV2_ORDERS,''))))+ '</G_PROV2_ORDERS>'  + CHAR(10)
						/*поле ECON_OPER - линк таблицы XOZ_OPER*/
						+ SPACE(4) + '<G_PROV2_ECON_OPER>'	
							+ SPACE(5) + '<XOZ_OPER_CODE>' + RTRIM(LTRIM(ISNULL(P.XOZ_OPER_CODE, ''))) + '</XOZ_OPER_CODE>'  + CHAR(10)
							+ SPACE(5) + '<XOZ_OPER_NAME>' + RTRIM(LTRIM(ISNULL(P.XOZ_OPER_NAME, ''))) + '</XOZ_OPER_NAME>'  + CHAR(10)
						+ SPACE(4) + '</G_PROV2_ECON_OPER>'				
					 + SPACE(3) + '</G_PROV2>' + CHAR(10)
					FROM
						#PROV_DOC P
						INNER JOIN #G_PROV_AP_FULL GP ON GP.G_PROV_LINK = P.G_PROV_LINK
					WHERE 
						P.G_PROV_LINK = @GPROV_LINK
					
					
					
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
					SELECT @lcFNAME,
					 /*Дебет*/
					 SPACE(3) + '<G_PROV_AP_D>' + CHAR(10)
					 	+ SPACE(4) + '<G_PROV_AP_D_DB_KR>' + RTRIM(LTRIM(STR(COALESCE(GP.G_PROV_AP_D_DB_KR,'')))) + '</G_PROV_AP_D_DB_KR>'  + CHAR(10)
						/*поле ACCOUNT - линк таблицы s_accounts*/
						+ SPACE(4) + '<G_PROV_AP_D_ACCOUNT>' + CHAR(10)
							+ SPACE(5) + '<s_accounts_D_name>' + RTRIM(LTRIM(ISNULL(GP.s_accounts_D_name, ''))) + '</s_accounts_D_name>'  + CHAR(10)
							+ SPACE(5) + '<s_accounts_D_CODE>' + RTRIM(LTRIM(ISNULL(GP.s_accounts_D_CODE, ''))) + '</s_accounts_D_CODE>'  + CHAR(10)
							+ SPACE(5) + '<s_accounts_D_cSource>' + ISNULL(GP.s_accounts_D_cSource, '') + '</s_accounts_D_cSource>'  + CHAR(10)
							+ SPACE(5) + '<s_accounts_D_cSinth>' + ISNULL(GP.s_accounts_D_cSinth, '') + '</s_accounts_D_cSinth>'  + CHAR(10)
							+ SPACE(5) + '<s_accounts_D_cAnalit>' + ISNULL(GP.s_accounts_D_cAnalit, '') + '</s_accounts_D_cAnalit>'  + CHAR(10)
						+ SPACE(4) + '</G_PROV_AP_D_ACCOUNT>'  + CHAR(10)
						/*поле KBK - линк таблицы KL_KBK*/
						+ SPACE(4) + '<G_PROV_AP_D_KBK>' + CHAR(10)
								+ SPACE(5) + '<KL_KBK_D_type>' + RTRIM(LTRIM(STR(COALESCE(GP.KL_KBK_D_type,'')))) + '</KL_KBK_D_type>'  + CHAR(10)
								+ SPACE(5) + '<KL_KBK_D_code>' + RTRIM(LTRIM(ISNULL(GP.KL_KBK_D_code, ''))) + '</KL_KBK_D_code>'  + CHAR(10)
								+ SPACE(5) + '<KL_KBK_D_NAME>' + RTRIM(LTRIM(ISNULL(GP.KL_KBK_D_NAME, ''))) + '</KL_KBK_D_NAME>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_D_KBK>' + CHAR(10)		
						 /*поле EKR - линк таблицы KOSGU*/
						 + SPACE(4) + '<G_PROV_AP_D_EKR>' + CHAR(10)
								+ SPACE(5) + '<KOSGU_EKR_D_code>' + RTRIM(LTRIM(ISNULL(GP.KOSGU_EKR_D_code, ''))) + '</KOSGU_EKR_D_code>'  + CHAR(10)
								+ SPACE(5) + '<KOSGU_EKR_D_NAME>' + RTRIM(LTRIM(ISNULL(GP.KOSGU_EKR_D_NAME, ''))) + '</KOSGU_EKR_D_NAME>'  + CHAR(10)
								+ SPACE(5) + '<KOSGU_EKR_D_ls_ekr>' + RTRIM(LTRIM(ISNULL(GP.KOSGU_EKR_D_ls_ekr, ''))) + '</KOSGU_EKR_D_ls_ekr>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_D_EKR>' + CHAR(10)	
						 /*поле DEP - линк таблицы DEPARTMENTS*/
						 + SPACE(4) + '<G_PROV_AP_D_DEP>' + CHAR(10)
								+ SPACE(5) + '<DEP_D_CODE>' + RTRIM(LTRIM(ISNULL(GP.DEP_D_CODE, ''))) + '</DEP_D_CODE>'  + CHAR(10)
								+ SPACE(5) + '<DEP_D_NAME>' + RTRIM(LTRIM(ISNULL(GP.DEP_D_NAME, ''))) + '</DEP_D_NAME>'  + CHAR(10)
								+ SPACE(5) + '<DEP_D_FNAME>' + RTRIM(LTRIM(ISNULL(GP.DEP_D_FNAME, ''))) + '</DEP_D_FNAME>'  + CHAR(10)
								+ SPACE(5) + '<DEP_D_INN>' + RTRIM(LTRIM(ISNULL(GP.DEP_D_INN, ''))) + '</DEP_D_INN>'  + CHAR(10)
								+ SPACE(5) + '<DEP_D_KPP>' + RTRIM(LTRIM(ISNULL(GP.DEP_D_KPP, ''))) + '</DEP_D_KPP>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_D_DEP>' + CHAR(10)	
						 /*поле SUB - линк таблицы SUBDIV*/
						 + SPACE(4) + '<G_PROV_AP_D_SUB>' + CHAR(10)
								+ SPACE(5) + '<SUBDIV_D_code>' + RTRIM(LTRIM(ISNULL(GP.SUBDIV_D_code, ''))) + '</SUBDIV_D_code>'  + CHAR(10)
								+ SPACE(5) + '<SUBDIV_D_NAME>' + RTRIM(LTRIM(ISNULL(GP.SUBDIV_D_NAME, ''))) + '</SUBDIV_D_NAME>'  + CHAR(10)
								+ SPACE(5) + '<SUBDIV_D_lim>' + ISNULL(GP.DEP_D_FNAME, '') + '</SUBDIV_D_lim>'  + CHAR(10)
								+ SPACE(5) + '<SUBDIV_D_obosob>' + RTRIM(LTRIM(STR(COALESCE(GP.SUBDIV_D_obosob,'')))) + '</SUBDIV_D_obosob>'  + CHAR(10)
								+ SPACE(5) + '<SUBDIV_D_o_okato>' + RTRIM(LTRIM(ISNULL(GP.DEP_D_KPP, ''))) + '</SUBDIV_D_o_okato>'  + CHAR(10)
								+ SPACE(5) + '<SUBDIV_D_o_okpp>' + RTRIM(LTRIM(ISNULL(GP.SUBDIV_D_o_okpp, ''))) + '</SUBDIV_D_o_okpp>'  + CHAR(10)
								+ SPACE(5) + '<SUBDIV_D_o_oktmo>' + RTRIM(LTRIM(ISNULL(GP.SUBDIV_D_o_oktmo, ''))) + '</SUBDIV_D_o_oktmo>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_D_SUB>' + CHAR(10)	
						 /*поле EMP - линк таблицы SD_EMPL*/
						 + SPACE(4) + '<G_PROV_AP_D_EMP>' + CHAR(10)
								+ SPACE(5) + '<SD_EMPL_D_tab>' + RTRIM(LTRIM(ISNULL(GP.SD_EMPL_D_tab, ''))) + '</SD_EMPL_D_tab>'  + CHAR(10)
								+ SPACE(5) + '<SD_EMPL_D_fm>' + RTRIM(LTRIM(ISNULL(GP.SD_EMPL_D_fm, ''))) + '</SD_EMPL_D_fm>'  + CHAR(10)
								+ SPACE(5) + '<SD_EMPL_D_im>' + RTRIM(LTRIM(ISNULL(GP.SD_EMPL_D_im, ''))) + '</SD_EMPL_D_im>'  + CHAR(10)
								+ SPACE(5) + '<SD_EMPL_D_ot>' + RTRIM(LTRIM(ISNULL(GP.SD_EMPL_D_ot, ''))) + '</SD_EMPL_D_ot>'  + CHAR(10)
								+ SPACE(5) + '<SD_EMPL_D_FIO>' + RTRIM(LTRIM(ISNULL(GP.SD_EMPL_D_FIO, ''))) + '</SD_EMPL_D_FIO>'  + CHAR(10)
								+ SPACE(5) + '<SD_EMPL_D_INSUR_NUM>' + RTRIM(LTRIM(ISNULL(GP.SD_EMPL_D_INSUR_NUM, ''))) + '</SD_EMPL_D_INSUR_NUM>'  + CHAR(10)
								+ SPACE(5) + '<SD_EMPL_D_INN>' + RTRIM(LTRIM(ISNULL(GP.SD_EMPL_D_INN, ''))) + '</SD_EMPL_D_INN>'  + CHAR(10)
								+ SPACE(5) + '<SD_EMPL_D_date_begin>' + CASE WHEN convert(varchar(10),ISNULL(GP.SD_EMPL_D_date_begin,''),104) = '01.01.1900' THEN '' ELSE convert(varchar(10),ISNULL(GP.SD_EMPL_D_date_begin,''),104) end + '</SD_EMPL_D_date_begin>'  + CHAR(10)
								+ SPACE(5) + '<SD_EMPL_D_date_end>' + CASE WHEN convert(varchar(10),ISNULL(GP.SD_EMPL_D_date_end,''),104) = '01.01.1900' THEN '' ELSE convert(varchar(10),ISNULL(GP.SD_EMPL_D_date_end,''),104) end + '</SD_EMPL_D_date_end>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_D_EMP>' + CHAR(10)	
						  /*поле NOMEN - линк таблицы NOMENCLATURE*/
						 + SPACE(4) + '<G_PROV_AP_D_NOMEN>' + CHAR(10)
								+ SPACE(5) + '<NOMENCLATURE_D_CODE>' + RTRIM(LTRIM(ISNULL(GP.NOMENCLATURE_D_CODE, ''))) + '</NOMENCLATURE_D_CODE>'  + CHAR(10)
								+ SPACE(5) + '<NOMENCLATURE_D_NAME>' + RTRIM(LTRIM(ISNULL(GP.NOMENCLATURE_D_NAME, ''))) + '</NOMENCLATURE_D_NAME>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_D_NOMEN>' + CHAR(10)
						 /*поле INV - линк таблицы INVENTORY*/
						 + SPACE(4) + '<G_PROV_AP_D_INV>' + CHAR(10)
								+ SPACE(5) + '<INVENTORY_D_code>' + RTRIM(LTRIM(ISNULL(GP.INVENTORY_D_code, ''))) + '</INVENTORY_D_code>'  + CHAR(10)
								+ SPACE(5) + '<INVENTORY_D_NAME>' + RTRIM(LTRIM(ISNULL(GP.INVENTORY_D_NAME, ''))) + '</INVENTORY_D_NAME>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_D_INV>' + CHAR(10)							
						 /*поле KAU - линк таблицы KAU*/
						 + SPACE(4) + '<G_PROV_AP_D_KAU>' + CHAR(10)
								+ SPACE(5) + '<KAU_D_code>' + RTRIM(LTRIM(ISNULL(GP.KAU_D_code, ''))) + '</KAU_D_code>'  + CHAR(10)
								+ SPACE(5) + '<KAU_D_name>' + RTRIM(LTRIM(ISNULL(GP.KAU_D_name, ''))) + '</KAU_D_name>'  + CHAR(10)
								+ SPACE(5) + '<KAU_D_thema>' + RTRIM(LTRIM(ISNULL(GP.KAU_D_thema, ''))) + '</KAU_D_thema>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_D_KAU>' + CHAR(10)		
						 /*поле DEP_ACC - линк таблицы DEPARTMENT_ACCOUNTS*/
						 + SPACE(4) + '<G_PROV_AP_D_DEP_ACC>' + CHAR(10)
								+ SPACE(5) + '<DEPARTMENT_ACCOUNTS_D_code>' + RTRIM(LTRIM(ISNULL(GP.DEPARTMENT_ACCOUNTS_D_code, ''))) + '</DEPARTMENT_ACCOUNTS_D_code>'  + CHAR(10)
								+ SPACE(5) + '<DEPARTMENT_ACCOUNTS_D_TYPE>' + RTRIM(LTRIM(STR(COALESCE(GP.DEPARTMENT_ACCOUNTS_D_TYPE,'')))) + '</DEPARTMENT_ACCOUNTS_D_TYPE>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_D_DEP_ACC>' + CHAR(10)	
						 /*поле TMC - линк таблицы DICTION*/
						 + SPACE(4) + '<G_PROV_AP_D_TMC>' + CHAR(10)
								+ SPACE(5) + '<DICTION_D_NAME>' + RTRIM(LTRIM(ISNULL(GP.DEPARTMENT_ACCOUNTS_D_code, ''))) + '</DICTION_D_NAME>'  + CHAR(10)
								+ SPACE(5) + '<DICTION_D_code>' + RTRIM(LTRIM(STR(COALESCE(GP.DEPARTMENT_ACCOUNTS_D_TYPE,'')))) + '</DICTION_D_code>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_D_TMC>' + CHAR(10)	
						 + SPACE(4) + '<G_PROV_AP_D_INDATE>' + CASE WHEN convert(varchar(10),ISNULL(GP.G_PROV_AP_D_INDATE,''),104) = '01.01.1900' THEN '' ELSE convert(varchar(10),ISNULL(GP.G_PROV_AP_D_INDATE,''),104) end + '</G_PROV_AP_D_INDATE>'  + CHAR(10)	
						 /*поле SGU - линк таблицы KOSGU*/
						 + SPACE(4) + '<G_PROV_AP_D_SGU>' + CHAR(10)
								+ SPACE(5) + '<KOSGU_SGU_D_code>' + RTRIM(LTRIM(ISNULL(GP.KOSGU_SGU_D_code, ''))) + '</KOSGU_SGU_D_code>'  + CHAR(10)
								+ SPACE(5) + '<KOSGU_SGU_D_NAME>' + RTRIM(LTRIM(ISNULL(GP.KOSGU_SGU_D_NAME, ''))) + '</KOSGU_SGU_D_NAME>'  + CHAR(10)
								+ SPACE(5) + '<KOSGU_SGU_D_ls_ekr>' + RTRIM(LTRIM(STR(COALESCE(GP.KOSGU_SGU_D_ls_ekr,'')))) + '</KOSGU_SGU_D_ls_ekr>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_D_SGU>' + CHAR(10)			
						 /*поле AP1 - линк таблицы OSNOV*/
						 + SPACE(4) + '<G_PROV_AP_D_AP1>' + CHAR(10)
								/*таблица OSNOV*/
								+ SPACE(5) + '<OSNOV_AP1_D_TYPE_LINK>' + RTRIM(LTRIM(STR(COALESCE(GP.OSNOV_AP1_D_TYPE_LINK,'')))) + '</OSNOV_AP1_D_TYPE_LINK>'  + CHAR(10)
								+ SPACE(5) + '<OSNOV_AP1_D_doc_link>' +  RTRIM(LTRIM(STR(COALESCE(GP.OSNOV_AP1_D_doc_link,'')))) + '</OSNOV_AP1_D_doc_link>'  + CHAR(10)
									/*поле LINK_G_PROV - линк таблицы G_PROV*/
									+ SPACE(6) + '<G_PROV_AP1_D_NUMBER>' + RTRIM(LTRIM(ISNULL(GP.G_PROV_AP1_D_NUMBER, ''))) + '</G_PROV_AP1_D_NUMBER>'  + CHAR(10)	
									+ SPACE(6) + '<G_PROV_AP1_D_DATE>' + CASE WHEN convert(varchar(10),ISNULL(GP.G_PROV_AP1_D_DATE,''),104) = '01.01.1900' THEN '' ELSE convert(varchar(10),ISNULL(GP.G_PROV_AP1_D_DATE,''),104) end + '</G_PROV_AP1_D_DATE>'  + CHAR(10)						
									+ SPACE(6) + '<S_OBJECTS_AP1_D_CODE>' + RTRIM(LTRIM(ISNULL(GP.S_OBJECTS_AP1_D_CODE, ''))) + '</S_OBJECTS_AP1_D_CODE>'  + CHAR(10)
									+ SPACE(6) + '<S_OBJECTS_AP1_D_NAME>' + RTRIM(LTRIM(ISNULL(GP.S_OBJECTS_AP1_D_NAME, ''))) + '</S_OBJECTS_AP1_D_NAME>'  + CHAR(10)
									+ SPACE(6) + '<G_PROV_AP1_D_DATE_PROV>' + RTRIM(LTRIM(ISNULL(GP.S_OBJECTS_AP1_D_CODE, ''))) + '</G_PROV_AP1_D_DATE_PROV>'  + CHAR(10)			
									+ SPACE(6) + '<G_PROV_AP1_D_SUMMA>' + RTRIM(LTRIM(STR(COALESCE(GP.G_PROV_AP1_D_SUMMA,0),18,4))) + '</G_PROV_AP1_D_SUMMA>'  + CHAR(10)	
									+ SPACE(6) + '<G_PROV_AP1_D_COMMENT>' + RTRIM(LTRIM(ISNULL(GP.G_PROV_AP1_D_COMMENT, ''))) + '</G_PROV_AP1_D_COMMENT>'  + CHAR(10)	
									+ SPACE(6) + '<G_PROV_AP1_D_GET_STORE>' + RTRIM(LTRIM(STR(COALESCE(GP.G_PROV_AP1_D_GET_STORE,'')))) + '</G_PROV_AP1_D_GET_STORE>'  + CHAR(10)		
										+ SPACE(7) + '<department_accounts_AP1_D_CODE>' + ISNULL(GP.department_accounts_AP1_D_CODE, '') + '</department_accounts_AP1_D_CODE>'  + CHAR(10)		
						 + SPACE(4) + '</G_PROV_AP_D_AP1>' + CHAR(10)	
						 /*поле AP2 - линк таблицы DOP_CLASSIF*/
						 + SPACE(4) + '<G_PROV_AP_D_AP2>' + CHAR(10)
								+ SPACE(5) + '<DOP_CLASSIF_D_code>' + RTRIM(LTRIM(ISNULL(GP.DOP_CLASSIF_D_code, ''))) + '</DOP_CLASSIF_D_code>'  + CHAR(10)
								+ SPACE(5) + '<DOP_CLASSIF_D_NAME>' + RTRIM(LTRIM(ISNULL(GP.DOP_CLASSIF_D_NAME, ''))) + '</DOP_CLASSIF_D_NAME>'  + CHAR(10)
						  + SPACE(4) + '</G_PROV_AP_D_AP2>' + CHAR(10)
						  + SPACE(4) + '<G_PROV_AP_D_AP3>' + RTRIM(LTRIM(ISNULL(GP.DOP_CLASSIF_D_code, ''))) + '</G_PROV_AP_D_AP3>'  + CHAR(10)
					+ SPACE(3) + '</G_PROV_AP_D>' + CHAR(10)
					FROM
						#PROV_DOC P
						INNER JOIN #G_PROV_AP_FULL GP ON GP.G_PROV_LINK = P.G_PROV_LINK
					WHERE 
						P.G_PROV_LINK = @GPROV_LINK
					
					
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
					SELECT @lcFNAME,					
					/*Кредит*/
					SPACE(3) + '<G_PROV_AP_K>' + CHAR(10)
					 	+ SPACE(4) + '<G_PROV_AP_K_DB_KR>' + RTRIM(LTRIM(STR(COALESCE(GP.G_PROV_AP_K_DB_KR,'')))) + '</G_PROV_AP_K_DB_KR>'  + CHAR(10)
						/*поле ACCOUNT - линк таблицы s_accounts*/
						+ SPACE(4) + '<G_PROV_AP_K_ACCOUNT>' + CHAR(10)
							+ SPACE(5) + '<s_accounts_K_name>' + RTRIM(LTRIM(ISNULL(GP.s_accounts_K_name, ''))) + '</s_accounts_K_name>'  + CHAR(10)
							+ SPACE(5) + '<s_accounts_K_CODE>' + RTRIM(LTRIM(ISNULL(GP.s_accounts_K_CODE, ''))) + '</s_accounts_K_CODE>'  + CHAR(10)
							+ SPACE(5) + '<s_accounts_K_cSource>' + ISNULL(GP.s_accounts_K_cSource, '') + '</s_accounts_K_cSource>'  + CHAR(10)
							+ SPACE(5) + '<s_accounts_K_cSinth>' + ISNULL(GP.s_accounts_K_cSinth, '') + '</s_accounts_K_cSinth>'  + CHAR(10)
							+ SPACE(5) + '<s_accounts_K_cAnalit>' + ISNULL(GP.s_accounts_K_cAnalit, '') + '</s_accounts_K_cAnalit>'  + CHAR(10)
						+ SPACE(4) + '</G_PROV_AP_K_ACCOUNT>'  + CHAR(10)
						/*поле KBK - линк таблицы KL_KBK*/
						+ SPACE(4) + '<G_PROV_AP_K_KBK>' + CHAR(10)
								+ SPACE(5) + '<KL_KBK_K_type>' + RTRIM(LTRIM(STR(COALESCE(GP.KL_KBK_K_type,'')))) + '</KL_KBK_K_type>'  + CHAR(10)
								+ SPACE(5) + '<KL_KBK_K_code>' + RTRIM(LTRIM(ISNULL(GP.KL_KBK_K_code, ''))) + '</KL_KBK_K_code>'  + CHAR(10)
								+ SPACE(5) + '<KL_KBK_K_NAME>' + RTRIM(LTRIM(ISNULL(GP.KL_KBK_K_NAME, ''))) + '</KL_KBK_K_NAME>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_K_KBK>' + CHAR(10)		
						 /*поле EKR - линк таблицы KOSGU*/
						 + SPACE(4) + '<G_PROV_AP_K_EKR>' + CHAR(10)
								+ SPACE(5) + '<KOSGU_EKR_K_code>' + RTRIM(LTRIM(ISNULL(GP.KOSGU_EKR_K_code, ''))) + '</KOSGU_EKR_K_code>'  + CHAR(10)
								+ SPACE(5) + '<KOSGU_EKR_K_NAME>' + RTRIM(LTRIM(ISNULL(GP.KOSGU_EKR_K_NAME, ''))) + '</KOSGU_EKR_K_NAME>'  + CHAR(10)
								+ SPACE(5) + '<KOSGU_EKR_K_ls_ekr>' + RTRIM(LTRIM(ISNULL(GP.KOSGU_EKR_K_ls_ekr, ''))) + '</KOSGU_EKR_K_ls_ekr>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_K_EKR>' + CHAR(10)	
						 /*поле DEP - линк таблицы DEPARTMENTS*/
						 + SPACE(4) + '<G_PROV_AP_K_DEP>' + CHAR(10)
								+ SPACE(5) + '<DEP_K_CODE>' + RTRIM(LTRIM(ISNULL(GP.DEP_K_CODE, ''))) + '</DEP_K_CODE>'  + CHAR(10)
								+ SPACE(5) + '<DEP_K_NAME>' + RTRIM(LTRIM(ISNULL(GP.DEP_K_NAME, ''))) + '</DEP_K_NAME>'  + CHAR(10)
								+ SPACE(5) + '<DEP_K_FNAME>' + RTRIM(LTRIM(ISNULL(GP.DEP_K_FNAME, ''))) + '</DEP_K_FNAME>'  + CHAR(10)
								+ SPACE(5) + '<DEP_K_INN>' + RTRIM(LTRIM(ISNULL(GP.DEP_K_INN, ''))) + '</DEP_K_INN>'  + CHAR(10)
								+ SPACE(5) + '<DEP_K_KPP>' + RTRIM(LTRIM(ISNULL(GP.DEP_K_KPP, ''))) + '</DEP_K_KPP>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_K_DEP>' + CHAR(10)	
						 /*поле SUB - линк таблицы SUBDIV*/
						 + SPACE(4) + '<G_PROV_AP_K_SUB>' + CHAR(10)
								+ SPACE(5) + '<SUBDIV_K_code>' + RTRIM(LTRIM(ISNULL(GP.SUBDIV_K_code, ''))) + '</SUBDIV_K_code>'  + CHAR(10)
								+ SPACE(5) + '<SUBDIV_K_NAME>' + RTRIM(LTRIM(ISNULL(GP.SUBDIV_K_NAME, ''))) + '</SUBDIV_K_NAME>'  + CHAR(10)
								+ SPACE(5) + '<SUBDIV_K_lim>' + ISNULL(GP.DEP_K_FNAME, '') + '</SUBDIV_K_lim>'  + CHAR(10)
								+ SPACE(5) + '<SUBDIV_K_obosob>' + RTRIM(LTRIM(STR(COALESCE(GP.SUBDIV_K_obosob,'')))) + '</SUBDIV_K_obosob>'  + CHAR(10)
								+ SPACE(5) + '<SUBDIV_K_o_okato>' + RTRIM(LTRIM(ISNULL(GP.DEP_K_KPP, ''))) + '</SUBDIV_K_o_okato>'  + CHAR(10)
								+ SPACE(5) + '<SUBDIV_K_o_okpp>' + RTRIM(LTRIM(ISNULL(GP.SUBDIV_K_o_okpp, ''))) + '</SUBDIV_K_o_okpp>'  + CHAR(10)
								+ SPACE(5) + '<SUBDIV_K_o_oktmo>' + RTRIM(LTRIM(ISNULL(GP.SUBDIV_K_o_oktmo, ''))) + '</SUBDIV_K_o_oktmo>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_K_SUB>' + CHAR(10)	
						 /*поле EMP - линк таблицы SD_EMPL*/
						 + SPACE(4) + '<G_PROV_AP_K_EMP>' + CHAR(10)
								+ SPACE(5) + '<SD_EMPL_K_tab>' + RTRIM(LTRIM(ISNULL(GP.SD_EMPL_K_tab, ''))) + '</SD_EMPL_K_tab>'  + CHAR(10)
								+ SPACE(5) + '<SD_EMPL_K_fm>' + RTRIM(LTRIM(ISNULL(GP.SD_EMPL_K_fm, ''))) + '</SD_EMPL_K_fm>'  + CHAR(10)
								+ SPACE(5) + '<SD_EMPL_K_im>' + RTRIM(LTRIM(ISNULL(GP.SD_EMPL_K_im, ''))) + '</SD_EMPL_K_im>'  + CHAR(10)
								+ SPACE(5) + '<SD_EMPL_K_ot>' + RTRIM(LTRIM(ISNULL(GP.SD_EMPL_K_ot, ''))) + '</SD_EMPL_K_ot>'  + CHAR(10)
								+ SPACE(5) + '<SD_EMPL_K_FIO>' + RTRIM(LTRIM(ISNULL(GP.SD_EMPL_K_FIO, ''))) + '</SD_EMPL_K_FIO>'  + CHAR(10)
								+ SPACE(5) + '<SD_EMPL_K_INSUR_NUM>' + RTRIM(LTRIM(ISNULL(GP.SD_EMPL_K_INSUR_NUM, ''))) + '</SD_EMPL_K_INSUR_NUM>'  + CHAR(10)
								+ SPACE(5) + '<SD_EMPL_K_INN>' + RTRIM(LTRIM(ISNULL(GP.SD_EMPL_K_INN, ''))) + '</SD_EMPL_K_INN>'  + CHAR(10)
								+ SPACE(5) + '<SD_EMPL_K_date_begin>' + CASE WHEN convert(varchar(10),ISNULL(GP.SD_EMPL_K_date_begin,''),104) = '01.01.1900' THEN '' ELSE convert(varchar(10),ISNULL(GP.SD_EMPL_K_date_begin,''),104) end + '</SD_EMPL_K_date_begin>'  + CHAR(10)
								+ SPACE(5) + '<SD_EMPL_K_date_end>' + CASE WHEN convert(varchar(10),ISNULL(GP.SD_EMPL_K_date_end,''),104) = '01.01.1900' THEN '' ELSE convert(varchar(10),ISNULL(GP.SD_EMPL_K_date_end,''),104) end + '</SD_EMPL_K_date_end>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_K_EMP>' + CHAR(10)	
						  /*поле NOMEN - линк таблицы NOMENCLATURE*/
						 + SPACE(4) + '<G_PROV_AP_K_NOMEN>' + CHAR(10)
								+ SPACE(5) + '<NOMENCLATURE_K_CODE>' + RTRIM(LTRIM(ISNULL(GP.NOMENCLATURE_K_CODE, ''))) + '</NOMENCLATURE_K_CODE>'  + CHAR(10)
								+ SPACE(5) + '<NOMENCLATURE_K_NAME>' + RTRIM(LTRIM(ISNULL(GP.NOMENCLATURE_K_NAME, ''))) + '</NOMENCLATURE_K_NAME>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_K_NOMEN>' + CHAR(10)
						 /*поле INV - линк таблицы INVENTORY*/
						 + SPACE(4) + '<G_PROV_AP_K_INV>' + CHAR(10)
								+ SPACE(5) + '<INVENTORY_K_code>' + RTRIM(LTRIM(ISNULL(GP.INVENTORY_K_code, ''))) + '</INVENTORY_K_code>'  + CHAR(10)
								+ SPACE(5) + '<INVENTORY_K_NAME>' + RTRIM(LTRIM(ISNULL(GP.INVENTORY_K_NAME, ''))) + '</INVENTORY_K_NAME>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_K_INV>' + CHAR(10)							
						 /*поле KAU - линк таблицы KAU*/
						 + SPACE(4) + '<G_PROV_AP_K_KAU>' + CHAR(10)
								+ SPACE(5) + '<KAU_K_code>' + RTRIM(LTRIM(ISNULL(GP.KAU_K_code, ''))) + '</KAU_K_code>'  + CHAR(10)
								+ SPACE(5) + '<KAU_K_name>' + RTRIM(LTRIM(ISNULL(GP.KAU_K_name, ''))) + '</KAU_K_name>'  + CHAR(10)
								+ SPACE(5) + '<KAU_K_thema>' + RTRIM(LTRIM(ISNULL(GP.KAU_K_thema, ''))) + '</KAU_K_thema>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_K_KAU>' + CHAR(10)		
						 /*поле DEP_ACC - линк таблицы DEPARTMENT_ACCOUNTS*/
						 + SPACE(4) + '<G_PROV_AP_K_DEP_ACC>' + CHAR(10)
								+ SPACE(5) + '<DEPARTMENT_ACCOUNTS_K_code>' + RTRIM(LTRIM(ISNULL(GP.DEPARTMENT_ACCOUNTS_K_code, ''))) + '</DEPARTMENT_ACCOUNTS_K_code>'  + CHAR(10)
								+ SPACE(5) + '<DEPARTMENT_ACCOUNTS_K_TYPE>' + RTRIM(LTRIM(STR(COALESCE(GP.DEPARTMENT_ACCOUNTS_K_TYPE,'')))) + '</DEPARTMENT_ACCOUNTS_K_TYPE>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_K_DEP_ACC>' + CHAR(10)	
						 /*поле TMC - линк таблицы DICTION*/
						 + SPACE(4) + '<G_PROV_AP_K_TMC>' + CHAR(10)
								+ SPACE(5) + '<DICTION_K_NAME>' + RTRIM(LTRIM(ISNULL(GP.DEPARTMENT_ACCOUNTS_K_code, ''))) + '</DICTION_K_NAME>'  + CHAR(10)
								+ SPACE(5) + '<DICTION_K_code>' + RTRIM(LTRIM(STR(COALESCE(GP.DEPARTMENT_ACCOUNTS_K_TYPE,'')))) + '</DICTION_K_code>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_K_TMC>' + CHAR(10)	
						 + SPACE(4) + '<G_PROV_AP_K_INDATE>' + CASE WHEN convert(varchar(10),ISNULL(GP.G_PROV_AP_K_INDATE,''),104) = '01.01.1900' THEN '' ELSE convert(varchar(10),ISNULL(GP.G_PROV_AP_K_INDATE,''),104) end + '</G_PROV_AP_K_INDATE>'  + CHAR(10)	
						 /*поле SGU - линк таблицы KOSGU*/
						 + SPACE(4) + '<G_PROV_AP_K_SGU>' + CHAR(10)
								+ SPACE(5) + '<KOSGU_SGU_K_code>' + RTRIM(LTRIM(ISNULL(GP.KOSGU_SGU_K_code, ''))) + '</KOSGU_SGU_K_code>'  + CHAR(10)
								+ SPACE(5) + '<KOSGU_SGU_K_NAME>' + RTRIM(LTRIM(ISNULL(GP.KOSGU_SGU_K_NAME, ''))) + '</KOSGU_SGU_K_NAME>'  + CHAR(10)
								+ SPACE(5) + '<KOSGU_SGU_K_ls_ekr>' + RTRIM(LTRIM(STR(COALESCE(GP.KOSGU_SGU_K_ls_ekr,'')))) + '</KOSGU_SGU_K_ls_ekr>'  + CHAR(10)
						 + SPACE(4) + '</G_PROV_AP_K_SGU>' + CHAR(10)			
						 /*поле AP1 - линк таблицы OSNOV*/
						 + SPACE(4) + '<G_PROV_AP_K_AP1>' + CHAR(10)
								/*таблица OSNOV*/
								+ SPACE(5) + '<OSNOV_AP1_K_TYPE_LINK>' + RTRIM(LTRIM(STR(COALESCE(GP.OSNOV_AP1_K_TYPE_LINK,'')))) + '</OSNOV_AP1_K_TYPE_LINK>'  + CHAR(10)
								+ SPACE(5) + '<OSNOV_AP1_K_doc_link>' +  RTRIM(LTRIM(STR(COALESCE(GP.OSNOV_AP1_K_doc_link,'')))) + '</OSNOV_AP1_K_doc_link>'  + CHAR(10)
									/*поле LINK_G_PROV - линк таблицы G_PROV*/
									+ SPACE(6) + '<G_PROV_AP1_K_NUMBER>' + RTRIM(LTRIM(ISNULL(GP.G_PROV_AP1_K_NUMBER, ''))) + '</G_PROV_AP1_K_NUMBER>'  + CHAR(10)	
									+ SPACE(6) + '<G_PROV_AP1_K_DATE>' + CASE WHEN convert(varchar(10),ISNULL(GP.G_PROV_AP1_K_DATE,''),104) = '01.01.1900' THEN '' ELSE convert(varchar(10),ISNULL(GP.G_PROV_AP1_K_DATE,''),104) end + '</G_PROV_AP1_K_DATE>'  + CHAR(10)						
									+ SPACE(6) + '<S_OBJECTS_AP1_K_CODE>' + RTRIM(LTRIM(ISNULL(GP.S_OBJECTS_AP1_K_CODE, ''))) + '</S_OBJECTS_AP1_K_CODE>'  + CHAR(10)
									+ SPACE(6) + '<S_OBJECTS_AP1_K_NAME>' + RTRIM(LTRIM(ISNULL(GP.S_OBJECTS_AP1_K_NAME, ''))) + '</S_OBJECTS_AP1_K_NAME>'  + CHAR(10)
									+ SPACE(6) + '<G_PROV_AP1_K_DATE_PROV>' + RTRIM(LTRIM(ISNULL(GP.S_OBJECTS_AP1_K_CODE, ''))) + '</G_PROV_AP1_K_DATE_PROV>'  + CHAR(10)			
									+ SPACE(6) + '<G_PROV_AP1_K_SUMMA>' + RTRIM(LTRIM(STR(COALESCE(GP.G_PROV_AP1_K_SUMMA,0),18,4))) + '</G_PROV_AP1_K_SUMMA>'  + CHAR(10)	
									+ SPACE(6) + '<G_PROV_AP1_K_COMMENT>' + RTRIM(LTRIM(ISNULL(GP.G_PROV_AP1_K_COMMENT, ''))) + '</G_PROV_AP1_K_COMMENT>'  + CHAR(10)	
									+ SPACE(6) + '<G_PROV_AP1_K_GET_STORE>' + RTRIM(LTRIM(STR(COALESCE(GP.G_PROV_AP1_K_GET_STORE,'')))) + '</G_PROV_AP1_K_GET_STORE>'  + CHAR(10)		
										+ SPACE(7) + '<department_accounts_AP1_K_CODE>' + ISNULL(GP.department_accounts_AP1_K_CODE, '') + '</department_accounts_AP1_K_CODE>'  + CHAR(10)		
						 + SPACE(4) + '</G_PROV_AP_K_AP1>' + CHAR(10)	
						 /*поле AP2 - линк таблицы DOP_CLASSIF*/
						 + SPACE(4) + '<G_PROV_AP_K_AP2>' + CHAR(10)
								+ SPACE(5) + '<DOP_CLASSIF_K_code>' + RTRIM(LTRIM(ISNULL(GP.DOP_CLASSIF_K_code, ''))) + '</DOP_CLASSIF_K_code>'  + CHAR(10)
								+ SPACE(5) + '<DOP_CLASSIF_K_NAME>' + RTRIM(LTRIM(ISNULL(GP.DOP_CLASSIF_K_NAME, ''))) + '</DOP_CLASSIF_K_NAME>'  + CHAR(10)
						  + SPACE(4) + '</G_PROV_AP_K_AP2>' + CHAR(10)
						  + SPACE(4) + '<G_PROV_AP_K_AP3>' + RTRIM(LTRIM(ISNULL(GP.DOP_CLASSIF_K_code, ''))) + '</G_PROV_AP_K_AP3>'  + CHAR(10)
					+ SPACE(3) + '</G_PROV_AP_K>' + CHAR(10)
					 FROM
						#PROV_DOC P
						INNER JOIN #G_PROV_AP_FULL GP ON GP.G_PROV_LINK = P.G_PROV_LINK
					WHERE 
						P.G_PROV_LINK = @GPROV_LINK
					
			END

			set @N_STR = @N_STR + 1 
			FETCH NEXT FROM @Cur2 INTO @GPROV_LINK
		END

		CLOSE @Cur2
		DEALLOCATE @Cur2
		
		FETCH NEXT FROM @Cur1 INTO @DEP_LINK
	END

	--set @N_STR = @N_STR + 1 
	
	
	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
	SELECT @lcFNAME, SPACE(1) + '</Org>'	
END

CLOSE @Cur1
DEALLOCATE @Cur1



INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, '</Exchange>'


SET NOCOUNT OFF

select * from #OUTPUT order by [ID]
--select OUT_TEXT from #OUTPUT order by [ID]







GO


GRANT EXECUTE ON dbo.[SS_PROV_EXPORT] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_PKG_LIST_POST_DELETE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_PKG_LIST_POST_DELETE]

GO

CREATE     PROCEDURE dbo.SA_PKG_LIST_POST_DELETE
	@varKSintLINK	INT,
	@varKSintLINK_PKG INT 
AS
DECLARE @varKStrancount	int,
	@varKSObjectLink	int,
	@varKSEventText	varchar(254)

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

	DELETE FROM dbo.pkg_post_date  
	WHERE link_post = @varKSintLINK AND link_pkg = @varKSintLINK_PKG
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END

IF @@TRANCOUNT > @varKStrancount
	BEGIN
		SELECT @varKSEventText = 'Справочник "Должности ПКГ" ' + [name] from dbo.post where link = @varKSintLINK
		SELECT @varKSObjectLink = LINK FROM S_OBJECTS WHERE CODE = 'PKG_OKLAD'
		EXECUTE WF_GENERATEEVENT 'Удаление из справочника', @varKSEventText, @varKSObjectLink, 'PKG_OKLAD', @varKSintLINK
		COMMIT TRAN
	END
RETURN 0


GO


GRANT EXECUTE ON dbo.[SA_PKG_LIST_POST_DELETE] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_N_VAC_FILL1]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_N_VAC_FILL1]

GO

CREATE    PROCEDURE dbo.SA_N_VAC_FILL1 
(
 @LINK_DOC INT OUTPUT, --Ссылка на документ.	
 @OBJ_CODE VARCHAR(50), --Код объекта
 @SR_VID TINYINT = 1, -- Прочие расчеты по среднему 1 - Компенсация за отпуск, 2 - прочее
 @LINK_VAC INT, --Ссылка на приказ
 @SR_LINK_EMPL INT  = NULL, --Прочие расчеты по среднему  Ссылка на сотрудника
 @LINK_PAYS INT = NULL, --Ссылка на вид начисления
 @TYP_PERIOD TINYINT  = NULL, --Тип расчетного периода: 1- 3 месяца, 2 - 12 месяцев
 @VID_DAYS TINYINT  = NULL,-- Способ расчета 1 - в рабочих днях, 2 - в календарных днях
 @SR_DATE1 DATETIME  = NULL,--  для расчета прочих начислений по среднему Дата начала
 @SR_DATE2 DATETIME  = NULL,--  для расчета прочих начислений по среднему Дата окончания
 @SR_DATE DATETIME  = NULL,--  для расчета прочих начислений по среднему Дата начала расчетного периода
 @RECALC TINYINT = 0, -- 0 Полный расчет. расчет начинается с таблицы 3 
			-- 1 - не надо рассчитывать по видам начислений
			-- 2 - не надо рассчитывать по месяцам
			-- 3 - не надо рассчитывать средние суммы
 @OPER TINYINT = 0, -- 1 - сформировать операции
 @LINK_DEP INT = NULL
)
AS

SET NOCOUNT ON

-- Определение типа расчетного периода
SET @TYP_PERIOD = CASE WHEN COALESCE(@TYP_PERIOD,0) = 0 THEN
			CASE RTRIM(LTRIM(@OBJ_CODE))
				WHEN 'DOCUMENTS_ADD_FURLOUGH' THEN dbo.sa_get_option_by_code('FURLOUGH_OPT2')
				WHEN 'DOCUMENTS_CALC_TRAVEL' THEN dbo.sa_get_option_by_code('CALC_TRAVEL_OPT1')
				WHEN 'DOCUMENTS_CALC_AVG' THEN 1
				ELSE NULL
			END
		ELSE @TYP_PERIOD END
-- Определение способа расчета
SET @VID_DAYS = CASE WHEN COALESCE(@VID_DAYS,0) = 0 THEN
			CASE RTRIM(LTRIM(@OBJ_CODE))
				WHEN 'DOCUMENTS_ADD_FURLOUGH' THEN dbo.sa_get_option_by_code('FURLOUGH_OPT3')
				WHEN 'DOCUMENTS_CALC_TRAVEL' THEN dbo.sa_get_option_by_code('CALC_TRAVEL_OPT2')
				WHEN 'DOCUMENTS_CALC_AVG' THEN 2
				ELSE NULL
			END
		ELSE @VID_DAYS END
---инит
DECLARE 
 @LINK_EMPL INT, --Ссылка на сотрудника
 @DATE_BEGIN DATETIME, --Начало отпуска, командировки
 @DATE_BEGIN2 DATETIME, --Начало отпуска, командировки
 @DATE_END DATETIME, --Окончание отпуска, командировки
 @REF_TYP INT, --Ссылка на вид отпуска, командировки
 @order_link int, 
 @NEW_DATE_END DATETIME,
 @NEW_DATE_BEG DATETIME,
 @UCHET_PREM TINYINT,
 @comment varchar(100),
 @HOLIDAY TINYINT,
 @NO_RAION TINYINT

DECLARE @UNAME VARCHAR(30)
SET @UNAME = CASE WHEN DBO.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPT10') = 1 THEN COALESCE(dbo.AdminGetUserFIO(default),'') ELSE '' END
SET @UNAME = @UNAME + CASE WHEN LEN(@UNAME) > 0 THEN ':' ELSE '' END

IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_ADD_FURLOUGH'
BEGIN

	SELECT @LINK_EMPL = EMPL_LINK, @LINK_PAYS = COALESCE(@LINK_PAYS,LINK_PAYS), 
		@DATE_BEGIN = DATE_BEGIN,
		@SR_DATE = COALESCE(@SR_DATE, (select min(DATE_BEGIN) from dbo.ITEM_VACATION IV1 WHERE IV1.order_link = IV.order_link and IV1.EMPL_LINK = IV.EMPL_LINK)), 
		@DATE_END = DATE_END,
		@REF_TYP = IV.TYPE_LINK, @order_link = order_link,
		@comment = @UNAME + 'Начисл.отпускных:' + COALESCE(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM(VV.[NAME])),30) + ' №'+RTRIM(LTRIM([NUMBER])) + ' от ' + CONVERT(VARCHAR(10),[DATE],104),
		@HOLIDAY = VV.HOLIDAY, --С учетом праздничных
		@LINK_DEP = COALESCE(@LINK_DEP,O.DEP_LINK)
	FROM dbo.ORDERS O INNER JOIN dbo.ITEM_VACATION IV ON IV.ORDER_LINK = O.LINK
		INNER JOIN dbo.VACATION_VID VV ON IV.TYPE_LINK = VV.LINK WHERE IV.LINK = @LINK_VAC

	DECLARE	@DATE_BREAK DATETIME	-- дата отзыва из отпуска
	DECLARE	@DATE_BREAK_NEW_BEGIN DATETIME	-- дата отзыва из отпуска

	-- Уменьшение: об отзыве, о выходе из отпуска по уходу за ребенком
	IF EXISTS(SELECT * FROM ITEM_VACATION_BREAK IVB WHERE IVB.ACTIVE = 1 AND ISNULL(BREAK_WORK_DAYS,0) != 0 AND IVB.VAC_LINK = @LINK_VAC) BEGIN

		DECLARE @BREAK_WORK_DAYS INT	-- количество рабочих дней отзва
		DECLARE @LEN_KAL_DAYS INT	-- количество календарных дней продления
		DECLARE @EMPL_LINK INT		-- ссылка на сотрудника
		--
		SELECT	TOP 1
			@EMPL_LINK = EMPL_LINK,
			@DATE_BREAK = DATE_BREAK,
			@BREAK_WORK_DAYS = BREAK_WORK_DAYS,
			@LEN_KAL_DAYS = LEN_KAL_DAYS
		FROM	ITEM_VACATION_BREAK IVB
		WHERE	IVB.ACTIVE = 1
			AND ISNULL(BREAK_WORK_DAYS,0) != 0
			AND IVB.VAC_LINK = @LINK_VAC
		--
		SET ROWCOUNT @BREAK_WORK_DAYS
		SELECT	T.DATE
		INTO	#TEMP_TABLE
		FROM
		(
		SELECT	[DATE]  = dbo.ConvertDMY2Date(GD.DAY, MONTH(G.PERIOD), Year(G.PERIOD)),
			[HOURS] = MAX(HOURS)
		FROM	GRAPHICS G INNER JOIN dbo.GRAPHIC_DAYS GD ON GD.LINK_UP=G.LINK 
		WHERE	G.GRAPH_LINK = dbo.kd_GetEmplGr(@EMPL_LINK)
			AND dbo.ConvertDMY2Date(GD.DAY, MONTH(G.PERIOD), Year(G.PERIOD)) BETWEEN @DATE_BREAK AND @DATE_BREAK + @BREAK_WORK_DAYS + @LEN_KAL_DAYS
		GROUP	BY dbo.ConvertDMY2Date(GD.DAY, MONTH(G.PERIOD), Year(G.PERIOD))
		) T
		WHERE	T.HOURS > 0
			AND T.DATE >= @DATE_BREAK
		SET ROWCOUNT 0
		--
		SET @DATE_BREAK_NEW_BEGIN = (SELECT TOP 1 DATE + 1 FROM #TEMP_TABLE ORDER BY DATE DESC)
		SET @NEW_DATE_END = @DATE_END + @LEN_KAL_DAYS - 1 + 1  -- расчет окончания отпуска с учетом отзыва
	
		DROP TABLE #TEMP_TABLE
		SET @DATE_END = COALESCE(@NEW_DATE_END,@DATE_END)

	END 
	ELSE BEGIN
		SET @NEW_DATE_END = (SELECT MIN(ivb.DATE_BREAK - 1) FROM dbo.item_vacation iv inner join dbo.item_vacation_break ivb on ivb.vac_link = iv.link WHERE ivb.ACTIVE = 1 AND iv.LINK = @LINK_VAC)
		SET @DATE_END = (CASE WHEN COALESCE(@NEW_DATE_END,@DATE_END) <  @DATE_END THEN COALESCE(@NEW_DATE_END,@DATE_END) ELSE @DATE_END END)
	END
	-- Увеличение: о продлении по болезни
	SET @NEW_DATE_END = (SELECT MAX(ivb.NEW_DATE_END) FROM item_vacation iv inner join item_vacation_dis ivb on ivb.vac_link = iv.link WHERE  ivb.ACTIVE = 1 AND iv.LINK = @LINK_VAC)
	SET @DATE_END = (CASE WHEN COALESCE(@NEW_DATE_END,@DATE_END) >  @DATE_END THEN COALESCE(@NEW_DATE_END,@DATE_END) ELSE @DATE_END END)

END


IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_CALC_TRAVEL'
BEGIN
	SELECT @LINK_EMPL = EMPL_LINK, @LINK_PAYS = COALESCE(@LINK_PAYS,LINK_PAYS), 
		@SR_DATE = COALESCE(@SR_DATE, DATE_BEGIN), 
		@DATE_BEGIN = DATE_BEGIN, @DATE_END = DATE_END, 
		@REF_TYP = IT.TYPE_LINK,
		@comment = @UNAME + 'Начисл.командир.:' + COALESCE(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM(KV.[NAME])),30) + ' №'+RTRIM(LTRIM([NUMBER])) + ' от ' + CONVERT(VARCHAR(10),[DATE],104),
		@LINK_DEP = COALESCE(@LINK_DEP,O.DEP_LINK)
	FROM dbo.ORDERS O INNER JOIN dbo.item_travel IT ON IT.ORDER_LINK = O.LINK
		INNER JOIN dbo.KOMAND_VID KV ON IT.TYPE_LINK = KV.LINK WHERE IT.LINK = @LINK_VAC

	-- Увеличение: о продлении 
	SET @NEW_DATE_END = (SELECT MAX(ivb.NEW_DATE_END) FROM item_travel iv inner join item_travel_long ivb on ivb.TRAVEL_LINK = iv.link WHERE ivb.ACTIVE = 1 AND iv.LINK = @LINK_VAC)
	SET @DATE_END = (CASE WHEN COALESCE(@NEW_DATE_END,@DATE_END) >  @DATE_END THEN COALESCE(@NEW_DATE_END,@DATE_END) ELSE @DATE_END END)

END

DECLARE @PDAY NUMERIC(5,2)
SET @PDAY = 0

IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_CALC_AVG'
BEGIN

	SELECT @LINK_EMPL = EMPL_LINK, 
		@SR_DATE = COALESCE(@SR_DATE, DIS_DATE), 
		@DATE_BEGIN = DIS_DATE + 1, 
		@DATE_END = (DIS_DATE + 1) + CASE WHEN ISNULL(VAC_KOMPENS_DAY,0) > 0 THEN CONVERT(INT, VAC_KOMPENS_DAY) ELSE 0 END,
		@PDAY = CASE WHEN ISNULL(VAC_KOMPENS_DAY,0) > 0 THEN VAC_KOMPENS_DAY - CONVERT(INT, VAC_KOMPENS_DAY) ELSE 0 END,
		@REF_TYP = IT.REASON,
		@comment = @UNAME + 'Компенс.за неисп.отпуск:' + COALESCE(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM(KV.[NAME])),30) + ' №'+RTRIM(LTRIM([NUMBER])) + ' от ' + CONVERT(VARCHAR(10),[DATE],104),
		@LINK_DEP = COALESCE(@LINK_DEP,O.DEP_LINK), 
		@SR_DATE1 = DIS_DATE + 1, 
		@SR_DATE2 = DIS_DATE + CASE WHEN ISNULL(VAC_KOMPENS_DAY,0) > 0 THEN CONVERT(INT, VAC_KOMPENS_DAY) ELSE 0 END
	FROM dbo.ORDERS O INNER JOIN dbo.ITEM_DIS_FACE IT ON IT.ORDER_LINK = O.LINK
		INNER JOIN [dbo].[DICTION] KV ON IT.REASON = KV.LINK 
	WHERE IT.LINK = @LINK_VAC AND ISNULL(VAC_KOMPENS_DAY,0) > 0

	IF @LINK_EMPL IS NULL
		SELECT @LINK_EMPL = @SR_LINK_EMPL, @comment = @UNAME + 'Начисл.средн.:' + COALESCE(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM(P.[NAME])),30)
		FROM dbo.PAYS P WHERE LINK = @LINK_PAYS

	SELECT @LINK_DEP = DEP_LINK FROM DBO.USER_DEP WHERE @LINK_DEP IS NULL
END

--- Учет премии в расчете
IF (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1)
	SET @UCHET_PREM = COALESCE(dbo.sa_get_option_by_code('FURLOUGH_OPT8'),1)
ELSE
	SET @UCHET_PREM = COALESCE(dbo.sa_get_option_by_code('CALC_TRAVEL_OPT5'),1)

---

DECLARE 
 @SystPay INT,
 @RP INT, --Размер расчетного периода 
 @DATE_BEGIN_RP DATETIME, --Начало расчетного периода
 @DATE_END_RP DATETIME, --Конец расчетного периода
 @DATE_BEGIN_WRK DATETIME, --Дата приема сотрудника
 @DATE_END_WRK DATETIME, --Дата увольнения сотрудника
 @LINK_PERS INT, --Ссылка на физ.лицо
 @DEP_LINK INT,
 @MAX_DATE DATETIME,
 @I INT,
 @varKSsoLink INT

SET @RP = (CASE @TYP_PERIOD WHEN 1 THEN 3 WHEN 2 THEN 12 ELSE 0 END)

SELECT TOP 1 
 @LINK_PERS = PERS_LINK,  @SystPay = SYST_PAY, @DEP_LINK = DEP_LINK, 
 @DATE_BEGIN_RP = dbo.kd_DateBeginWork(LINK,@DATE_BEGIN), 
 @DATE_END_RP = dbo.kd_DateEndWork(LINK,@DATE_BEGIN), 
 @MAX_DATE = '29990101',
 @NO_RAION = ISNULL(NO_RAION,0) 
FROM dbo.EMPL WHERE LINK = @LINK_EMPL

declare @EmplNumStake numeric(5,2)
Set @EmplNumStake = Coalesce(dbo.ku_GetEmplNumStake(@LINK_EMPL,DEFAULT),0)

---Определение расчетного периода
IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_CALC_AVG'
	SELECT @DATE_BEGIN_RP = @SR_DATE, @DATE_END_RP = dbo.DateEndOfMonth(DATEADD(MONTH, @RP-1,@SR_DATE)), @DATE_BEGIN = @SR_DATE1, @DATE_END = @SR_DATE2, @LINK_EMPL = @SR_LINK_EMPL
ELSE BEGIN
	
	SELECT 
	@DATE_BEGIN_RP = dbo.DateBeginOfMonth( CASE WHEN @DATE_BEGIN_RP > @SR_DATE THEN @DATE_BEGIN_RP ELSE @SR_DATE END),
	@DATE_END_RP = dbo.DateEndOfMonth( CASE WHEN COALESCE(@DATE_END_RP,@MAX_DATE) < dbo.DateEndOfMonth(DATEADD(MONTH, @RP-1,@SR_DATE)) THEN COALESCE(@DATE_END_RP,@MAX_DATE) ELSE dbo.DateEndOfMonth(DATEADD(MONTH, @RP-1,@SR_DATE)) END ),
	@SR_VID = 1
	
	--Проверим, чтобы рассчитанная дата окончания расчетного периода не оказалась больше даты начала отпуска
	IF YEAR(@DATE_END_RP) * 100 + MONTH(@DATE_END_RP) >= YEAR(@DATE_BEGIN) * 100 + MONTH(@DATE_BEGIN) 
		SET @DATE_END_RP = dbo.DateBeginOfMonth(@DATE_BEGIN) - 1
	
END	

---
DECLARE @MINROT NUMERIC(18,2)
SET @MINROT = dbo.minrot2(@DATE_BEGIN) * @EmplNumStake

--- Если новый расчет, то получить линк документа
DECLARE @NUMBER VARCHAR(10), @DATE_DOC DATETIME
IF COALESCE(@LINK_DOC,0)  = 0
BEGIN
	exec dbo.SALARY_NEXT_NUM @NUMBER OUT, @OBJ_CODE
	SET @DATE_DOC = (Select top 1 WORKDATE from USER_DATES)
	exec dbo.SD_N_VACATION_SAVE @LINK_DOC OUT,@OBJ_CODE, @NUMBER, @DATE_DOC, @LINK_PAYS, @comment, 0, @LINK_EMPL, 0, 0, @TYP_PERIOD, 
			@DATE_BEGIN, @DATE_END, 0, @VID_DAYS, @LINK_VAC, 0, @SR_VID, @DATE_BEGIN_RP, @LINK_DEP
END
ELSE
	SET @DATE_DOC = (SELECT [DATE] FROM SDOC WHERE LINK = @LINK_DOC)

--
UPDATE dbo.SDOC_AVAC 
SET INSTR = 1
WHERE LINK_UP = @LINK_DOC


/***************************************************************************************/
--- вспомогательный период. Вычисление коэффициентов индексации зарплаты по время отпуска
DECLARE @INDEX TABLE ([DATE] DATETIME, [DATE2] DATETIME, SUMMA NUMERIC(18,2), INDEX_VAL NUMERIC(18,10))

/*Перечень сотрудников, которым НЕ нужно индексировать*/
DECLARE @NO_INDEX_EMPL table (link int)
INSERT INTO @NO_INDEX_EMPL (link)
SELECT LINK_EMPL FROM dbo.GROUPS_EMPL G inner join dbo.GROUPS_EMPL_REF E on E.LINK_GROUP = G.LINK
WHERE G.LINK = [dbo].[sa_get_option_by_code]('DICTIONARY_INDEX_OPT4')

--Способ индексации 
--Использовать коэффициент индексации из справочника,Рассчитывать коэффициент от оклада сотрудника,Рассчитывать коэффициент для каждого начисления
DECLARE @INDEX_OPT2 int 
SET @INDEX_OPT2 = [dbo].[sa_get_option_by_code]('DICTIONARY_INDEX_OPT2')

/*Перечень надбавок, которые НЕ нужно индексировать*/
DECLARE @NO_INDEX_PAY table (link int)
INSERT INTO @NO_INDEX_PAY (link)
SELECT P.link
FROM dbo.PAY_GROUPS G inner join PAYS_REF PR on PR.LINK_GROUPS = G.LINK
	inner join  dbo.PAYS P on P.LINK = PR.LINK_PAYS
WHERE G.LINK = [dbo].[sa_get_option_by_code]('DICTIONARY_INDEX_OPT3')

declare @pn2 table (link_pay int, period datetime, summa numeric(18,2))	

--на случай повышения после окончания расчётного периода и до наступления отпуска
INSERT INTO @INDEX ([DATE], [DATE2], SUMMA, INDEX_VAL)
VALUES (@DATE_END_RP,@DATE_BEGIN,0,1)

--Коэф вычисляется из окладов и надбавок
IF @INDEX_OPT2 >= 2 AND NOT EXISTS (SELECT * FROM @NO_INDEX_EMPL WHERE LINK = @LINK_EMPL)
BEGIN

	--на случай повышения ОКЛАДОВ во время отпуска
	INSERT INTO @INDEX
	SELECT DISTINCT      
		[DATE] = CASE WHEN @DATE_BEGIN >= DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END, 
		NULL,
		0,
		1
	FROM 
		DBO.DICTIONARY_PAYS_EMPL_FN(@DATE_END, @LINK_EMPL, 0, DEFAULT, @DEP_LINK, DEFAULT) S
	WHERE
		EXISTS (SELECT * FROM dbo.WAY_CALC WC WHERE WC.TYPE = 1 AND WC.CODE = S.WAY_CALC AND WC.OKLAD = 1)
		AND
		EXISTS (Select * FROM dbo.group_pays(@LINK_PAYS) T WHERE T.PAY_LINK = s.LINK_PAYS)
		AND
		NOT EXISTS (SELECT * FROM @NO_INDEX_PAY A WHERE A.LINK = s.LINK_PAYS)

	UPDATE A
	SET A.DATE2 = ISNULL((SELECT MIN(B.[DATE])-1 FROM @INDEX B WHERE B.[DATE] > A.[DATE]),@DATE_END)
	FROM @INDEX A
	
	DECLARE @Cur1 CURSOR, @Cur2 CURSOR, @NEXT_DATE DATETIME, @NEXT_DATE2 DATETIME, @INDEX_VAL NUMERIC(18,10)
	SET @Cur1 = CURSOR FORWARD_ONLY

	FOR SELECT [DATE] FROM @INDEX ORDER BY [DATE]

	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @NEXT_DATE
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
			
			UPDATE @INDEX 
			SET SUMMA = (SELECT SUM(SUMMA) FROM dbo.SA_ALL_PAYS_ALL_DATE0(@LINK_EMPL, @NEXT_DATE, DEFAULT, @LINK_DEP) S 
							INNER JOIN dbo.PAYS P ON P.LINK = S.LINK_PAY
							INNER JOIN dbo.WAY_CALC W ON P.WAY_CALC = W.CODE 
							WHERE LINK_SOVM = 0 AND W.[TYPE] = 1 AND W.OKLAD = 1 )
			WHERE 
				[DATE] = @NEXT_DATE

			SET @INDEX_VAL = 1
		
			SET @Cur2 = CURSOR FORWARD_ONLY
			FOR SELECT [DATE] FROM @INDEX WHERE [DATE] <= @NEXT_DATE ORDER BY [DATE]
			OPEN @Cur2
			FETCH NEXT FROM @Cur2 INTO @NEXT_DATE2
			WHILE (@@fetch_status <> -1)
			BEGIN
				IF (@@fetch_status <> -2)
				BEGIN
					SET @INDEX_VAL = @INDEX_VAL 
					* (CASE WHEN (SELECT TOP 1 SUMMA FROM @INDEX WHERE [DATE] < @NEXT_DATE2 ORDER BY [DATE] DESC) <> 0
						THEN
							(SELECT SUMMA / (SELECT TOP 1 SUMMA FROM @INDEX WHERE [DATE] < @NEXT_DATE2 ORDER BY [DATE] DESC) FROM @INDEX WHERE [DATE] = @NEXT_DATE2)
						ELSE 1
						END)
				END
				FETCH NEXT FROM @Cur2 INTO @NEXT_DATE2
			END

			CLOSE @Cur2
			DEALLOCATE @Cur2				

			UPDATE @INDEX 
			SET INDEX_VAL = @INDEX_VAL
			WHERE [DATE] = @NEXT_DATE
		
		END

		FETCH NEXT FROM @Cur1 INTO @NEXT_DATE
	END

	CLOSE @Cur1
	DEALLOCATE @Cur1

	--убираются вспомогательный период
	DELETE FROM @INDEX WHERE DATE2 < @DATE_BEGIN

END --IF NOT EXISTS (SELECT * FROM @NO_INDEX_EMPL WHERE LINK = @LINK_EMPL

--Коэф вычисляется из таблицы
IF @INDEX_OPT2 <= 1 AND NOT EXISTS (SELECT * FROM @NO_INDEX_EMPL WHERE LINK = @LINK_EMPL)
BEGIN

	INSERT INTO @INDEX ([DATE], [DATE2], SUMMA, INDEX_VAL)
	SELECT TOP 1 @DATE_END_RP+1, [DATE], 0, [KOEF] FROM dbo.DICTIONARY_INDEX WHERE [DATE] BETWEEN @DATE_END_RP+1 AND @DATE_BEGIN ORDER BY [DATE] DESC

	INSERT INTO @INDEX ([DATE], [DATE2], SUMMA, INDEX_VAL)
	SELECT TOP 1 [DATE], @DATE_END, 0, [KOEF] FROM dbo.DICTIONARY_INDEX WHERE [DATE] BETWEEN @DATE_BEGIN+1 AND @DATE_END ORDER BY [DATE] DESC	

	UPDATE A
	SET A.DATE2 = ISNULL((SELECT MIN(B.[DATE])-1 FROM @INDEX B WHERE B.[DATE] > A.[DATE]),@DATE_END)
	FROM @INDEX A	
	
END	
--Коэф. 1 для тех, кому не надо считать коэф
IF EXISTS (SELECT * FROM @NO_INDEX_EMPL WHERE LINK = @LINK_EMPL)
BEGIN

	INSERT INTO @INDEX ([DATE], [DATE2], SUMMA, INDEX_VAL)
	SELECT TOP 1 @DATE_END_RP+1, @DATE_END, 0, 1

	UPDATE A
	SET A.DATE2 = ISNULL((SELECT MIN(B.[DATE])-1 FROM @INDEX B WHERE B.[DATE] > A.[DATE]),@DATE_END)
	FROM @INDEX A	
	
END

/***************************************************************************************/

--
IF @RECALC = 0  --- Расчет сумм по видам начислений
BEGIN

	--- Промежуточная база расчета
	CREATE TABLE #BASE1 (
		PERIOD DATETIME,
		NADB NUMERIC(18,2),
		CODE_PAY VARCHAR(254),
		NAME_PAY VARCHAR(254), 
		WAY_CALC INT,
		LINK_PAY INT,
		SUMMA NUMERIC(18,2),
		SUM0 NUMERIC(18,2),
		KOEF  NUMERIC(18,4),
		CV	NUMERIC(18,2),
		LINK_VKR INT,
		DATE1 DATETIME,
		DATE2 DATETIME
	)


	DECLARE @DEFAULT_KBK INT
	SET @DEFAULT_KBK = (Select TOP 1 KBK.LINK_KBK FROM dbo.KU_EmplStafKBK(default) KBK WHERE KBK.LINK_EMPL = @LINK_EMPL)

	INSERT INTO #BASE1 (PERIOD, NADB, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, SUM0, KOEF, CV, LINK_VKR, DATE1, DATE2)
	exec dbo.SD_BASE_SUM_PAY_DIF_PERIODS @LINK_PAYS, @LINK_EMPL, @DATE_BEGIN_RP, @DATE_END_RP, @OBJ_CODE, @DATE_BEGIN, @DATE_END_RP

	IF COALESCE((SELECT SUM(SUMMA) FROM #BASE1),0) = 0 BEGIN

		SELECT TOP 1  @DATE_BEGIN_RP = dbo.kd_DateBeginWork(LINK,@DATE_BEGIN), @DATE_END_RP = dbo.kd_DateEndWork(LINK,@DATE_BEGIN)
		FROM dbo.EMPL WHERE LINK = @LINK_EMPL
		---	
		IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_CALC_AVG'
			SELECT @DATE_BEGIN_RP = DATEADD(MONTH,-@RP,@SR_DATE), @DATE_END_RP = dbo.DateEndOfMonth(DATEADD(MONTH, (@RP-1)+@RP,@SR_DATE))
		ELSE 
			SELECT @DATE_BEGIN_RP = dbo.DateBeginOfMonth( CASE WHEN @DATE_BEGIN_RP > DATEADD(MONTH, -(@RP+@RP),@DATE_BEGIN) THEN @DATE_BEGIN_RP ELSE DATEADD(MONTH, -@RP*2,@DATE_BEGIN) END),
			@DATE_END_RP = dbo.DateEndOfMonth( CASE WHEN COALESCE(@DATE_END_RP,@MAX_DATE) < DATEADD(MONTH, -((CASE WHEN @RP > 0 THEN 1 ELSE 0 END)+@RP),@DATE_BEGIN) THEN COALESCE(@DATE_END_RP,@MAX_DATE) ELSE DATEADD(MONTH, -((CASE WHEN @RP > 0 THEN 1 ELSE 0 END)+@RP),@DATE_BEGIN) END )

		IF COALESCE(@DATE_END_RP,@MAX_DATE) < @DATE_BEGIN_RP
			SET @DATE_END_RP = dbo.DateEndOfMonth(@DATE_BEGIN_RP)
		---
		INSERT INTO #BASE1 (PERIOD, NADB, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, SUM0, KOEF, CV, LINK_VKR, DATE1, DATE2)
		exec dbo.SD_BASE_SUM_PAY_DIF_PERIODS @LINK_PAYS, @LINK_EMPL, @DATE_BEGIN_RP, @DATE_END_RP, @OBJ_CODE, @DATE_BEGIN, @DATE_END_RP

		IF COALESCE((SELECT SUM(SUMMA) FROM #BASE1),0) = 0 BEGIN
			SET @DATE_BEGIN_RP = dbo.DateBeginOfMonth(@DATE_BEGIN)
			SET @DATE_END_RP = dbo.DateEndOfMonth(@DATE_BEGIN)
	
			INSERT INTO #BASE1 (PERIOD, NADB, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, SUM0, KOEF, CV, LINK_VKR, DATE1, DATE2)
			SELECT @DATE_BEGIN, 0, P.CODE, P.NAME, P.WAY_CALC, S.LINK_PAY, S.SUMMA,S.SUMMA, 1, 0, S.LINK_KBK, @DATE_BEGIN_RP, dbo.DateEndOfMonth(@DATE_BEGIN) 
			FROM 
				dbo.SA_ALL_PAYS_ALL_DATE0(@LINK_EMPL, @DATE_BEGIN, DEFAULT, @LINK_DEP) S
				inner join dbo.pays P on s.link_pay = p.link
			WHERE s.link_pay IN (SELECT T.PAY_LINK FROM dbo.group_pays(@LINK_PAYS) T)
	
		END
		
	END

--индексируем на коэффициенты повышения после расчетного периода и до наступления отпуска

	DECLARE @INDEX2 NUMERIC(18,10)
	SET @INDEX2 = ISNULL((SELECT TOP 1 INDEX_VAL FROM @INDEX WHERE [DATE] <= @DATE_BEGIN ORDER BY [DATE] DESC),1)

	IF @INDEX2 > 1 BEGIN

		UPDATE B
		SET B.KOEF = B.KOEF * @INDEX2, B.SUMMA = B.SUMMA * @INDEX2
		FROM
			#BASE1 B
		WHERE
			B.PERIOD < @DATE_END_RP
			AND
			NOT EXISTS (SELECT * FROM @NO_INDEX_PAY N WHERE N.LINK = B.LINK_PAY)

		--убираются вспомогательный период
		UPDATE @INDEX SET INDEX_VAL = 1
		WHERE DATE <= @DATE_BEGIN
	
	END	--IF @INDEX2 > 1 BEGIN		

	---
	UPDATE #BASE1 SET LINK_VKR = @DEFAULT_KBK WHERE LINK_VKR IS NULL

	--- Определим, делать ли расчет в разрезе КБК
	DECLARE @KBK_OPT TINYINT
	IF (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1)
		SET @KBK_OPT = dbo.sa_get_option_by_code('FURLOUGH_OPT7')
	ELSE			
		SET @KBK_OPT = dbo.sa_get_option_by_code('CALC_TRAVEL_OPT4')

	DECLARE @isMATER tinyint
	SET @isMATER = dbo.sa_get_option_by_code('FURLOUGH_OPT12')

	IF @KBK_OPT <> 1
	BEGIN
		--- Заменить на общий коэф. индексации, если есть за один период несколько одинаковых начислений с разными источниками и разными коэффициентами индексации
		CREATE TABLE #GRP_KOEF (PERIOD DATETIME, LINK_PAY INT, GRP_KOEF NUMERIC(18,4))
		
		INSERT INTO #GRP_KOEF (PERIOD, LINK_PAY, GRP_KOEF)
		SELECT PERIOD, LINK_PAY, ROUND(SUM(SUMMA) / SUM(SUM0),4) FROM #BASE1 GROUP BY PERIOD, LINK_PAY HAVING(SUM(SUM0)) > 0
		
		UPDATE #BASE1
		SET KOEF = (SELECT TOP 1 GRP_KOEF FROM #GRP_KOEF G WHERE G.PERIOD = #BASE1.PERIOD AND G.LINK_PAY = #BASE1.LINK_PAY)
		WHERE EXISTS (SELECT * FROM #GRP_KOEF G WHERE G.PERIOD = #BASE1.PERIOD AND G.LINK_PAY = #BASE1.LINK_PAY)
		
		DROP TABLE #GRP_KOEF
	END	

	--------------------------------------------------------------------------------------------------------------
	DECLARE 
		@FURLOUGH_OPT_REG_KOEF INT, -- Расчет с учетом районного коэффициента
		@FURLOUGH_OPT_NORTH_KOEF INT -- Расчет с учетом северного коэффициента

	--Если у сотрудника указано "Не начислять районный", то рассчитываем без районного
	SET @FURLOUGH_OPT_REG_KOEF = 
			CASE RTRIM(LTRIM(@OBJ_CODE))
				WHEN 'DOCUMENTS_ADD_FURLOUGH' THEN (CASE WHEN @NO_RAION = 1 THEN 0 ELSE dbo.sa_get_option_by_code('FURLOUGH_OPT15') END)
				WHEN 'DOCUMENTS_CALC_TRAVEL' THEN (CASE WHEN @NO_RAION = 1 THEN 0 ELSE dbo.sa_get_option_by_code('CALC_TRAVEL_OPT7') END)
				WHEN 'DOCUMENTS_CALC_AVG' THEN (CASE WHEN @NO_RAION = 1 
													THEN 0 
													ELSE 
														CASE WHEN @SR_VID = 1 
															THEN dbo.sa_get_option_by_code('FURLOUGH_OPT15') 
															ELSE dbo.sa_get_option_by_code('CALC_TRAVEL_OPT7') 
														END	
												END)				
				ELSE 0
			END		

	SET @FURLOUGH_OPT_NORTH_KOEF =
			CASE RTRIM(LTRIM(@OBJ_CODE))
				WHEN 'DOCUMENTS_ADD_FURLOUGH' THEN dbo.sa_get_option_by_code('FURLOUGH_OPT16')
				WHEN 'DOCUMENTS_CALC_TRAVEL' THEN dbo.sa_get_option_by_code('CALC_TRAVEL_OPT8')
				WHEN 'DOCUMENTS_CALC_AVG' THEN 	CASE WHEN @SR_VID = 1 
													THEN dbo.sa_get_option_by_code('FURLOUGH_OPT16') 
													ELSE dbo.sa_get_option_by_code('CALC_TRAVEL_OPT8') 
												END	
				ELSE 0
			END		 

	DECLARE @NORTH_KOEF NUMERIC(6,2), @REG_KOEF NUMERIC(6,2)
	
	IF @FURLOUGH_OPT_REG_KOEF = 1 OR @FURLOUGH_OPT_NORTH_KOEF = 1
	BEGIN
	
		SET @NORTH_KOEF = DBO.SA_GET_REGION(@LINK_EMPL,@DATE_BEGIN,2) / 100
		SET @REG_KOEF = DBO.SA_GET_REGION(@LINK_EMPL,@DATE_BEGIN,1) / 100

		UPDATE #BASE1
		SET 
			SUMMA = ISNULL(SUMMA,0)
				---Накручиваем районный коэффициент, если надо
				+ (CASE WHEN @FURLOUGH_OPT_REG_KOEF = 1 AND @REG_KOEF > 0 THEN ISNULL(SUMMA,0) * @REG_KOEF ELSE 0 END)
				---Накручиваем северный коэффициент, если надо
				+ (CASE WHEN @FURLOUGH_OPT_NORTH_KOEF = 1 AND @NORTH_KOEF > 0 THEN ISNULL(SUMMA,0) * @NORTH_KOEF ELSE 0 END),

			SUM0 = ISNULL(SUM0,0)
				---Накручиваем районный коэффициент, если надо
				+ (CASE WHEN @FURLOUGH_OPT_REG_KOEF = 1 AND @REG_KOEF > 0 THEN ISNULL(SUM0,0) * @REG_KOEF ELSE 0 END)
				---Накручиваем северный коэффициент, если надо
				+ (CASE WHEN @FURLOUGH_OPT_NORTH_KOEF = 1 AND @NORTH_KOEF > 0 THEN ISNULL(SUM0,0) * @NORTH_KOEF ELSE 0 END)

	END
	--------------------------------------------------------------------------------------------------------------

	---
	Select PERIOD = MIN(PERIOD), PERIOD1 = (YEAR(PERIOD) * 100 + MONTH(PERIOD)), CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, 
		SUMMA = SUM( CASE WHEN WAY_CALC in (6,7) AND (DATEDIFF(MONTH,DATE1, DATE2) + 1) <> 0 AND @UCHET_PREM = 1 THEN 
					CONVERT(NUMERIC(18,2), SUM0 * --В размере месячной части за каждый месяц расчетного периода (если она начислена за период > 1 месяц)
						(DATEDIFF(MONTH,CASE WHEN DATE1 <= @DATE_BEGIN_RP THEN @DATE_BEGIN_RP ELSE DATE1 END,
								CASE WHEN DATE2 >= @DATE_END_RP THEN @DATE_END_RP ELSE DATE2 END) + 1)
						/ (DATEDIFF(MONTH,DATE1, DATE2) + 1))
				ELSE
					CASE WHEN WAY_CALC = 12 
					THEN
						CONVERT(NUMERIC(18,2), SUM0 * 
							CASE @isMATER
								WHEN 1 THEN 1 --1) Полностью
								WHEN 2 THEN --2) В размере месячной части за каждый месяц расчетного периода (если она начислена за период > 1 месяц)
									CONVERT(NUMERIC(18,2), (DATEDIFF(MONTH,CASE WHEN DATE1 <= @DATE_BEGIN_RP THEN @DATE_BEGIN_RP ELSE DATE1 END, 
									CASE WHEN DATE2 >= @DATE_END_RP THEN @DATE_END_RP ELSE DATE2 END) + 1))
									/ (DATEDIFF(MONTH,DATE1, DATE2) + 1)
								WHEN 3 THEN 0 --3) Вообще не включать
							ELSE 1 END)
					ELSE SUM0 
					END
			END), 
		SUM0 = SUM(SUM0),	
		KOEF, 
		LINK_VKR = (CASE WHEN @KBK_OPT = 1 then LINK_VKR else @DEFAULT_KBK end), DATE1, DATE2 
	INTO #BASE
	from #BASE1 
	where (@isMATER = 3 and WAY_CALC <> 12 or @isMATER <> 3)
	group by (YEAR(PERIOD) * 100 + MONTH(PERIOD)), CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, KOEF, (CASE WHEN @KBK_OPT = 1 then LINK_VKR else @DEFAULT_KBK end), DATE1, DATE2 

	-- Перевенем таблицу 
	DECLARE @PAYS_MONTS VARCHAR(100)
	EXEC X_GET_TABLE_NAME @PAYS_MONTS OUTPUT

	---
	EXEC M_CROSS_TABLE
		'LINK_PAY, LINK_VKR',
		'PERIOD1', 'INT',
		'SUMMA', 'NUMERIC(18,2)', 'SUM(SUMMA) AS SUMMA',
		'#BASE', @PAYS_MONTS

	DECLARE @PAYS_MONTS1 VARCHAR(100)
	SET @PAYS_MONTS1 = @PAYS_MONTS + '1'

	EXEC M_CROSS_TABLE
		'LINK_PAY, LINK_VKR',
		'PERIOD1', 'INT',
		'KOEF', 'NUMERIC(18,4)', 'MAX(KOEF) AS KOEF',
		'#BASE', @PAYS_MONTS1

	DELETE FROM dbo.SDOC_AVAC_TABLE3  WHERE LINK_UP = @LINK_DOC
	
	DECLARE @SCRIPT VARCHAR(8000)
	SET @SCRIPT = ' INSERT INTO dbo.SDOC_AVAC_TABLE3 (LINK_UP, ORDERS, LINK_PAY, LINK_KBK, SUMMA1, KOEF1, SUMMA2, KOEF2, SUMMA3, KOEF3, SUMMA4, KOEF4, SUMMA5, KOEF5, SUMMA6, KOEF6, 
				SUMMA7, KOEF7, SUMMA8, KOEF8,  SUMMA9, KOEF9, SUMMA10, KOEF10, SUMMA11, KOEF11,  SUMMA12, KOEF12)'  
			+ ' Select ' + CONVERT(VARCHAR(20),@LINK_DOC) + ', 0, P1.LINK_PAY, P1.LINK_VKR'  
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,0,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,0,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,0,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,0,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,0,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,0,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,1,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,1,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,1,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,1,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,1,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,1,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,2,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,2,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,2,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,2,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,2,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,2,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,3,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,3,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,3,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,3,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,3,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,3,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,4,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,4,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,4,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,4,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,4,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,4,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,5,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,5,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,5,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,5,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,5,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,5,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,6,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,6,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,6,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,6,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,6,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,6,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,7,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,7,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,7,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,7,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,7,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,7,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,8,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,8,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,8,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,8,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,8,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,8,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,9,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,9,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,9,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,9,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,9,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,9,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,10,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,10,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,10,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,10,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,10,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,10,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,11,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,11,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,11,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,11,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,11,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,11,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
		+ ' from ' + @PAYS_MONTS + ' P1 LEFT JOIN ' + @PAYS_MONTS1 + ' P2 ON P1.LINK_PAY = P2.LINK_PAY AND P1.LINK_VKR = P2.LINK_VKR' 

	exec (@SCRIPT)

	SET @I = 0
	UPDATE dbo.SDOC_AVAC_TABLE3  
	SET @I = @I+1, ORDERS = @I
	WHERE LINK_UP = @LINK_DOC

	UPDATE dbo.sdoc_avac 
	SET DATE_BEGIN = @DATE_BEGIN_RP, DATE_END = @DATE_END_RP
	WHERE LINK_UP = @LINK_DOC		
	
END -- IF @RECALC = 0
--SELECT * FROM dbo.SDOC_AVAC_TABLE3 WHERE LINK_UP = @LINK_DOC
---------------------------------------------
SELECT @DATE_BEGIN_RP = DATE_BEGIN, @DATE_END_RP = ISNULL(DATE_END, @DATE_END_RP)
FROM dbo.sdoc_avac WHERE LINK_UP = @LINK_DOC
---------------------------------------------		

IF @RECALC < = 1 --- Расчет сумм по месяцам
BEGIN
	---- Время
	DECLARE @WTIME TABLE(M INT, Y INT, DAYS NUMERIC(18,2), HOURS NUMERIC(18,2), DAYS_NORM NUMERIC(18,2), HOURS_NORM NUMERIC(18,2), KDAYS NUMERIC(18,2), KDAYS_N NUMERIC(18,2))

	DECLARE @LINK_GRAPH INT
	SET @LINK_GRAPH = (SELECT TOP 1 GRAPH_LINK FROM DBO.EMPL WHERE LINK = @LINK_EMPL)

	INSERT INTO @WTIME (M,Y,DAYS,HOURS,DAYS_NORM,HOURS_NORM,KDAYS,KDAYS_N)
	---Данные по табелям 
	SELECT  M, Y,
		DAYS = COALESCE(CONVERT(NUMERIC(4,0), DBO.SA_GET_EMPL_WD (@LINK_EMPL, 0, DEFAULT, dbo.ConvertDMY2Date(1,M,Y), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,M,Y)), @LINK_GRAPH, 0) ),0),
		HOURS = COALESCE(CONVERT(NUMERIC(10,2), DBO.SA_GET_EMPL_WH (@LINK_EMPL, 0, DEFAULT, dbo.ConvertDMY2Date(1,M,Y), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,M,Y)), @LINK_GRAPH, 0) ),0),
		DAYS_NORM = ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(@LINK_EMPL,M,Y)),0),
		HOURS_NORM = ISNULL(CONVERT(NUMERIC(10,2),dbo.NORM_HOURS(@LINK_EMPL,M,Y)),0),
		0,0
	FROM dbo.months_ex(@DATE_BEGIN_RP, @DATE_END_RP) M
	WHERE NOT EXISTS (SELECT * FROM @WTIME W WHERE (W.Y = M.Y AND W.M = M.M) )

	---
	IF  @VID_DAYS <> 1 BEGIN-- В календарных днях
		UPDATE @WTIME
		SET KDAYS = ISNULL(CONVERT(NUMERIC(4,0),dbo.SA_CALENDAR_DAYS_FN(@LINK_EMPL,M,Y)),0),
			KDAYS_N = ISNULL(CONVERT(NUMERIC(4,0),DAY(dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1, M, Y)))),0)

	END

	Declare @KBK_DEF INT
	SET @KBK_DEF = (Select top 1 link_kbk from dbo.KU_EmplStafKBK(default) where link_empl = @LINK_EMPL)

	---
	DECLARE @TABLE2 TABLE (Y INT, M INT, LINK_KBK INT, SUMMA_ZP NUMERIC(18,2), SUMMA_PR NUMERIC(18,2), SUMMA_MAT NUMERIC(18,2), DAYS INT, HOURS NUMERIC(18,2), DAYS_NORM INT, HOURS_NORM NUMERIC(18,2), KDAYS INT, KDAYS_N INT)
	INSERT INTO @TABLE2
	SELECT  
		T.Y,
		T.M,
		COALESCE(B.LINK_KBK,@KBK_DEF),
		SUMMA_ZP = SUM( CASE WHEN coalesce(PAYMENT,0) not in (7,12) THEN coalesce(SUMMA,0) ELSE 0 END),
		SUMMA_PR = SUM( CASE WHEN coalesce(PAYMENT,0) = 7 THEN coalesce(SUMMA,0) ELSE 0 END),
		SUMMA_MAT = SUM( CASE WHEN coalesce(PAYMENT,0) = 12 THEN coalesce(SUMMA,0) ELSE 0 END),
		COALESCE(DAYS,0),COALESCE(HOURS,0),COALESCE(DAYS_NORM,0),COALESCE(HOURS_NORM,0), COALESCE(KDAYS,0), COALESCE(KDAYS_N,0)
	FROM 
		@WTIME T LEFT JOIN 
		(
		Select PERIOD = DATEADD(MONTH,0,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,0,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,0,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA1,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA1,0) <> 0
	UNION ALL 
		Select PERIOD = DATEADD(MONTH,1,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,1,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,1,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA2,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA2,0) <> 0
	UNION ALL 
		Select PERIOD = DATEADD(MONTH,2,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,2,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,2,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA3,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA3,0) <> 0
	UNION ALL 
		Select PERIOD = DATEADD(MONTH,3,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,3,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,3,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA4,0)  
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA4,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,4,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,4,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,4,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA5,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA5,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,5,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,5,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,5,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA6,0)  
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA6,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,6,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,6,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,6,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA7,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA7,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,7,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,7,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,7,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA8,0) 
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA8,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,8,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,8,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,8,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA9,0)  
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA9,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,9,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,9,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,9,@DATE_BEGIN_RP)),	

			SUMMA = COALESCE(T3.KSUMMA10,0) 
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA10,0) <> 0 
	UNION ALL
		Select PERIOD = DATEADD(MONTH,10,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,10,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,10,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA11,0)  
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA11,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,11,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,11,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,11,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA12,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3 WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA12,0) <> 0
	) AS B ON T.Y = YEAR(B.PERIOD) AND T.M = MONTH(B.PERIOD)
	GROUP BY
		T.Y, T.M, B.LINK_KBK, DAYS,HOURS, DAYS_NORM, HOURS_NORM, KDAYS, KDAYS_N	

	-----
	DELETE FROM dbo.SDOC_AVAC_TABLE2  WHERE LINK_UP = @LINK_DOC

	INSERT INTO dbo.SDOC_AVAC_TABLE2 (LINK_UP, ORDERS, PERIOD, LINK_KBK, SUMMA, PREM, DAYS, HOURS, DAYS_N, HOURS_N, KDAYS, KDAYS_N, MATER)
	SELECT  @LINK_DOC, 0, dbo.ConvertDMY2Date(1, M, Y), 
	LINK_KBK, SUMMA_ZP, SUMMA_PR, DAYS,HOURS,DAYS_NORM,HOURS_NORM, KDAYS, KDAYS_N, SUMMA_MAT
	FROM @TABLE2
	ORDER BY Y, M, LINK_KBK

	SET @I = 0
	UPDATE dbo.SDOC_AVAC_TABLE2  
	SET @I = @I+1, ORDERS = @I
	WHERE LINK_UP = @LINK_DOC

END	--IF @RECALC < = 1

IF @RECALC < = 2 --- Расчет периодов больничного и определение средних сум
BEGIN		

	---Периоды отпуска
	DECLARE @PERIODY TABLE (DATE_BEGIN DATETIME, DATE_END DATETIME, INDEX_VAL NUMERIC(18,10), DH_NORM NUMERIC(18,2))
	DECLARE @PERIODY_DOP TABLE (NUM INT IDENTITY(1,1), DATE_BEGIN DATETIME, DATE_END DATETIME, T TINYINT)

		--- 1. Разбивка на периоды по месяцам
	if @DATE_BREAK IS NULL
		INSERT INTO @PERIODY_DOP (DATE_BEGIN, DATE_END, T)
		SELECT 
			DATE_BEGIN = (CASE WHEN @DATE_BEGIN > DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END), 
			DATE_END = (CASE WHEN @DATE_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
			1 --Первый тип периодов
		from dbo.months_ex(@DATE_BEGIN, @DATE_END)
	ELSE
	BEGIN
		SET @DATE_BREAK = @DATE_BREAK -1
		
		INSERT INTO @PERIODY_DOP (DATE_BEGIN, DATE_END, T)
		select 
			DATE_BEGIN = (CASE WHEN @DATE_BEGIN > DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END), 
			DATE_END = (CASE WHEN  @DATE_BREAK < dbo.DateEndOfMonth(DATE_BEGIN) THEN  @DATE_BREAK ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
			1 --Первый тип периодов
		from dbo.months_ex(@DATE_BEGIN, @DATE_BREAK)
		UNION ALL
		select 
			DATE_BEGIN = (CASE WHEN @DATE_BREAK_NEW_BEGIN > DATE_BEGIN THEN @DATE_BREAK_NEW_BEGIN ELSE DATE_BEGIN END), 
			DATE_END = (CASE WHEN @DATE_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
			1 --Первый тип периодов			
		from dbo.months_ex(@DATE_BREAK_NEW_BEGIN, @DATE_END)

	END

	--Второй тип периодов
	INSERT INTO @PERIODY_DOP (DATE_BEGIN, DATE_END, T)
	SELECT DATE_BEGIN = [DATE], DATE_END = [DATE2], 2 FROM @INDEX	

	DECLARE @A TABLE (NUM INT, [DATE] DATETIME, T INT)
	DECLARE @MIN_D DATETIME, @MAX_D DATETIME
	SELECT @MIN_D = MIN(DATE_BEGIN), @MAX_D = MAX(DATE_END) FROM @PERIODY_DOP

	INSERT INTO @A (NUM, [DATE], T)
	SELECT P.NUM, [DATE], T 
	FROM
		@PERIODY_DOP P
		INNER JOIN dbo.days_ex(@MIN_D, @MAX_D) D ON D.[DATE] BETWEEN P.DATE_BEGIN AND P.DATE_END
	ORDER BY P.NUM		

	DECLARE @T1 TABLE (NUM1 INT, [DATE] DATETIME, NUM2 INT)

	INSERT INTO @T1 (NUM1, [DATE], NUM2)
	SELECT A1.NUM, A1.[DATE], A2.NUM
	FROM @A A1 INNER JOIN @A A2 ON A1.[DATE] = A2.[DATE]
	WHERE A1.T = 1  AND A2.T = 2
	UNION
	SELECT A2.NUM, A2.[DATE], A1.NUM
	FROM @A A1 INNER JOIN @A A2 ON A1.[DATE] = A2.[DATE]
	WHERE A1.T = 1 AND A2.T = 2

	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, INDEX_VAL)
	SELECT 
		DATE_BEGIN, DATE_END,
		INDEX_VAL = ISNULL((SELECT INDEX_VAL FROM @INDEX I WHERE T.[DATE_BEGIN] BETWEEN I.DATE AND I.DATE2 AND T.[DATE_END] BETWEEN I.DATE AND I.DATE2),1)
	FROM (
		SELECT DISTINCT DATE_BEGIN = MIN([DATE]), DATE_END = MAX([DATE]) FROM @T1 GROUP BY NUM1, NUM2	
		) T	

	----
	UPDATE @PERIODY
	SET DH_NORM = 
			  CASE WHEN @VID_DAYS = 1 
				THEN ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAY_DH(@LINK_EMPL,DATE_BEGIN,DATE_END)),0) + (CASE WHEN DATE_BEGIN = (SELECT MAX(DATE_BEGIN) FROM @PERIODY) THEN @PDAY ELSE 0 END)
			  ELSE	
				DATEDIFF(DAY,DATE_BEGIN, DATE_END)+1 - (CASE WHEN @HOLIDAY = 1 THEN dbo.SA_HOLIDAY_COUNT_FN(DATE_BEGIN,DATE_END) ELSE 0 END) + (CASE WHEN DATE_BEGIN = (SELECT MAX(DATE_BEGIN) FROM @PERIODY) THEN @PDAY ELSE 0 END)
			  END
	---
	DECLARE @REP_SUMMA_PR NUMERIC(18,2), @SUMMA_ZP NUMERIC(18,2), @SUMMA_PR NUMERIC(18,2), @PNORM NUMERIC(18,2), @PWORK NUMERIC(18,2), 
		@SR_ZP NUMERIC(18,2), @AvgDays NUMERIC(18,2), @DAYS_SZ NUMERIC(18,2)
	SET @AvgDays = COALESCE(dbo.sa_get_option_by_code('FURLOUGH_OPT4'),29.3)
	
	--IF @DATE_BEGIN <= '20140401'
	--	SET @AvgDays = 29.4
/*
	Согласно статье 139 Трудового кодекса РФ (в редакции Федерального закона от 2 апреля 2014 г. N 55-ФЗ) 
	средний дневной заработок для оплаты отпусков и выплаты компенсации за неиспользованные отпуска 
	исчисляется за последние 12 календарных месяцев путем деления суммы начисленной заработной платы 
	на 12 и на 29,3 (среднемесячное число календарных дней)
	Решением Верховного Суда РФ от 22 августа 2012 г. N АКПИ12-942 абзац второй пункта 10 настоящего Положения 
	признан не противоречащим действующему законодательству		
*/	
	
	--- Время за расчетный период
	SELECT  [PERIOD],
		[DAYS_N] = MAX(DAYS_N),
		[HOURS_N] = MAX(HOURS_N),
		[DAYS] = MAX(DAYS),
		[HOURS] = MAX(HOURS),
		[KDAYS] = MAX(KDAYS),
		[KDAYS_N] = MAX(ISNULL(CONVERT(NUMERIC(4,0),DAY(dbo.DateEndOfMonth(PERIOD))),0))
	INTO #TMP
	FROM dbo.SDOC_AVAC_TABLE2 WHERE LINK_UP = @LINK_DOC
	GROUP BY [PERIOD]

	SELECT  
		@PNORM = SUM(CASE WHEN @SystPay = 1 THEN DAYS_N ELSE  HOURS_N END),
		@PWORK = SUM(CASE WHEN @SystPay = 1 THEN DAYS ELSE HOURS END),
		@DAYS_SZ = SUM(
			CASE WHEN @VID_DAYS = 1 THEN--В рабочих днях 
				CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
					CASE WHEN COALESCE(DAYS,0.00) >= COALESCE(DAYS_N,0.00) THEN COALESCE(DAYS_N,0.00) else COALESCE(DAYS,0.00) * 1.2 END
				ELSE DAYS --Рассчитываются не отпускные, а прочие начисления по среднему
				END
			ELSE --В календарных днях
				CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
					CASE WHEN COALESCE(KDAYS,0.00) <> 0 AND COALESCE(KDAYS,0.00) >= COALESCE(KDAYS_N,0.00) THEN @AvgDays else CONVERT(NUMERIC(18,2),@AvgDays * (CASE WHEN COALESCE(KDAYS_N,0.00) <> 0.00 THEN COALESCE(KDAYS,0.00) / COALESCE(KDAYS_N,0.00) else 0.00 END)) END
				ELSE KDAYS --Рассчитываются не отпускные, а прочие начисления по среднему
				END				
			END)
	FROM #TMP

	---	
	SELECT 
		@SUMMA_ZP = SUM(SUMMA) + SUM(MATER), 
		@SUMMA_PR = CASE WHEN SUM(@PNORM) > 0 THEN SUM(PREM) / SUM(@PNORM) * SUM(@PWORK) ELSE 0 END,
		@REP_SUMMA_PR = CASE WHEN SUM(@PNORM) > 0 THEN SUM(PREM) / SUM(@PNORM) * SUM(@PWORK) ELSE 0 END
	FROM dbo.SDOC_AVAC_TABLE2 WHERE LINK_UP = @LINK_DOC

	---	
	SET @SR_ZP = CASE WHEN @DAYS_SZ <> 0 THEN (@SUMMA_ZP + @SUMMA_PR) / @DAYS_SZ ELSE 0 END
		
	DECLARE @KBK_KOEF TABLE (LINK_KBK INT, KOEF NUMERIC(18,4))
	DECLARE @S NUMERIC(18,2)
	SET @S = COALESCE((SELECT SUM(SUMMA) + (CASE WHEN SUM(@PNORM) > 0 THEN SUM(PREM) / SUM(@PNORM) * SUM(@PWORK) ELSE 0 END) FROM dbo.SDOC_AVAC_TABLE2 WHERE LINK_UP = @LINK_DOC),0)

	INSERT INTO @KBK_KOEF (LINK_KBK, KOEF) 
	SELECT LINK_KBK, CASE WHEN @S <> 0 THEN (SUM(SUMMA) + (CASE WHEN SUM(@PNORM) > 0 THEN SUM(PREM) / SUM(@PNORM) * SUM(@PWORK) ELSE 0 END)) / @S ELSE 0 END
	FROM dbo.SDOC_AVAC_TABLE2  WHERE LINK_UP = @LINK_DOC 
	GROUP BY LINK_KBK
	
	---
	DELETE FROM dbo.SDOC_AVAC_TABLE1  WHERE LINK_UP = @LINK_DOC

	INSERT INTO dbo.SDOC_AVAC_TABLE1 (LINK_UP, ORDERS, DATE1, DATE2, DAYS, HOURS, SR_ZP, SUMMA, LINK_KBK, KOEF_KBK, KOEF_IDX)
	SELECT @LINK_DOC, 0, DATE_BEGIN, DATE_END, 
		DH_NORM,
		ISNULL(CONVERT(NUMERIC(10,2),dbo.NORM_HOUR_DH(@LINK_EMPL,DATE_BEGIN,DATE_END)),0),
		SR_ZP = @SR_ZP,
		0,
		K.LINK_KBK,	
		K.KOEF,
		ISNULL(P.INDEX_VAL,1)
	FROM @PERIODY P INNER JOIN @KBK_KOEF K ON 1=1
	ORDER BY DATE_BEGIN

	UPDATE sdoc_avac WITH (ROWLOCK) 
	SET 	LINK_EMPL = @LINK_EMPL, LINK_PAY=@LINK_PAYS, DATE_BEGIN=@DATE_BEGIN_RP, SUMMA_TOTAL = @SUMMA_ZP, SR_PREM=@SUMMA_PR, 
			TYP_PERIOD=@TYP_PERIOD, SUMMA_BASE = @SR_ZP, 
			PAYMENT=@VID_DAYS, REF_DOC = @LINK_VAC, DATE1 = @DATE_BEGIN, DATE2 = @DATE_END, TYPE = @SR_VID
	WHERE LINK_UP = @LINK_DOC

	--Дневное пособие не может быть менее дневного пособия, рассчитанного исходя из МРОТ
	IF dbo.sa_get_option_by_code('FURLOUGH_OPT6') = 1 AND (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1)
	BEGIN
		IF @VID_DAYS = 1 --Если расчет в рабочих днях
			UPDATE dbo.SDOC_AVAC_TABLE1
			SET SR_ZP = (case when 
		 			(CASE WHEN @SystPay = 1 
		 				THEN ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(@LINK_EMPL, MONTH(DATE1), YEAR(DATE1) )),0) 
		 				ELSE ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_HOURS(@LINK_EMPL, MONTH(DATE1), YEAR(DATE1) )),0) 	
		 			END)  > 0
		 
		 		then 
						case when SR_ZP < CONVERT(NUMERIC(18,2), dbo.minrot2(DATE1) / 
												(CASE WHEN @SystPay = 1 
													THEN ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(@LINK_EMPL, MONTH(DATE1), YEAR(DATE1) )),0) 
													ELSE ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_HOURS(@LINK_EMPL, MONTH(DATE1), YEAR(DATE1) )),0) 	
												END) )
							then	
								CONVERT(NUMERIC(18,2), dbo.minrot2(DATE1) / 
									(CASE WHEN @SystPay = 1 
										THEN ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(@LINK_EMPL, MONTH(DATE1), YEAR(DATE1) )),0) 
										ELSE ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_HOURS(@LINK_EMPL, MONTH(DATE1), YEAR(DATE1) )),0) 	
									END) )
							else SR_ZP end
		 		else SR_ZP end)
			WHERE LINK_UP = @LINK_DOC
		ELSE	--Если расчет в календарных днях
			IF dbo.sa_get_option_by_code('FURLOUGH_OPT6') = 1 AND (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1)
			UPDATE dbo.SDOC_AVAC_TABLE1
			SET SR_ZP = case when SR_ZP < dbo.minrot2(DATE1) / (datediff(day,dbo.DateBeginOfMonth(DATE1),dbo.DateEndOfMonth(DATE1)) + 1) 
				then	
					dbo.minrot2(DATE1) / (datediff(day,dbo.DateBeginOfMonth(DATE1),dbo.DateEndOfMonth(DATE1)) + 1)
				else	
					SR_ZP 
				end
			WHERE LINK_UP = @LINK_DOC	
	END
END --@RECALC <= 2 


Select CJ.DATE_BEGIN, CJ.DATE_END, CJ.LINK_VKR, DAYS = SUM(CJ.DAYS) , HOURS = SUM(CJ.HOURS), SUMMA = SUM(SUMMA)
INTO #SUM_OLD
from 
	dbo.SDOC_AVAC SA inner join dbo.CALCULATE_JURNAL CJ on CJ.LINK_DOC = SA.LINK_UP
	inner join dbo.sdoc d on CJ.LINK_DOC = d.link 
where
	COALESCE(@LINK_VAC,0) > 0
	AND
	SA.REF_DOC = @LINK_VAC
	and
	d.object = (Select top 1 link from s_objects where code = @OBJ_CODE)
GROUP BY
	CJ.DATE_BEGIN, CJ.DATE_END, CJ.LINK_VKR

---- сопоставить старые
UPDATE dbo.SDOC_AVAC_TABLE1
SET 
	SUMMA_NEW = CONVERT(NUMERIC(18,2), T.SR_ZP * T.DAYS * KOEF_KBK 
					* --индексация суммы во время отпуска
						(CASE WHEN KOEF_IDX >= 1 THEN KOEF_IDX ELSE 1 END)
						), 
	SUMMA_OLD = COALESCE(SO.SUMMA,0),
	DAYS = COALESCE(T.DAYS,0) - COALESCE(SO.DAYS,0), 
	HOURS = COALESCE(T.HOURS,0) - COALESCE(SO.HOURS,0)
FROM dbo.sdoc_avac A INNER JOIN dbo.SDOC_AVAC_TABLE1 T ON A.LINK_UP = T.LINK_UP
	LEFT JOIN #SUM_OLD SO ON T.DATE1 = SO.DATE_BEGIN AND T.DATE2 = SO.DATE_END AND T.LINK_KBK = SO.LINK_VKR
WHERE T.LINK_UP = @LINK_DOC AND KOEF_KBK IS NOT NULL AND SR_ZP IS NOT NULL

-- добавить старые, которых теперь нет
insert into dbo.SDOC_AVAC_TABLE1 (link_up, ORDERS, DATE1, DATE2, DAYS, HOURS, SUMMA, LINK_KBK, SR_ZP, KOEF_KBK, SUMMA_OLD, SUMMA_NEW)
Select @LINK_DOC, 0, DATE_BEGIN, DATE_END, -DAYS, -HOURS, 0, LINK_VKR, 0, 1, SO.SUMMA, 0
from #SUM_OLD SO
where 
	NOT EXISTS (Select * from dbo.SDOC_AVAC_TABLE1 T where T.LINK_UP = @LINK_DOC and T.DATE1 = SO.DATE_BEGIN AND T.DATE2 = SO.DATE_END AND T.LINK_KBK = SO.LINK_VKR)

---- сравнить
UPDATE dbo.SDOC_AVAC_TABLE1
SET SUMMA = COALESCE(SUMMA_NEW,0) - COALESCE(SUMMA_OLD,0)
WHERE LINK_UP = @LINK_DOC

---
SET @I = 0
UPDATE dbo.SDOC_AVAC_TABLE1  
SET @I = @I+1, ORDERS = @I
WHERE LINK_UP = @LINK_DOC

---
DECLARE @SUMMA NUMERIC(18,2)
SELECT @SUMMA = COALESCE((SELECT SUM(SUMMA) FROM dbo.SDOC_AVAC_TABLE1 WHERE LINK_UP = @LINK_DOC),0), @SUMMA_ZP = COALESCE(@SUMMA_ZP,0), @SUMMA_PR = COALESCE(@SUMMA_PR,0)

---
SELECT @NUMBER = NUMBER,  @DATE_DOC = [DATE] from dbo.SDOC WHERE LINK = @LINK_DOC
--- Сохрание расчета
SELECT @varKSsoLink = LINK FROM s_objects  WHERE CODE = @OBJ_CODE
EXECUTE dbo.SALARY_UPD_SDOC @LINK_DOC OUTPUT, @varKSsoLink, @NUMBER,@DATE_DOC,@comment,0,null,@SUMMA, @LINK_DEP

IF @OPER = 1 
	exec dbo.SD_N_VACATION_PROV @LINK_DOC, @OBJ_CODE
	
SET NOCOUNT OFF



GO


GRANT EXECUTE ON dbo.[SA_N_VAC_FILL1] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_U_VEDOM_DGH_INCOM_VKR]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_U_VEDOM_DGH_INCOM_VKR]

GO
/*
© Кейсистемс (Keysystems), 2005
*/

CREATE  PROCEDURE [dbo].SD_U_VEDOM_DGH_INCOM_VKR
	@varKSnMonth int,
	@varKSnYear int,
	@varKSLinkVKR int,
	@varKSLinkEKR INT = 0,
	@DEP_LINK INT = NULL
AS 

IF @DEP_LINK IS NULL
	exec dbo.xd_whats_zb @DEP_LINK output

	set @varKSLinkEKR = isnull(@varKSLinkEKR,0)

	SELECT DISTINCT SJC.PERS_LINK AS PERS_LINK,'' AS TAB_NUMER,dbo.ku_GetPersFio(SJC.PERS_LINK) AS FIO ,SJC.LINK_EKR AS LINK_EKR, k.CODE AS CODE_EKR  
	FROM S_J_C_Short SJC 
	LEFT JOIN dbo.KOSGU k ON k.LINK = SJC.LINK_EKR
	WHERE SJC.LINK_EMPL IS NULL AND SJC.PERS_LINK IS NOT NULL 
	AND SJC.MONTH_BEGIN = @varKSnMonth AND SJC.YEAR_BEGIN = @varKSnYear AND SJC.LINK_VKR = @varKSLinkVKR AND (@varKSLinkEKR = 0 or SJC.LINK_EKR = @varKSLinkEKR)
	AND SJC.TYP_OPER = 1 AND SJC.SUMMA > 0
	AND SJC.LINK_DEP = @DEP_LINK





GO


GRANT EXECUTE ON dbo.[SD_U_VEDOM_DGH_INCOM_VKR] TO PUBLIC

GO


--Расширенные свойства--


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_PKG_POST_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_PKG_POST_SAVE]

GO
CREATE PROCEDURE dbo.[SA_PKG_POST_SAVE]
	@LINK int OUTPUT,
	@CODE varchar(6),
	@NAME varchar(254)
AS

DECLARE @varKSERROR	tinyint, @varKSstrVALUE	varchar(7000), @varKStrancount	int, 	@varKSsoLink int, @varKSRowCount int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

SET @CODE = RTRIM(LTRIM(COALESCE(@CODE,'')))
SET @NAME = RTRIM(LTRIM(COALESCE(@NAME,'')))
IF @Code = '' OR @NAME = '' 
BEGIN
	ROLLBACK
	RETURN 5
END

IF @LINK is null OR @LINK = 0
BEGIN

	IF EXISTS (Select * from dbo.PKG_POST where rtrim(ltrim(code)) = @NAME or rtrim(ltrim([name])) =@NAME)
	BEGIN
		ROLLBACK
		RETURN 8	
	END

	INSERT INTO dbo.PKG_POST WITH (ROWLOCK) (code, [name])
		VALUES (@code, @Name)

	SELECT @varKSERROR = @@ERROR, @LINK = @@IDENTITY
	IF @varKSERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
END

ELSE
BEGIN
	UPDATE dbo.PKG_POST SET [name] = @Name, code = @Code
	WHERE link=@LINK
	SELECT @varKSERROR = @@ERROR 
	IF @varKSERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
END

declare @ObjectLink int, @EventText varchar(254)
SELECT @ObjectLink = link FROM s_objects WHERE code='SA_PKG_POST'
SET @EventText = 'ПКГ должностей ' +  RTRIM(@Name)
EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника', @EventText, @ObjectLink, 'SA_PKG_POST', @LINK


WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0





GO


GRANT EXECUTE ON dbo.[SA_PKG_POST_SAVE] TO PUBLIC

GO




GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_PKG_LIST_POST_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_PKG_LIST_POST_SAVE]

GO
CREATE PROCEDURE dbo.[SA_PKG_LIST_POST_SAVE]
	@LINK_POST int,
	@LINK_PKG INT,
	@PERIOD_BEGIN DATETIME = null 
AS
-- exec SA_PKG_LIST_POST_SAVE 76772,1,'2014-01-01 00:00:00','2014-01-02 00:00:00'
DECLARE @varKSERROR	tinyint, @varKSstrVALUE	varchar(7000), @varKStrancount	int, 	@varKSsoLink int, @varKSRowCount int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

IF @LINK_PKG is null or @LINK_POST is NULL OR @PERIOD_BEGIN IS NULL --OR @PERIOD_END IS NULL
BEGIN
	ROLLBACK
	RETURN 5
END

DECLARE @err VARCHAR(254), @CODE VARCHAR(10), @NAME VARCHAR(254)  
SET @err = ''

declare @LINK int 

select @link = link from dbo.pkg_post_date where link_pkg = @link_pkg and link_post = @LINK_POST


IF @LINK is null OR @LINK = 0
BEGIN

	IF EXISTS (Select * from dbo.pkg_post_date where link_pkg = @link_pkg and link_post = @LINK_POST)
		
	BEGIN
		ROLLBACK
		RETURN 8	
	END

	INSERT INTO  dbo.pkg_post_date WITH (ROWLOCK) (link_pkg,link_post,date_begin)
		VALUES (@link_pkg,@link_post,@period_begin)

	SELECT @varKSERROR = @@ERROR, @LINK = @@IDENTITY
	IF @varKSERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
END

ELSE
BEGIN

	UPDATE dbo.pkg_post_date 
	SET LINK_PKG = @LINK_PKG, link_Post = @LINK_POST, DATE_BEGIN = @PERIOD_BEGIN
	WHERE link = @LINK

	SELECT @varKSERROR = @@ERROR
	IF @varKSERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END

END

SET @NAME = (SELECT NAME FROM dbo.POST WHERE link = @LINK_POST)

declare @ObjectLink int, @EventText varchar(254)
SELECT @ObjectLink = link FROM s_objects WHERE code='DICTIONARY_POST'
SET @EventText = 'Должность ' +  RTRIM(@Name)
EXECUTE WF_GENERATEEVENT 'Отнесение к группе', @EventText, @ObjectLink, 'DICTIONARY_POST', @LINK_POST


WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0


GO


GRANT EXECUTE ON dbo.[SA_PKG_LIST_POST_SAVE] TO PUBLIC

GO


GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SD_N_VACATION_TABLE4_SAVE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SD_N_VACATION_TABLE4_SAVE]
GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE SD_N_VACATION_TABLE4_SAVE
	@varKSparLINK			int,
	@varKSparREF_PAY		int,
	@varKSparKOEF1			numeric(15,4),
	@varKSparKOEF2			numeric(15,4),
	@varKSparKOEF3			numeric(15,4),
	@varKSparKOEF4			numeric(15,4),
	@varKSparKOEF5			numeric(15,4),
	@varKSparKOEF6			numeric(15,4),
	@varKSparKOEF7			numeric(15,4),
	@varKSparKOEF8			numeric(15,4),
	@varKSparKOEF9			numeric(15,4),
	@varKSparKOEF10			numeric(15,4),
	@varKSparKOEF11			numeric(15,4),
	@varKSparKOEF12			numeric(15,4),
	@LINK_KBK			INT
AS
DECLARE @varKSERROR	tinyint, @varKStrancount	int,  @varKSSQLError int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

IF @varKSparREF_PAY IS NULL
BEGIN
	ROLLBACK
	RETURN 5
END

UPDATE SDOC_AVAC_TABLE3 WITH (ROWLOCK) 
Set 	KOEF1 = @varKSparKOEF1,
	KOEF2 = @varKSparKOEF2,
	KOEF3 = @varKSparKOEF3,
	KOEF4 = @varKSparKOEF4,
	KOEF5 = @varKSparKOEF5,
	KOEF6 = @varKSparKOEF6,
	KOEF7 = @varKSparKOEF7,
	KOEF8 = @varKSparKOEF8,
	KOEF9 = @varKSparKOEF9,
	KOEF10 = @varKSparKOEF10,
	KOEF11 = @varKSparKOEF11,
	KOEF12 = @varKSparKOEF12
WHERE
	LINK_UP = @varKSparLINK and LINK_PAY = @varKSparREF_PAY AND LINK_KBK = @LINK_KBK

SELECT @varKSSQLError = @@ERROR
IF @varKSSQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END

WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0



GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_PKG_POST_DELETE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_PKG_POST_DELETE]

GO

CREATE     PROCEDURE dbo.SA_PKG_POST_DELETE
	@varKSintLINK	int
AS
DECLARE @varKStrancount	int,
	@varKSObjectLink	int,
	@varKSEventText	varchar(254)

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

	SELECT @varKSEventText = 'Справочник "ПКГ должностей"' + ' ' + [name] FROM dbo.PKG_POST WITH (UPDLOCK) WHERE LINK = @varKSintLINK
	IF @@RowCount = 0 OR @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 2
	END


	DELETE FROM dbo.PKG_OKLAD WHERE LINK_UP = @varKSintLINK
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END

	DELETE FROM dbo.PKG_POST WHERE LINK = @varKSintLINK
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
	

IF @@TRANCOUNT > @varKStrancount
	BEGIN
		SELECT @varKSObjectLink = LINK FROM S_OBJECTS WHERE CODE = 'SA_PKG_POST'
		EXECUTE WF_GENERATEEVENT 'Удаление из справочника', @varKSEventText, @varKSObjectLink, 'SA_PKG_POST', @varKSintLINK
		COMMIT TRAN
	END
RETURN 0

GO


GRANT EXECUTE ON dbo.[SA_PKG_POST_DELETE] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RSA_RSV_1_14_PFR_INV]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RSA_RSV_1_14_PFR_INV]

GO
--- EXEC RSA_RSV_1_14_PFR_INV  '2014' , 1 , 7 , 1 
CREATE PROCEDURE dbo.RSA_RSV_1_14_PFR_INV
	@cYEAR  VARCHAR(4),
	@nQuart int,
	@WAY_CALC TINYINT = 7,
	@REP TINYINT = 0
	
	/*@dDate1 DATETIME,
	@dDate2 DATETIME,
	@LINK_DEP int = NULL,
	@WAY_CALC TINYINT = 7,
	@REP TINYINT = 0*/
AS BEGIN




	DECLARE @MONTH1 INT , @MONTH2 INT , @MONTH3 INT
	
	IF @nQuart = 1
	SELECT @MONTH1 = 1 , @MONTH2 = 2, @MONTH3 = 3
	IF @nQuart = 2
	SELECT @MONTH1 = 4 , @MONTH2 = 5, @MONTH3 = 6	
	IF @nQuart = 3
	SELECT @MONTH1 = 7 , @MONTH2 = 8, @MONTH3 = 9	
	IF @nQuart = 4
	SELECT @MONTH1 = 10 , @MONTH2 = 11,  @MONTH3 = 12		
	

	DECLARE @START_YEAR DATETIME , @dDate1 DATETIME , @dDate2 DATETIME
	SET @START_YEAR  = dbo.DateBeginOfYear(dbo.ConvertDMY2Date(1,@MONTH1,@cYEAR))

	SET @dDate1 = dbo.ConvertDMY2Date(1,@MONTH1,@cYEAR)
	SET @dDate2 = dbo.DateEndOfMonth(dbo.DateBeginOfYear(dbo.ConvertDMY2Date(1,@MONTH3,@cYEAR)))



	DECLARE @DEFAULTDK AS DATETIME
	
	SET	@DEFAULTDK = CONVERT( VARCHAR(8), ( YEAR( GETDATE() ) * 100 + 12 ) * 100 + 31 )

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output


	CREATE TABLE #TMP (
		LINK INT, 
		FIO VARCHAR(254),
		FIO2 VARCHAR(254),
		NUM_SPR VARCHAR(30), 
		DATE_SPR VARCHAR(10), 
		GRP VARCHAR(25), 
		GRP2 VARCHAR(25), 
		PER_BEG VARCHAR(10), 
		PER_END VARCHAR(10), 
		SM_ALL 	NUMERIC(18,2), SM_QWART NUMERIC(18,2), SM1 NUMERIC(18,2), SM2 NUMERIC(18,2), SM3 NUMERIC(18,2) )

	CREATE TABLE #TMP0 (
		[PERS_LINK] int,
		[FIO] varchar(254),
		[FIO2] varchar(254),
		[DOC_NUM] varchar(30),
		[DOC_DATE] varchar(10),
		[GROUP_NAME] varchar(254),
		[GRP2] varchar(3),
		[PER_BEG] varchar(10),
		[PER_END] varchar(10))	

	INSERT INTO #TMP0(PERS_LINK,FIO,FIO2,DOC_NUM,DOC_DATE,GROUP_NAME,GRP2,PER_BEG,PER_END)
	SELECT
		DIF.PERS_LINK, 
		LEFT((SELECT 
			TOP 1 LTRIM(RTRIM(DF.FM)) + ' ' + LTRIM(RTRIM(DF.IM)) + ' ' + LTRIM(RTRIM(DF.OT)) 

				FROM person DF
				WHERE DF.LINK = DIF.PERS_LINK),254) AS FIO,
		LEFT((SELECT 
			TOP 1 UPPER(LTRIM(RTRIM(DF.FM)) + ',' + LTRIM(RTRIM(DF.IM)) + ',' + LTRIM(RTRIM(DF.OT)) )

				FROM person DF
				WHERE DF.LINK = DIF.PERS_LINK),254) AS FIO2,
		DOC_NUM = LEFT(MAX(DIF.DOC_NUM),30),
		DOC_DATE = LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),MAX(DIF.DOC_DATE),104),''))), 
		GROUP_NAME = LEFT(MAX(DIF.GROUP_NAME),254),
		CASE 
			WHEN MAX(DIF.GROUP_NAME) = 'I ГРУППА' THEN 'I'
			WHEN MAX(DIF.GROUP_NAME) = 'II ГРУППА' THEN 'II'
			WHEN MAX(DIF.GROUP_NAME) = 'III ГРУППА' THEN 'III'
			ELSE ''
		END AS GRP2, 
		LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),MAX(DIF.DATE_BEGIN),104),''))) AS PER_BEG,
		LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),ISNULL(MAX(DIF.DATE_END),dbo.DateEndOfYear(@dDate1)),104),''))) AS PER_END
	FROM dbo.KU_PERS_INVALID  DIF INNER JOIN dbo.EMPL E ON DIF.PERS_LINK = E.PERS_LINK
	WHERE COALESCE(DIF.DATE_BEGIN,@dDate2) <= @dDate2 AND COALESCE(DIF.DATE_END,@START_YEAR) >= @START_YEAR
		and E.DEP_LINK = @DEP_LINK
	GROUP BY 
		DIF.PERS_LINK

	INSERT INTO #TMP0(PERS_LINK,FIO,FIO2,DOC_NUM,DOC_DATE,GROUP_NAME,GRP2,PER_BEG,PER_END)
	SELECT
		DIF.PERS_LINK, 
		LEFT((SELECT 
			TOP 1 LTRIM(RTRIM(DF.FM)) + ' ' + LTRIM(RTRIM(DF.IM)) + ' ' + LTRIM(RTRIM(DF.OT)) 

				FROM person DF
				WHERE DF.LINK = DIF.PERS_LINK),254) AS FIO,
		LEFT((SELECT 
			TOP 1 UPPER(LTRIM(RTRIM(DF.FM)) + ',' + LTRIM(RTRIM(DF.IM)) + ',' + LTRIM(RTRIM(DF.OT)) )

				FROM person DF
				WHERE DF.LINK = DIF.PERS_LINK),254) AS FIO2,
		DOC_NUM = LEFT(MAX(DIF.DOC_NUM),30),
		DOC_DATE = LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),MAX(DIF.DOC_DATE),104),''))), 
		GROUP_NAME = LEFT(MAX(DIF.GROUP_NAME),254),
		CASE 
			WHEN MAX(DIF.GROUP_NAME) = 'I ГРУППА' THEN 'I'
			WHEN MAX(DIF.GROUP_NAME) = 'II ГРУППА' THEN 'II'
			WHEN MAX(DIF.GROUP_NAME) = 'III ГРУППА' THEN 'III'
			ELSE ''
		END AS GRP2, 
		LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),MAX(DIF.DATE_BEGIN),104),''))) AS PER_BEG,
		LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),ISNULL(MAX(DIF.DATE_END),dbo.DateEndOfYear(@dDate1)),104),''))) AS PER_END
	FROM dbo.KU_PERS_INVALID  DIF
	WHERE 
		COALESCE(DIF.DATE_BEGIN,@dDate2) <= @dDate2 AND COALESCE(DIF.DATE_END,@START_YEAR) >= @START_YEAR
		and EXISTS (SELECT * FROM dbo.REESTR_DGH DGH 
						WHERE DGH.DEP_LINK = @DEP_LINK AND DGH.PERS_LINK = DIF.PERS_LINK 
								AND COALESCE(DGH.DATE1,@dDate2) <= @dDate2 AND COALESCE(DGH.DATE2,@START_YEAR) >= @START_YEAR)
		AND NOT EXISTS (SELECT * FROM #TMP0 TT WHERE TT.PERS_LINK = DIF.PERS_LINK)						
	GROUP BY 
		DIF.PERS_LINK			

	--
	if  OBJECT_ID('tempdb..#PERS_INV1') IS NOT NULL
		DROP TABLE #PERS_INV1

	--

	DECLARE @nYear INT, @nMonth1 INT, @nMONTH2 INT, @nMONTH3 INT
	SELECT 
		@nYear = YEAR(@dDate1),
		@nMonth1 = MONTH(@dDate2)-2,
		@nMONTH2 = MONTH(@dDate2)-1,
		@nMONTH3 = MONTH(@dDate2)

	Declare @StBase2 table (link int)
	Insert into @StBase2 (link)
	select distinct link_pays from tax_ref where link_tax = (select top 1 link from pays where object = 3 and way_calc = @WAY_CALC)

	---------
	CREATE TABLE #TSUM (PERS_LINK INT, MON TINYINT, FACE_GROUP TINYINT, SUMMA NUMERIC(18,2))

	INSERT INTO 
		#TSUM (PERS_LINK, MON, FACE_GROUP, SUMMA)
	select 
		E.PERS_LINK,
		MON = Month(CJ.PERIOD_BEGIN),
		( CASE WHEN YEAR(birthdate)<= 1966 THEN 1 ELSE 2 END ) AS FACE_GROUP,
		SUMMA = SUM(CASE WHEN I.LINK IS NOT NULL AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN COALESCE(I.DATE_BEGIN,CJ.PERIOD_BEGIN) AND  COALESCE(I.DATE_END,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) THEN SUMMA ELSE 0 END)
	from 
		dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
		INNER JOIN DBO.EMPL E ON E.LINK = CJ.LINK_EMPL
		INNER JOIN DBO.PERSON P1 ON P1.LINK = E.PERS_LINK
		LEFT JOIN @StBase2 B ON B.LINK = cj.LINK_PAYS
		LEFT JOIN DBO.KU_PERS_INVALID I ON I.PERS_LINK = E.PERS_LINK AND COALESCE(I.DATE_BEGIN,dbo.DateBeginOfYear(@dDate1)) <= dbo.DateEndOfYear(@dDate2) AND COALESCE(I.DATE_END,dbo.DateEndOfYear(@dDate2)) >= dbo.DateBeginOfYear(@dDate1)
	where 	
		Year(period_begin) = @nYear and Month(period_begin) <= @nMONTH3 
		and CJ.LINK_DEP = @DEP_LINK
		and P.[OBJECT] = 1
	GROUP BY
		E.PERS_LINK, Month(CJ.PERIOD_BEGIN),( CASE WHEN YEAR(birthdate)<= 1966 THEN 1 ELSE 2 END )
	UNION ALL	
	select
		CJ.PERS_LINK, 
		MON = Month(CJ.PERIOD_BEGIN),
		( CASE WHEN YEAR(birthdate)<= 1966 THEN 1 ELSE 2 END ) AS FACE_GROUP,
		SUMMA_ALL_I = SUM(CASE WHEN I.LINK IS NOT NULL AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN COALESCE(I.DATE_BEGIN,CJ.PERIOD_BEGIN) AND  COALESCE(I.DATE_END,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) THEN SUMMA ELSE 0 END)
	from 
		dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
		INNER JOIN DBO.PERSON P1 ON P1.LINK = CJ.PERS_LINK
		LEFT JOIN DBO.KU_PERS_INVALID I ON I.PERS_LINK = CJ.PERS_LINK AND COALESCE(I.DATE_BEGIN,dbo.DateBeginOfYear(@dDate1)) <= dbo.DateEndOfYear(@dDate2) AND COALESCE(I.DATE_END,dbo.DateEndOfYear(@dDate2)) >= dbo.DateBeginOfYear(@dDate1)
	where 	
		Year(period_begin) = @nYear and Month(period_begin) <= @nMONTH3 
		and CJ.LINK_DEP = @DEP_LINK
		and P.[OBJECT] = 1
	GROUP BY
		CJ.PERS_LINK, Month(CJ.PERIOD_BEGIN), ( CASE WHEN YEAR(birthdate)<= 1966 THEN 1 ELSE 2 END )		

	-------
	CREATE TABLE #TMP_00 (PERS_LINK INT, MON TINYINT, FACE_GROUP TINYINT, SUMMA NUMERIC(18,2))
	
	INSERT INTO #TMP_00 (PERS_LINK, MON, FACE_GROUP, SUMMA)
	SELECT 
		PERS_LINK, MON, FACE_GROUP, SUMMA = SUM(SUMMA)
	FROM 
		#TSUM
	GROUP BY 
		PERS_LINK, MON, FACE_GROUP

	--По людям округленные суммы
	SELECT PERS_LINK, 
		CASE @nMONTH3
			WHEN 3 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))
			WHEN 6 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END))	
			WHEN 9 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA ELSE 0 END))
			WHEN 12 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA ELSE 0 END))							
		END AS SM_ALL, 
		Convert(numeric(18,2),SUM(CASE WHEN MON = @nMonth1 THEN SUMMA ELSE 0 END)) AS SM1,
		Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA ELSE 0 END)) AS SM2,
		Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA ELSE 0 END)) AS SM3,

		S1 = Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END)),
		S2 = Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END)),
		S3 = Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END)),
		
		S4 = Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END)),
		S5 = Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END)),
		S6 = Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END)),
		
		S7 = Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA ELSE 0 END)),
		S8 = Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA ELSE 0 END)),
		S9 = Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA ELSE 0 END))
		
	INTO #TMP_000
	FROM #TMP_00
	GROUP BY PERS_LINK

	--Подгонка суммы (Из-за проблем округления)	
	DECLARE @NADO TABLE (SUM_Q numeric(18,2),SUM_M1 numeric(18,2),SUM_M2 numeric(18,2),SUM_M3 numeric(18,2), S1 numeric(18,2), S2 numeric(18,2), S3 numeric(18,2), S4 numeric(18,2), S5 numeric(18,2), S6 numeric(18,2), S7 numeric(18,2), S8 numeric(18,2), S9 numeric(18,2))
	--Итоговые округленные суммы неокругленных сумм по людам
	INSERT INTO @NADO (SUM_Q, SUM_M1, SUM_M2, SUM_M3, S1, S2, S3, S4, S5, S6, S7, S8, S9)
	SELECT 
		CASE @nMONTH3
			WHEN 3 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))
			WHEN 6 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END))	
			WHEN 9 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA ELSE 0 END))
			WHEN 12 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA ELSE 0 END))							
		END AS SM_ALL, 
			 
		 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMonth1 THEN SUMMA ELSE 0 END)),
		 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA ELSE 0 END)),
		 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA ELSE 0 END)),

		S1 = Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END)),
		S2 = Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END)),
		S3 = Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END)),
		
		S4 = Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END)),
		S5 = Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END)),
		S6 = Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END)),
		
		S7 = Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA ELSE 0 END)),
		S8 = Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA ELSE 0 END)),
		S9 = Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA ELSE 0 END))		  
		 
	FROM #TMP_00	
	WHERE FACE_GROUP = 1

	INSERT INTO @NADO (SUM_Q, SUM_M1, SUM_M2, SUM_M3, S1, S2, S3, S4, S5, S6, S7, S8, S9)
	SELECT 
		CASE @nMONTH3
			WHEN 3 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))
			WHEN 6 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END))	
			WHEN 9 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA ELSE 0 END))
			WHEN 12 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA ELSE 0 END))							
		END AS SM_ALL, 
			 
		 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMonth1 THEN SUMMA ELSE 0 END)),
		 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA ELSE 0 END)),
		 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA ELSE 0 END)),

		S1 = Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END)),
		S2 = Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END)),
		S3 = Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END)),
		
		S4 = Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END)),
		S5 = Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END)),
		S6 = Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END)),
		
		S7 = Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA ELSE 0 END)),
		S8 = Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA ELSE 0 END)),
		S9 = Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA ELSE 0 END))
		 
	FROM #TMP_00		 
	WHERE FACE_GROUP = 2
	------------------------------------------------
--Распределение разницы между итоговой округленной суммы неокругленных сумм по людам и суме округленных сум по людам
--Разница округлений исправляется на человеке с максимальным доходом в месяце, когда получилась разница	
--Корректировка сумм за предудущий 1 квартал
	IF @nMONTH3 > 3 AND ISNULL((SELECT SUM(S1) FROM #TMP_000),0) <> ISNULL((SELECT SUM(S1) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(S1) FROM @NADO),0) - ISNULL((SELECT SUM(S1) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY S1 DESC)
	END
	IF @nMONTH3 > 3 AND ISNULL((SELECT SUM(S2) FROM #TMP_000),0) <> ISNULL((SELECT SUM(S2) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(S2) FROM @NADO),0) - ISNULL((SELECT SUM(S2) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY S2 DESC)
	END	
	IF @nMONTH3 > 3 AND ISNULL((SELECT SUM(S3) FROM #TMP_000),0) <> ISNULL((SELECT SUM(S3) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(S3) FROM @NADO),0) - ISNULL((SELECT SUM(S3) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY S3 DESC)
	END
--Корректировка сумм за предудущий 2 квартал
	IF @nMONTH3 > 6 AND ISNULL((SELECT SUM(S4) FROM #TMP_000),0) <> ISNULL((SELECT SUM(S4) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(S4) FROM @NADO),0) - ISNULL((SELECT SUM(S4) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY S4 DESC)
	END
	IF @nMONTH3 > 6 AND ISNULL((SELECT SUM(S5) FROM #TMP_000),0) <> ISNULL((SELECT SUM(S5) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(S5) FROM @NADO),0) - ISNULL((SELECT SUM(S5) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY S5 DESC)
	END	
	IF @nMONTH3 > 6 AND ISNULL((SELECT SUM(S6) FROM #TMP_000),0) <> ISNULL((SELECT SUM(S6) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(S6) FROM @NADO),0) - ISNULL((SELECT SUM(S6) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY S6 DESC)
	END
--Корректировка сумм за предудущий 3 квартал
	IF @nMONTH3 > 9 AND ISNULL((SELECT SUM(S7) FROM #TMP_000),0) <> ISNULL((SELECT SUM(S7) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(S7) FROM @NADO),0) - ISNULL((SELECT SUM(S7) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY S7 DESC)
	END
	IF @nMONTH3 > 9 AND ISNULL((SELECT SUM(S8) FROM #TMP_000),0) <> ISNULL((SELECT SUM(S8) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(S8) FROM @NADO),0) - ISNULL((SELECT SUM(S8) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY S8 DESC)
	END	
	IF @nMONTH3 > 9 AND ISNULL((SELECT SUM(S9) FROM #TMP_000),0) <> ISNULL((SELECT SUM(S9) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(S9) FROM @NADO),0) - ISNULL((SELECT SUM(S9) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY S9 DESC)
	END				
	
--Корректировка сумма для отчётного квартала
	IF ISNULL((SELECT SUM(SM1) FROM #TMP_000),0) <> ISNULL((SELECT SUM(SUM_M1) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM1 = ISNULL(SM1,0) + ISNULL((SELECT SUM(SUM_M1) FROM @NADO),0) - ISNULL((SELECT SUM(SM1) FROM #TMP_000),0),
			SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(SUM_M1) FROM @NADO),0) - ISNULL((SELECT SUM(SM1) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY SM1 DESC)
	END		

	IF ISNULL((SELECT SUM(SM2) FROM #TMP_000),0) <> ISNULL((SELECT SUM(SUM_M2) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM2 = ISNULL(SM2,0) + ISNULL((SELECT SUM(SUM_M2) FROM @NADO),0) - ISNULL((SELECT SUM(SM2) FROM #TMP_000),0),
			SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(SUM_M2) FROM @NADO),0) - ISNULL((SELECT SUM(SM2) FROM #TMP_000),0)		
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY SM2 DESC)
	END	

	IF ISNULL((SELECT SUM(SM3) FROM #TMP_000),0) <> ISNULL((SELECT SUM(SUM_M3) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM3 = ISNULL(SM3,0) + ISNULL((SELECT SUM(SUM_M3) FROM @NADO),0) - ISNULL((SELECT SUM(SM3) FROM #TMP_000),0),
			SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(SUM_M3) FROM @NADO),0) - ISNULL((SELECT SUM(SM3) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY SM3 DESC)
	END	

	INSERT INTO #TMP
	SELECT R1.*, SM_ALL, SM1+SM2+SM3, SM1, SM2, SM3
	FROM #TMP0 R1, #TMP_000 R2 
	WHERE R1.PERS_LINK = R2.PERS_LINK
	
	IF @REP = 0
		SELECT * FROM #TMP ORDER BY FIO
	ELSE
	BEGIN
		--Вывод для РСВ-1, 4-ФСС
		DECLARE @Cur1 CURSOR, @LINK INT, @NUM_PP INT, @MAX_LINK INT, @FIO VARCHAR(254)
		SET @MAX_LINK = ISNULL((SELECT MAX(LINK) FROM #TMP),0)
		SET @NUM_PP = @MAX_LINK
		SET @Cur1 = CURSOR FORWARD_ONLY

		FOR SELECT DISTINCT LINK, FIO from #TMP ORDER BY FIO

		OPEN @Cur1
		FETCH NEXT FROM @Cur1 INTO @LINK, @FIO
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN
				SET @NUM_PP = @NUM_PP + 1
				UPDATE #TMP SET LINK = @NUM_PP WHERE LINK = @LINK
			END
			FETCH NEXT FROM @Cur1 INTO @LINK, @FIO
		END

		CLOSE @Cur1
		DEALLOCATE @Cur1
		
		UPDATE #TMP SET LINK = LINK - @MAX_LINK

		SELECT
			CODE = CONVERT(VARCHAR(10),LINK),
			COL1 = CONVERT(VARCHAR(10),LINK),
			COL2 = FIO,
			COL3 = ISNULL(CONVERT(VARCHAR(10),DATE_SPR,104),''),
			COL4 = ISNULL(CONVERT(VARCHAR(10),PER_END,104),''),
			COL5 = SM_ALL, 
			COL6 = SM1, 
			COL7 = SM2, 
			COL8 = SM3
		FROM
			#TMP
		ORDER BY
			LINK
	
	END

DROP TABLE #TMP		

END






GO


GRANT EXECUTE ON dbo.[RSA_RSV_1_14_PFR_INV] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[STS_LIST_M0902]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[STS_LIST_M0902]

GO

CREATE  PROC [dbo].[STS_LIST_M0902] (@linkTL int, @PeriodBegin datetime, @PeriodEnd datetime, @VNS tinyint = 1, @SVOD tinyint = 0) as
/* Тарификационный список рабочих  */

SET NOCOUNT ON

----------------------------------------------
declare @dep_link int
	Select @dep_link = dbo.getCBDepLink()

----------------------------------------------
CREATE TABLE #STO_TAR_EMPL (LINK INT, link_empl INT, FIO VARCHAR(254), TAB VARCHAR(10), pers_link INT, date_begin DATETIME,
	date_end DATETIME, link_post INT, POST_NAME VARCHAR(254), inst_chief_acc TINYINT, link_kateg INT, kateg_name VARCHAR(254),
	razr_base varchar(10), inc_ets1 TINYINT, inc_ets1_name  VARCHAR(254), inc_ets1_value TINYINT, inc_ets2 TINYINT, inc_ets2_name VARCHAR(254),
	inc_ets2_value TINYINT, inc_ets3 TINYINT, inc_ets3_name VARCHAR(254), inc_ets3_value TINYINT, RAZR varchar(10), IRAZR INT,
	DEP_LINK INT, NUM_STAKE NUMERIC(18,2), LINK_KBK  INT, SUBDIV_NAME  VARCHAR(254),[status] tinyint, NOTWORK TINYINT, subdiv_head INT,
	KOEF numeric(7,4), FOT tinyint, pkg_oklad numeric(18,2))

CREATE TABLE #K (linkKBK INT)
INSERT INTO #K (linkKBK) SELECT tlkbk.linkKBK FROM dbo.STO_TLIST_KBK tlkbk WHERE tlkbk.linkTListHead = @linkTL

CREATE TABLE #C (linkCategor INT)
INSERT INTO #C (linkCategor) SELECT linkCategor FROM DBO.STO_TLIST_CATEGOR WHERE linkTListHead = @linkTL

--DECLARE @SA_PKG_POST_FN TABLE (LINK INT, OKLAD NUMERIC(18,2) )
--INSERT INTO @SA_PKG_POST_FN (LINK, OKLAD)
--SELECT LINK, OKLAD FROM dbo.SA_PKG_POST_FN(@PeriodBegin)

--CREATE TABLE #PKG_POST_OKLAD (POST_LINK INT, PKG_OKLAD NUMERIC(18,2))
--INSERT INTO #PKG_POST_OKLAD ( POST_LINK, PKG_OKLAD)
--SELECT DISTINCT P.LINK, O.OKLAD FROM DBO.POST P INNER JOIN @SA_PKG_POST_FN O ON O.LINK = P.LINK_PKG

CREATE TABLE #PKG_POST_OKLAD (POST_LINK INT, PKG_OKLAD NUMERIC(18,2))
INSERT INTO #PKG_POST_OKLAD ( POST_LINK, PKG_OKLAD)
SELECT LINK_POST, PKG.OKLAD
FROM
	dbo.[PKG_POST_DATE] PPD
	CROSS APPLY (SELECT MIN(DATE_BEGIN)-1 AS DATE_END FROM dbo.[PKG_POST_DATE] PPD2 WHERE PPD.LINK_POST = PPD2.LINK_POST AND PPD2.DATE_BEGIN > PPD.DATE_BEGIN) D
	OUTER APPLY (SELECT TOP 1 SUMMA AS OKLAD FROM dbo.PKG_OKLAD PO WITH (NOLOCK) WHERE PO.link_up = PPD.LINK_PKG and PO.date_begin <= @PeriodBegin order by PO.date_begin desc) PKG
WHERE
	@PeriodBegin BETWEEN DATE_BEGIN AND ISNULL(D.DATE_END,@PeriodBegin)

INSERT INTO #STO_TAR_EMPL ( LINK, link_empl, FIO, TAB, pers_link, date_begin, 
	date_end, link_post, POST_NAME, inst_chief_acc, link_kateg, kateg_name,
	razr_base, inc_ets1, inc_ets1_name, inc_ets1_value, inc_ets2, inc_ets2_name, 
	inc_ets2_value, inc_ets3, inc_ets3_name, inc_ets3_value, RAZR, IRAZR,
	DEP_LINK, NUM_STAKE, LINK_KBK, SUBDIV_NAME, [status], NOTWORK, subdiv_head,
	KOEF, FOT, pkg_oklad)

SELECT T.LINK, T.link_empl, T.FIO, T.TAB, T.pers_link, T.date_begin, 
	T.date_end, T.link_post, T.POST_NAME, T.inst_chief_acc, T.link_kateg, T.kateg_name,
	convert(varchar(10),T.razr_base), T.inc_ets1, T.inc_ets1_name, T.inc_ets1_value, T.inc_ets2, T.inc_ets2_name, 
	T.inc_ets2_value, T.inc_ets3, T.inc_ets3_name, T.inc_ets3_value, convert(varchar(10),T.RAZR), T.RAZR,
	T.DEP_LINK, T.NUM_STAKE, T.LINK_KBK, SUBDIV_NAME, ISNULL([STATUS],1), ISNULL(E.NOTWORK,0), subdiv_head,
	T.KOEF, T.FOT, pkg_oklad
FROM 
	dbo.STO_TAR_EMPL_FN(DEFAULT, @PeriodBegin, DEFAULT, @DEP_LINK) T
	inner join #PKG_POST_OKLAD pkg on pkg.POST_LINK = t.link_post
	INNER JOIN dbo.EMPL E ON E.LINK = T.LINK_EMPL
	INNER JOIN #C C ON C.linkCategor = T.link_kateg --Для определенного списка категорий
	LEFT JOIN dbo.empl_status(@PeriodBegin) s on s.EMPL_LINK = T.LINK_EMPL
WHERE
	T.dep_link = @DEP_LINK
	and (@VNS <> 2 or @VNS = 2 AND ISNULL([STATUS],1) <> 3)
	AND @PeriodBegin between T.DATE_BEGIN and ISNULL(T.DATE_END, @PeriodBegin)
	and T.FOT = 2	


CREATE TABLE #DICTIONARY_STAFF_FN (LINK INT, LINK_KBK INT, FREE_STAKES NUMERIC(10,2), deleted TINYINT, date_begin DATETIME, 
									date_end DATETIME, post_link INT, post_name VARCHAR(254), kat_link INT, kat_name VARCHAR(254), 
									ets_razr INT, ets_razr2 INT, dep_link INT, subdiv_name VARCHAR(254), subdiv_link INT)
INSERT INTO #DICTIONARY_STAFF_FN (LINK, LINK_KBK, FREE_STAKES, deleted, date_begin, date_end, post_link, post_name,
					kat_link, kat_name, ets_razr, ets_razr2, dep_link, subdiv_name, subdiv_link)
SELECT LINK, LINK_KBK, FREE_STAKES, deleted, date_begin, date_end, post_link, post_name,
					kat_link, kat_name, ets_razr, ets_razr2, dep_link, subdiv_name, subdiv_link
FROM dbo.DICTIONARY_STAFF_FN(@PeriodBegin)

----Вакансии из штатного
INSERT INTO #STO_TAR_EMPL ( LINK, link_empl, FIO, TAB, pers_link, date_begin, 
	date_end, link_post, POST_NAME, inst_chief_acc, link_kateg, kateg_name,
	razr_base, inc_ets1, inc_ets1_name, inc_ets1_value, inc_ets2, inc_ets2_name, inc_ets2_value, 
	inc_ets3, inc_ets3_name, inc_ets3_value, RAZR, IRAZR, 
	DEP_LINK, NUM_STAKE, LINK_KBK, SUBDIV_NAME, [status], NOTWORK)
SELECT 
	link, 0, '', '', 0, date_begin, 
	date_end, post_link, post_name, 2, kat_link, kat_name,
	convert(varchar(10),ISNULL(ets_razr,0)) + CASE WHEN ISNULL(ets_razr2,0) > 0 THEN '..' + convert(varchar(10),ets_razr2) ELSE '' END, null, '', 0, null, '', 0,
	null, '', 0, convert(varchar(10),ISNULL(ets_razr,0)) + CASE WHEN ISNULL(ets_razr2,0) > 0 THEN '..' + convert(varchar(10),ets_razr2) ELSE '' END, ets_razr,
	dep_link, 
	ISNULL(free_stakes,0), --ISNULL(free_stakes,0) + ISNULL(NW.NUM_STAKE,0), 
	LINK_KBK, subdiv_name, 0, 0
FROM 
	#DICTIONARY_STAFF_FN S
	INNER JOIN #C C ON C.linkCategor = S.kat_link --Для определенного списка категорий
	INNER JOIN #K K ON K.linkKBK = S.LINK_KBK
	--LEFT JOIN #NOT_WORK NW ON NW.subdiv_head = S.subdiv_link AND NW.link_post = S.post_link
where 
	deleted = 0  AND free_stakes > 0 --(free_stakes > 0 OR NW.NUM_STAKE IS NOT NULL)

-------------------------------------------
DECLARE @BUFF_ID VARCHAR(20)
EXEC X_GET_TABLE_NAME @BUFF_ID OUTPUT

DECLARE @SQL_SCRIPT VARCHAR(1000)

SET @SQL_SCRIPT = 
'
INSERT INTO DBO.BUFFER (ID, LINK)
SELECT DISTINCT ''' + @BUFF_ID + ''', link_empl FROM #STO_TAR_EMPL '
EXEC (@SQL_SCRIPT)

--------------------------------------------
CREATE TABLE #all_pays_tar_empl ( link_empl int, link_tar_empl int, link_les int, link_pay int, perc NUMERIC(18,4), summa NUMERIC(18,2), link_kbk int, way_calc int, link_ets int)
INSERT INTO #all_pays_tar_empl ( link_empl, link_tar_empl, link_les, link_pay, perc, summa, link_kbk, way_calc, link_ets)
SELECT 
	PTE.LINK_EMPL, PTE.LINK_SOVM, LINK_LES = NULL, PTE.LINK_PAY, PTE.PERC,  SUM(PTE.SUMMA),  PTE.LINK_KBK, P.WAY_CALC, P.LINK_ETS
FROM 
	DBO.SA_ALL_PAYS_ALL0(DEFAULT, @PeriodBegin, @BUFF_ID, @DEP_LINK, DEFAULT) PTE
	INNER JOIN  DBO.PAYS P ON PTE.LINK_PAY = P.LINK
GROUP BY 
	PTE.LINK_EMPL, PTE.LINK_SOVM, PTE.LINK_PAY, PTE.PERC,  PTE.LINK_KBK, P.WAY_CALC, P.LINK_ETS

---
EXEC( 'DELETE FROM DBO.BUFFER WHERE ID = ''' +  @BUFF_ID + '''')


----ФОТ для вакансии
CREATE TABLE #sa_all_pays_staff_date (link_staff INT, link_pay INT, perc NUMERIC(18,2), SUMMA NUMERIC(18,2))
INSERT INTO #sa_all_pays_staff_date (link_staff, link_pay, perc, SUMMA)
SELECT link_staff, link_pay, perc, SUMMA FROM dbo.sa_all_pays_staff_date(0, @PeriodBegin)

INSERT INTO #all_pays_tar_empl ( link_empl, link_tar_empl, link_les, link_pay, perc, summa, link_kbk, way_calc, link_ets)
SELECT 
	0, PTE.link_staff, LINK_LES = NULL, PTE.link_pay, PTE.perc,  
	SUM(PTE.SUMMA * ISNULL(free_stakes,0)),--SUM(PTE.SUMMA * (ISNULL(free_stakes,0) + ISNULL(NW.NUM_STAKE,0))),  
	S.LINK_KBK, P.WAY_CALC, P.LINK_ETS
FROM 
	#DICTIONARY_STAFF_FN S
	INNER JOIN  #sa_all_pays_staff_date PTE ON S.link = PTE.link_staff
	INNER JOIN  DBO.PAYS P ON PTE.LINK_PAY = P.LINK
	INNER JOIN #K K ON K.linkKBK = LINK_KBK
	--LEFT JOIN #NOT_WORK NW ON NW.subdiv_head = S.subdiv_link AND NW.link_post = S.post_link	
GROUP BY 
	PTE.link_staff, PTE.link_pay, PTE.perc, S.LINK_KBK, P.WAY_CALC, P.LINK_ETS

DROP TABLE #DICTIONARY_STAFF_FN
DROP TABLE #sa_all_pays_staff_date	

--------------------------------------------
declare @ray_koef numeric(18,2)
	Set @ray_koef = (Select koef from dbo.DICTIONARY_MROT  where PERIOD = (Select max(PERIOD) from DICTIONARY_MROT where PERIOD <= @PeriodEnd) )
----------------------------------------------
DECLARE @linkForm int
	SET @linkForm = ISNULL( ((SELECT TOP 1 linkForm FROM sto_tlist_head WHERE link = @linkTL)),0)
----------------------------------------------

CREATE TABLE #TMP0 (link_pay INT, way_calc TINYINT, sys_0 INT, sys_1 INT, col_1 VARCHAR(254), SUBDIV VARCHAR(254), kateg VARCHAR(50), col_2 VARCHAR(254), col_4 VARCHAR(10), col_5 NUMERIC(18,2), 
	col_6n NUMERIC(18,2), col_6 VARCHAR(20), col_7 NUMERIC(18,2), col_9 NUMERIC(18,2), col_11 NUMERIC(18,2), col_12 NUMERIC(18,2), col_14 VARCHAR(20), [status] TINYINT, IRAZR TINYINT, NOTWORK TINYINT, LINK_KBK INT, NUM_STAKE NUMERIC(18,2))

INSERT INTO #TMP0 (LINK_PAY, WAY_CALC, SYS_0, SYS_1, COL_1, SUBDIV, KATEG, COL_2, COL_4, COL_5, COL_6n, COL_6, COL_7, COL_9, COL_11, COL_12, COL_14, [STATUS], IRAZR, NOTWORK, LINK_KBK, NUM_STAKE)
SELECT 
	pte.LINK_PAY,
	pte.WAY_CALC,
	sys_0= te.LINK_EMPL,
	sys_1= pte.LINK_TAR_EMPL,
	col_1= ISNULL((RTRIM(LTRIM(pers.FM)) + ' ' + RTRIM(LTRIM(IM)) + ' ' + RTRIM(LTRIM(OT))),''),
	SUBDIV = RTRIM(LTRIM(te.SUBDIV_NAME)),
	kateg = RTRIM(LTRIM(te.KATEG_NAME)),
	col_2= RTRIM(LTRIM(te.POST_NAME)),
	col_4 = ISNULL((te.RAZR),''),
	col_5 =  CONVERT(NUMERIC(18,2), (CASE WHEN TE.NUM_STAKE <> 0 THEN pte.summa / TE.NUM_STAKE ELSE 0 END)), --Здесь только оклыды
	col_6n= TE.NUM_STAKE,
	col_6= LTRIM(RTRIM(convert(VARCHAR(5),TE.NUM_STAKE))) + SPACE(1) + CASE WHEN COALESCE(te.LINK_EMPL,0) = 0 THEN 'вакант.' ELSE (CASE [STATUS] WHEN 1 THEN 'осн.ст.' WHEN 2 THEN 'сов-во' WHEN 3 THEN 'вн.совм.' END) END,
	col_7= PTE.SUMMA, --Здесь только оклыды
	col_9= 0,
	col_11= 0,
	col_12= 0,
	col_14 = CASE WHEN ISNULL(te.LINK_EMPL,0) = 0 THEN 'вакант.' ELSE (CASE [STATUS] WHEN 1 THEN 'осн.ст.' WHEN 2 THEN 'сов-во' WHEN 3 THEN 'вн.совм.' END) END,
	[STATUS],
	IRAZR,
	TE.NOTWORK,
	LINK_KBK = ISNULL(pte.LINK_KBK,te.LINK_KBK),
	NUM_STAKE = TE.NUM_STAKE
FROM	
	#STO_TAR_EMPL as te
	INNER JOIN #all_pays_tar_empl as pte on pte.link_tar_empl = te.link AND PTE.LINK_EMPL = TE.LINK_EMPL
	INNER JOIN DBO.WAY_CALC W ON W.TYPE = 1 AND W.CODE = PTE.WAY_CALC
	INNER JOIN #K K ON K.linkKBK = ISNULL(pte.link_kbk,te.LINK_KBK) --Для определенного списка КБК
	LEFT JOIN dbo.person as pers on te.pers_link = pers.link
WHERE
	--Для определенного списка нагрузок
	(pte.link_pay is null or pte.link_pay in ( SELECT linkPayWH FROM STO_TLIST_WHOURS WHERE linkTListHead = @linkTL ))
	and
	ISNULL(W.OKLAD,1) = 1

INSERT INTO #TMP0 (LINK_PAY, WAY_CALC, SYS_0, SYS_1, COL_1, SUBDIV, KATEG, COL_2, COL_4, COL_5, COL_6n, COL_6, COL_7, COL_9, COL_11, COL_12, COL_14, STATUS, IRAZR, NOTWORK, LINK_KBK, NUM_STAKE)
SELECT DISTINCT
	PTE.LINK_PAY,
	PTE.WAY_CALC,
	SYS_0,
	SYS_1,
	col_1,
	SUBDIV,
	kateg,
	col_2,
	col_4,
	col_5 = 0,
	col_6n,
	col_6,
	col_7 = 0,
	col_9= ISNULL( (CASE WHEN dbo.STO_COLUMN(pte.link_pay, 9, @linkForm) = 1 THEN pte.summa ELSE 0 END),0), --Размер повышения базовой ставки в соответствии с коэффициентом специфики, руб. (гр.7*гр8)
	col_11= ISNULL( (CASE WHEN dbo.STO_COLUMN(pte.link_pay, 11, @linkForm) = 1 THEN pte.summa ELSE 0 END),0), --Размер повышения базовой ставки в соответствии с коэффициентом стажа работы, руб. (гр.7*гр.10)
	col_12= ISNULL( (CASE WHEN dbo.STO_COLUMN(pte.link_pay, 12, @linkForm) = 1 THEN pte.summa ELSE 0 END),0), --Другие повышения, предусмотренные действующим законодательством
	col_14,
	[status],
	IRAZR,
	TE.NOTWORK,
	pte.link_kbk,
	NUM_STAKE
FROM	
	#tmp0 as te 
	INNER JOIN #all_pays_tar_empl as pte on pte.link_tar_empl = te.sys_1 AND PTE.LINK_EMPL = TE.sys_0 AND PTE.link_kbk = TE.link_kbk
	INNER JOIN DBO.WAY_CALC W ON W.TYPE = 1 AND W.CODE = PTE.WAY_CALC 
WHERE
	ISNULL(W.OKLAD,1) = 0
ORDER BY SYS_1


--------------------------------------------
SELECT ID_Num = IDENTITY(int, 1, 1), * into #tmp FROM #tmp0
----------------------------------------------

CREATE TABLE #TMP1 (SYS_0 INT, SYS_1 INT, COL_1 VARCHAR(254), SUBDIV VARCHAR(254), KATEG VARCHAR(50), COL_2 VARCHAR(254), COL_4 VARCHAR(10), COL_5 NUMERIC(18,2), 
	COL_6n NUMERIC(18,2), COL_6 VARCHAR(20), COL_7 NUMERIC(18,2), COL_9 NUMERIC(18,2), COL_11 NUMERIC(18,2), COL_12 NUMERIC(18,2), COL_14 VARCHAR(20), [STATUS] TINYINT, IRAZR TINYINT, NOTWORK TINYINT, NUM_STAKE NUMERIC(18,2))

INSERT INTO #TMP1 (SYS_0, SYS_1, COL_1, SUBDIV, KATEG, COL_2, COL_4, COL_5, COL_6n, COL_6, COL_7, COL_9, COL_11, COL_12, COL_14, [STATUS], IRAZR, NOTWORK, NUM_STAKE)
SELECT 
	SYS_0,
	SYS_1,
	COL_1, -- ФИО
	SUBDIV,
	KATEG,
	COL_2, -- Наименование профессии
	COL_4, -- Разряд оплаты труда в соответствии с тарифной сеткой по оплате труда
	COL_5 = SUM(COL_5), -- Размер базового оклада (ставки)  (гр.3*гр4)
	COL_6n, --Объем работы по данной должности (1,0; 0,75; 0,5; 0,25) 
	COL_6, --Объем работы по данной должности (1,0; 0,75; 0,5; 0,25) 
	COL_7 = SUM(COL_7), --Размер базовой ставки с учетом объема работы, руб. (гр.5*гр6)
	COL_9 = 0,
	COL_11= 0,
	COL_12= 0,
	COL_14,
	[STATUS],
	IRAZR,
	NOTWORK,
	NUM_STAKE
FROM 
	#tmp A LEFT JOIN DBO.WAY_CALC W ON W.[TYPE] = 1 AND W.CODE = A.WAY_CALC
WHERE	
	ISNULL(W.OKLAD,1) = 1
GROUP BY
	sys_0, sys_1, col_1, SUBDIV, kateg, col_2, col_4,col_5, col_6n, col_6, col_14, [status], IRAZR, NOTWORK, NUM_STAKE

INSERT INTO #TMP1 (SYS_0, SYS_1, COL_1, SUBDIV, KATEG, COL_2, COL_4, COL_5, COL_6n, COL_6, COL_7, COL_9, COL_11, COL_12, COL_14, [STATUS], IRAZR, NOTWORK, NUM_STAKE)
SELECT 
	SYS_0,
	SYS_1,
	COL_1, -- ФИО
	SUBDIV,
	KATEG,
	COL_2, -- Наименование профессии
	COL_4, -- Разряд оплаты труда в соответствии с тарифной сеткой по оплате труда
	COL_5 = 0, -- Размер базового оклада (ставки)  (гр.3*гр4)
	COL_6n, --Объем работы по данной должности (1,0; 0,75; 0,5; 0,25) 
	COL_6, --Объем работы по данной должности (1,0; 0,75; 0,5; 0,25) 
	COL_7 = 0, --Размер базовой ставки с учетом объема работы, руб. (гр.5*гр6)
	COL_9= SUM(COL_9),
	COL_11= SUM(COL_11),
	COL_12= SUM(COL_12),
	COL_14,
	[STATUS],
	IRAZR,
	NOTWORK,
	NUM_STAKE
FROM #tmp A LEFT JOIN DBO.WAY_CALC W ON W.TYPE = 1 AND W.CODE = A.WAY_CALC
WHERE	
	ISNULL(W.OKLAD,1) = 0
group by
	SYS_0, SYS_1, COL_1, SUBDIV, KATEG, COL_2, COL_4, COL_6n, COL_6, COL_14, [STATUS], IRAZR, NOTWORK, NUM_STAKE

--- печть пустой формы
INSERT INTO #TMP1 (SYS_0, SYS_1, COL_1, SUBDIV, KATEG, COL_2, COL_4, COL_5, COL_6n, COL_6, COL_7, COL_9, COL_11, COL_12, COL_14, [STATUS], IRAZR, NOTWORK, NUM_STAKE)
SELECT 0,
	/* SYS_1 - INT */ 0,
	/* COL_1 - VARCHAR(254) */ '',
	/* SUBDIV - VARCHAR(254) */ '',
	/* KATEG - VARCHAR(50) */ '',
	/* COL_2 - VARCHAR(254) */ '',
	/* COL_4 - VARCHAR(10) */ '',
	/* COL_5 - NUMERIC(18,2) */ 0,
	/* COL_6n - VARCHAR(20) */ 0,	
	/* COL_6 - VARCHAR(20) */ '',
	/* COL_7 - NUMERIC(18,2) */ 0,
	/* COL_9 - NUMERIC(18,2) */ 0,
	/* COL_11 - NUMERIC(18,2) */ 0,
	/* COL_12 - NUMERIC(18,2) */ 0,
	/* COL_14 - VARCHAR(20) */ '',
	/* STATUS - TINYINT */ 0,
	/* IRAZR - TINYINT */ 0,
	/* NOTWORK - TINYINT */ 0,
	/* NUM_STAKE - NUMERIC(18,2) */ 0
WHERE 
	NOT EXISTS (SELECT * FROM #tmp1)


EXEC X_GET_TABLE_NAME @BUFF_ID OUTPUT

SET @SQL_SCRIPT = 
'
INSERT INTO DBO.BUFFER (ID, LINK)
SELECT DISTINCT ''' + @BUFF_ID + ''', E.link_empl 
FROM #STO_TAR_EMPL E INNER JOIN dbo.STO_ADD_PAYMENT AP ON E.link_empl = AP.LINK_EMPL
WHERE AP.mode = 2 
'
EXEC (@SQL_SCRIPT)
	
CREATE TABLE #SA_TarEmpl_PercAddStage(LINK_TAREMPL INT, LINK_EMPL INT, LINK_KATEG INT, STAGE NUMERIC(5,2), PERC NUMERIC(5,2), EXPIR_LINK INT, MAX_PERC NUMERIC(5,2), MAX_EXPIR_LINK INT)
INSERT INTO #SA_TarEmpl_PercAddStage(LINK_TAREMPL, LINK_EMPL, LINK_KATEG, STAGE, PERC, EXPIR_LINK, MAX_PERC, MAX_EXPIR_LINK)
SELECT LINK_TAREMPL, LINK_EMPL, LINK_KATEG, STAGE, PERC, EXPIR_LINK, MAX_PERC, MAX_EXPIR_LINK
FROM dbo.SA_TarEmpl_PercAddStage(@PeriodBegin, DEFAULT, DEFAULT, @BUFF_ID, @DEP_LINK, DEFAULT)

EXEC( 'DELETE FROM DBO.BUFFER WHERE ID = ''' +  @BUFF_ID + '''')

--Информация о стаже
create table #stage (link_tarEmpl int, link_empl int, link_kateg int, stage VARCHAR(20), perc NUMERIC(18,2), expir_link int, max_perc NUMERIC(18,2))
insert into #stage (link_tarEmpl, link_empl, link_kateg, stage, perc, expir_link, max_perc)
SELECT distinct 
	ST.link_tarEmpl, ST.link_empl, ST.link_kateg, 
	stage = convert(VARCHAR(5),convert(int,ST.stage)) + 'г.' + convert(VARCHAR(10),convert(int,round((ST.stage - convert(int,ST.stage)) * 12, 0))) + 'м.', 
	ST.perc, ST.expir_link, ST.max_perc 
FROM 
	dbo.STO_ADD_PAYMENT AP
	INNER JOIN #SA_TarEmpl_PercAddStage ST ON ST.LINK_TAREMPL = ap.link_tar_empl AND ST.LINK_EMPL = AP.LINK_EMPL 
WHERE
	AP.mode = 2
	AND
	max_perc > 0
	AND
	(ST.perc = ST.max_perc AND AP.link_expir IS NULL OR ST.expir_link = AP.link_expir)
order by 
	link_tarEmpl

DROP TABLE #SA_TarEmpl_PercAddStage

---------------------------------------------------
EXEC X_GET_TABLE_NAME @BUFF_ID OUTPUT

SET @SQL_SCRIPT = 
'
INSERT INTO DBO.BUFFER (ID, LINK)
SELECT DISTINCT ''' + @BUFF_ID + ''', E.link_empl 
FROM #STO_TAR_EMPL E INNER JOIN dbo.STO_ADD_PAYMENT AP ON E.link_empl = AP.LINK_EMPL
WHERE AP.mode = 2  AND E.link_empl NOT IN (SELECT link_empl FROM #stage)
'
EXEC (@SQL_SCRIPT)

CREATE TABLE #SA_TarEmpl_PercAddStage2(LINK_TAREMPL INT, LINK_EMPL INT, LINK_KATEG INT, STAGE NUMERIC(5,2), PERC NUMERIC(5,2), EXPIR_LINK INT, MAX_PERC NUMERIC(5,2), MAX_EXPIR_LINK INT)
INSERT INTO #SA_TarEmpl_PercAddStage2(LINK_TAREMPL, LINK_EMPL, LINK_KATEG, STAGE, PERC, EXPIR_LINK, MAX_PERC, MAX_EXPIR_LINK)
SELECT LINK_TAREMPL, LINK_EMPL, LINK_KATEG, STAGE, PERC, EXPIR_LINK, MAX_PERC, MAX_EXPIR_LINK
FROM dbo.SA_TarEmpl_PercAddStage(@PeriodEnd, DEFAULT, DEFAULT, @BUFF_ID, @DEP_LINK, DEFAULT)

EXEC( 'DELETE FROM DBO.BUFFER WHERE ID = ''' +  @BUFF_ID + '''')
	
--Информация о стаже для тех, у кого не было надбавки за стаж на дату начала, но будет на дату окончания
create table #stage2 (link_tarEmpl int, link_empl int, link_kateg int, stage VARCHAR(20), perc NUMERIC(18,2), expir_link int, max_perc NUMERIC(18,2))
insert into #stage2 (link_tarEmpl, link_empl, link_kateg, stage, perc, expir_link, max_perc)
SELECT distinct 
	ST.link_tarEmpl, ST.link_empl, ST.link_kateg, 
	stage = convert(VARCHAR(5),convert(int,ST.stage)) + 'г.' + convert(VARCHAR(10),convert(int,round((ST.stage - convert(int,ST.stage)) * 12, 0))) + 'м.', 
	ST.perc, ST.expir_link, ST.max_perc 
FROM 
	dbo.STO_ADD_PAYMENT AP
	INNER JOIN #SA_TarEmpl_PercAddStage2 ST ON ST.LINK_TAREMPL = ap.link_tar_empl AND ST.LINK_EMPL = AP.LINK_EMPL 
WHERE
	AP.mode = 2
	AND
	max_perc > 0	
	AND
	(ST.perc = ST.max_perc AND AP.link_expir IS NULL OR ST.expir_link = AP.link_expir)
order by 
	link_tarEmpl

DROP TABLE #SA_TarEmpl_PercAddStage2


-- Две строки со стажем
SELECT 
	link_empl = sys_0,
	link_tar_empl = sys_1,
	date_new_ap_stazh = dbo.SA_TarEmpl_GetDateChangePercStazh(sys_0,@PeriodBegin, @PeriodEnd, st.expir_link),
	st.expir_link
into #st_info
FROM 
	(SELECT distinct sys_0, sys_1 FROM #tmp1) T
	INNER JOIN #stage ST on ST.link_tarEmpl = sys_1 AND ST.LINK_EMPL = SYS_0
	
-- Две строки со стажем для тех, у кого не было надбавки за стаж на дату начала, но будет на дату окончания
insert into #st_info (link_empl, link_tar_empl, date_new_ap_stazh, expir_link)
SELECT 
	link_empl = sys_0,
	link_tar_empl = sys_1,
	date_new_ap_stazh = dbo.SA_TarEmpl_GetDateChangePercStazh(sys_0,@PeriodBegin, @PeriodEnd, st.expir_link),
	st.expir_link
FROM 
	(SELECT distinct sys_0, sys_1 FROM #tmp1) T
	INNER JOIN #stage2 ST on ST.link_tarEmpl = sys_1 AND ST.LINK_EMPL = SYS_0	
where not exists (select * from #st_info i where i.link_empl = sys_0 and i.link_tar_empl = sys_1)


--
SELECT  
	i.link_empl,
	i.link_tar_empl,
	date_new_ap_stazh,
	new_calc_perc = dbo.SA_TarEmpl_GetPercAddStage(i.link_empl, i.link_tar_empl, date_new_ap_stazh,expir_link, @DEP_LINK)
into #st_info2
FROM 
	#st_info i
WHERE	
	i.date_new_ap_stazh is not null


---
declare @TL_NAME VARCHAR(254)
SET @TL_NAME = ISNULL( (SELECT TOP 1 name FROM sto_tlist_head WHERE link = @linkTL),'')

declare @MinETS numeric(18,2)
Set @MinETS = (select top 1 min_val from #all_pays_tar_empl A inner join dbo.PAYS P on P.link = A.link_pay inner join dbo.sa_ets_Actual(@PeriodBegin) ETS on P.link_ets = ETS.LINK)

----- Вывод результата

CREATE TABLE #RES (TL_NAME VARCHAR(254), PERIOD VARCHAR(10), SYS_0 INT, SYS_1 INT, COL_1 VARCHAR(254), SUBDIV VARCHAR(254), KATEG VARCHAR(50), COL_2 VARCHAR(254), COL_3 NUMERIC(18,2), COL_4 VARCHAR(10), COL_5 NUMERIC(18,2), 
	COL_6n NUMERIC(18,2), COL_6 VARCHAR(20), COL_7 NUMERIC(18,2), COL_8 NUMERIC(18,4), COL_9 NUMERIC(18,2), COL_10 NUMERIC(18,4), COL_11 NUMERIC(18,2), COL_12 NUMERIC(18,2), COL_13 NUMERIC(18,2), COL_14 VARCHAR(20), MARK TINYINT, SUMMAR TINYINT, IRAZR TINYINT, NUM_STAKE NUMERIC(18,2))

INSERT INTO #RES (TL_NAME, PERIOD, SYS_0, SYS_1, COL_1, SUBDIV, KATEG, COL_2, COL_3, COL_4, COL_5, COL_6n, COL_6, COL_7, COL_8, COL_9, COL_10, COL_11, COL_12, COL_13, COL_14, [MARK], SUMMAR, IRAZR, NUM_STAKE)  
SELECT 
	TL_Name= @TL_NAME,
	period = convert(VARCHAR(10),@PeriodBegin,104),
	sys_0,
	sys_1,
	col_1, -- ФИО
	SUBDIV = UPPER(COALESCE(SUBDIV,'')), 
	kateg = LOWER(COALESCE(kateg,'')),
	col_2, -- Должность
	col_3 = @MinETS, -- Размер базовой единицы
	col_4, -- Разряд оплаты труда в соответствии с тарифной сеткой по оплате труда
	col_5 = sum(col_5), -- Размер базового оклада (ставки)  (гр.3*гр4)
	col_6n, --Объем работы по данной должности (1,0; 0,75; 0,5; 0,25) 
	col_6, --Объем работы по данной должности (1,0; 0,75; 0,5; 0,25) 
	col_7 = sum(col_7), --Размер базовой ставки с учетом объема работы, руб. (гр.5*гр6)
	col_8= Round(CASE WHEN sum(col_7) > 0 THEN sum(col_9) / sum(col_7) ELSE 0 END,4), --Коэффициент специфики
	col_9= sum(col_9), --Коэффициент специфики
	col_10= Round(CASE WHEN sum(col_7) > 0 THEN sum(col_11) / sum(col_7) ELSE 0 END,4), --Коэффициент стажа
	col_11= sum(col_11), --Коэффициент стажа 
	col_12= sum(col_12),
	col_13 = sum(col_7) + sum(col_9) + sum(col_11) + sum(col_12),
	col_14 = 
		(	-- либо у кого меняется стаж
			CASE WHEN i.LINK_TAR_EMPL IS NOT NULL THEN 'изм.стаж' ELSE
				-- либо кто временно не работает,
				CASE WHEN NOTWORK > 0 THEN 'врем.не раб.' ELSE
					CASE WHEN @VNS=3 and [status] = 3 THEN 'внеш.совм' ELSE
						LTRIM(RTRIM(col_24)) + SPACE(1)+ coalesce(st.stage,COALESCE(dbo.sa_empl_nepr_stage( sys_0, @PeriodBegin),''))
					END
				END
			END
		),				
	MARK = --Выделяем тех, кто временно не работает, 
		(CASE WHEN 
			i.LINK_TAR_EMPL IS NOT NULL -- либо у кого меняется стаж
			OR NOTWORK > 0 -- либо кто временно не работает,
			OR @VNS=3 and [status] = 3 --либо если внешнего совместителя включают в список, но не включают в итоги
		THEN 1 ELSE 0 END),
	[summar] = --Выделяем тех, кто временно не работает, 
		(CASE WHEN 
			i.LINK_TAR_EMPL IS NOT NULL -- либо у кого меняется стаж
			OR NOTWORK > 0 -- либо кто временно не работает,
			OR @VNS=3 and [status] = 3 --либо если внешнего совместителя включают в список, но не включают в итоги
		THEN 0 ELSE 1 END),			
	--col_14 = ltrim(rtrim(col_14)) + SPACE(1) + coalesce(st.stage,COALESCE(dbo.sa_empl_nepr_stage( sys_0, @PeriodBegin),'')),
	--MARK = (CASE WHEN i.link_tar_empl is null THEN 0 ELSE 1 END),
	--[summar] = CASE WHEN coalesce(i.link_tar_empl,0) > 0 or @VNS=3 and [status] = 3 THEN 0 ELSE 1 END,
	irazr,
	NUM_STAKE
FROM 
	#tmp1 T LEFT JOIN dbo.sa_ets_actual(@PeriodBegin) AS ets18 on ets18.link = t.col_9 AND ets18.razr = 18
	LEFT JOIN #stage as St on St.link_tarEmpl = sys_1 AND ST.LINK_EMPL = SYS_0
	LEFT JOIN #st_info2 i on i.link_empl = t.sys_0 and i.link_tar_empl = t.sys_1
GROUP BY
	sys_0, sys_1, i.link_tar_empl, col_1, SUBDIV, kateg, col_2, col_4, col_6n, col_6, st.stage, col_14, [status], irazr, NOTWORK, NUM_STAKE

INSERT INTO #RES (TL_NAME, PERIOD, SYS_0, SYS_1, COL_1, SUBDIV, KATEG, COL_2, COL_3, COL_4, COL_5, COL_6n, COL_6, COL_7, COL_8, COL_9, COL_10, COL_11, COL_12, COL_13, COL_14, [MARK], SUMMAR, IRAZR, NUM_STAKE)  
SELECT 
	TL_Name= @TL_NAME,
	period = convert(VARCHAR(10),@PeriodBegin,104),
	sys_0,
	sys_1,
	col_1, -- ФИО
	SUBDIV = UPPER(COALESCE(SUBDIV,'')), kateg = LOWER(COALESCE(kateg,'')),
	col_2, -- Должность
	col_3 = @MinETS, -- Размер базовой единицы
	col_4, -- Разряд оплаты труда в соответствии с тарифной сеткой по оплате труда
	col_5 = sum(col_5), -- Размер базового оклада (ставки)  (гр.3*гр4)
	col_6n, --Объем работы по данной должности (1,0; 0,75; 0,5; 0,25) 
	col_6, --Объем работы по данной должности (1,0; 0,75; 0,5; 0,25) 	
	col_7 = sum(col_7), --Размер базовой ставки с учетом объема работы, руб. (гр.5*гр6)
	col_8= Round(CASE WHEN sum(col_7) > 0 THEN sum(col_9) / sum(col_7) ELSE 0 END,4), --Коэффициент специфики
	col_9= sum(col_9), --Коэффициент специфики
	col_10= new_calc_perc, --Коэффициент стажа
	col_11= convert(numeric(18,2), sum(col_7) * new_calc_perc), --Коэффициент стажа 
	col_12= sum(col_12),
	col_13 = sum(col_7) + sum(col_9) + sum(col_11) + sum(col_12),
	col_14 = ltrim(rtrim(col_14)) + SPACE(1) + convert(varchar(10),date_new_ap_stazh,104),
	MARK = 0,
	[summar] = CASE WHEN @VNS=3 and [status] = 3 THEN 0 ELSE 1 END,
	irazr,
	NUM_STAKE
FROM 
	#tmp1 T INNER JOIN #st_info2 i on i.link_empl = t.sys_0
	LEFT JOIN dbo.sa_ets_actual(@PeriodBegin) AS ets18 on ets18.link = t.col_9 AND ets18.razr = 18
	LEFT JOIN #stage as St on St.link_tarEmpl = sys_1 AND ST.LINK_EMPL = SYS_0
WHERE
	NOTWORK = 0	
group by
	SUBDIV, kateg, sys_0, sys_1, col_1, SUBDIV, kateg, col_2, col_4, col_6n, col_6, st.stage, col_14, date_new_ap_stazh, new_calc_perc, [status], i.link_tar_empl, NOTWORK, irazr, NUM_STAKE
order by
	SUBDIV, kateg asc, col_3 desc, sys_0, sys_1 asc

SET NOCOUNT OFF

---
IF @SVOD = 0
	SELECT * FROM #RES ORDER BY SUBDIV, KATEG ASC, (CASE WHEN SYS_0 = 0 THEN 1 ELSE 0 END), IRAZR DESC, COL_1, SYS_1 ASC, MARK DESC

IF @SVOD = 1 BEGIN

	SELECT SUB = SUBDIV, A = 'A', ST = SUM(NUM_STAKE), S = SUM(col_13)--, CNT_STAKE = SUM(COL_12), OKLAD_ETS = SUM(COL_13), ADD_VRED = SUM(COL_15), ADD_STAGE = SUM(COL_21), ITOGO = SUM(COL_22)
	INTO #RES1	
	FROM #RES
	WHERE summar = 1
	group by SUBDIV
	order by SUBDIV

	DECLARE @TABLE1 VARCHAR(100), @TABLE2 VARCHAR(100), @TABLE3 VARCHAR(100), @TABLE4 VARCHAR(100), @TABLE5 VARCHAR(100)
	EXEC X_GET_TABLE_NAME @TABLE1 OUTPUT
	SELECT @TABLE2 = @TABLE1+'2', @TABLE3 = @TABLE1 + '3', @TABLE4 = @TABLE1 + '4', @TABLE5 = @TABLE1 + '5'

	SELECT SUBDIV,KATEG, OKLAD = SUM(col_7), VRED = SUM(COL_9), STAGE = SUM(COL_11), ITOG = SUM(col_13)
	INTO #RES2	
	FROM #RES
	WHERE summar = 1
	group by SUBDIV,KATEG
	order by SUBDIV,KATEG

	SELECT SUBDIV,KAT = KATEG,CNT = SUM(NUM_STAKE) -- Кол-во ставок
	INTO #RES3	
	FROM #RES
	WHERE summar = 1
	group by SUBDIV,KATEG
	order by SUBDIV,KATEG

	EXEC M_CROSS_TABLE
		'SUBDIV', 
		'KAT', 'VARCHAR(254)', 
		'CNT', 'NUMERIC(20,2)', 'SUM(CNT) AS CNT',
		'#RES3', @TABLE1

	EXEC M_CROSS_TABLE
		'SUBDIV', 
		'KATEG', 'VARCHAR(254)', 
		'OKLAD', 'NUMERIC(20,2)', 'SUM(OKLAD) AS OKLAD',
		'#RES2', @TABLE2

	EXEC M_CROSS_TABLE
		'SUBDIV', 
		'KATEG', 'VARCHAR(254)', 
		'VRED', 'NUMERIC(20,2)', 'SUM(VRED) AS VRED',
		'#RES2', @TABLE3

	EXEC M_CROSS_TABLE
		'SUBDIV', 
		'KATEG', 'VARCHAR(254)', 
		'STAGE', 'NUMERIC(20,2)', 'SUM(STAGE) AS STAGE',
		'#RES2', @TABLE4

	EXEC M_CROSS_TABLE
		'SUBDIV', 
		'KATEG', 'VARCHAR(254)', 
		'ITOG', 'NUMERIC(20,2)', 'SUM(ITOG) AS ITOG',
		'#RES2', @TABLE5

	EXEC (' SELECT R0.SUB, R0.ST, R0.S, R1.*, R2.*, R3.*, R4.*, R5.* FROM #RES1 R0
			LEFT JOIN ' + @TABLE1 + ' R1 ON R1.SUBDIV = R0.SUB
			LEFT JOIN ' + @TABLE2 + ' R2 ON R2.SUBDIV = R0.SUB
			LEFT JOIN ' + @TABLE3 + ' R3 ON R3.SUBDIV = R0.SUB
			LEFT JOIN ' + @TABLE4 + ' R4 ON R4.SUBDIV = R0.SUB
			LEFT JOIN ' + @TABLE5 + ' R5 ON R5.SUBDIV = R0.SUB
	')

END

RETURN 0




GO


GRANT EXECUTE ON dbo.[STS_LIST_M0902] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[KU_POST_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KU_POST_SAVE]

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE  PROCEDURE dbo.KU_POST_SAVE
	@varKSparLINK int OUTPUT,
	@varKSparCODE VARCHAR(10) = null,
	@varKSparNAME VARCHAR(254) = null
AS 
	DECLARE 
		@varKSERROR	int,
		@varKSRowCount int,
		@varKSstrVALUE	varchar(7000),
		@varKStrancount	int,
		@varKSEventText	varchar(254), 
		@varKSObject INT
	SET LOCK_TIMEOUT 30000
	SET @varKStrancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON
	BEGIN TRAN
	COMMIT TRAN
	
	EXECUTE @varKSERROR = X_TEST_POST_CODE @varKSparLINK, @varKSparCODE
	IF @varKSERROR <> 0
		RETURN @varKSERROR
	
	IF @varKSparCODE IS NULL OR LEN(@varKSparCODE) = 0 OR @varKSparNAME IS NULL OR LEN(@varKSparNAME) = 0 BEGIN
		ROLLBACK
		RETURN 5
	END

	IF @varKSparLINK is null OR @varKSparLINK = 0
	BEGIN
		INSERT INTO POST WITH (ROWLOCK) (CODE, [NAME]) 
		VALUES (@varKSparCODE, @varKSparNAME)
		SELECT @varKSERROR = @@ERROR, @varKSparLINK=@@identity
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	ELSE BEGIN
		UPDATE POST WITH (ROWLOCK) 
		SET CODE = @varKSparCODE, [NAME]=@varKSparNAME
		WHERE LINK=@varKSparLINK
		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END

	
	SET @varKSEventText = 'Должности' + ' ' +  RTRIM(CONVERT(VARCHAR(50),@varKSparCODE))+' '+ RTRIM(CONVERT(VARCHAR(7000), @varKSparNAME))
	SET @varKSObject = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'DICTIONARY_POST')
	EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника', @varKSEventText, @varKSObject, 'POST', @varKSparLINK

	IF @@TRANCOUNT > @varKStrancount
		COMMIT TRAN
	RETURN 0



GO


GRANT EXECUTE ON dbo.[KU_POST_SAVE] TO PUBLIC

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[STS_LIST_M0901]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[STS_LIST_M0901]

GO

CREATE  proc [dbo].[STS_LIST_M0901] (@linkTL int, @PeriodBegin datetime, @PeriodEnd datetime, @VNS tinyint = 1, @SVOD tinyint = 0) as
/* Тарификационный список №2 по сотоянию ра расчетный период */

SET NOCOUNT ON

DECLARE @DEP_LINK INT
SELECT @DEP_LINK = dbo.getCBDepLink()

----------------------------------------------
CREATE TABLE #STO_TAR_EMPL (LINK INT, link_empl INT, FIO VARCHAR(254), TAB VARCHAR(10), pers_link INT, date_begin DATETIME,
	date_end DATETIME, link_post INT, POST_NAME VARCHAR(254), inst_chief_acc TINYINT, link_kateg INT, kateg_name VARCHAR(254),
	razr_base varchar(10), inc_ets1 TINYINT, inc_ets1_name  VARCHAR(254), inc_ets1_value TINYINT, inc_ets2 TINYINT, inc_ets2_name VARCHAR(254),
	inc_ets2_value TINYINT, inc_ets3 TINYINT, inc_ets3_name VARCHAR(254), inc_ets3_value TINYINT, RAZR varchar(10), IRAZR INT,
	DEP_LINK INT, NUM_STAKE NUMERIC(18,3), LINK_KBK  INT, SUBDIV_NAME  VARCHAR(254),[status] tinyint, NOTWORK TINYINT, subdiv_head INT,
	KOEF numeric(7,4), FOT tinyint, pkg_oklad numeric(18,2))

CREATE TABLE #K (linkKBK INT)
INSERT INTO #K (linkKBK) SELECT tlkbk.linkKBK FROM dbo.STO_TLIST_KBK tlkbk WHERE tlkbk.linkTListHead = @linkTL

CREATE TABLE #C (linkCategor INT)
INSERT INTO #C (linkCategor) SELECT linkCategor FROM DBO.STO_TLIST_CATEGOR WHERE linkTListHead = @linkTL

--DECLARE @SA_PKG_POST_FN TABLE (LINK INT, OKLAD NUMERIC(18,2) )
--INSERT INTO @SA_PKG_POST_FN (LINK, OKLAD)
--SELECT LINK, OKLAD FROM dbo.SA_PKG_POST_FN(@PeriodBegin)

--CREATE TABLE #PKG_POST_OKLAD (POST_LINK INT, PKG_OKLAD NUMERIC(18,2))
--INSERT INTO #PKG_POST_OKLAD ( POST_LINK, PKG_OKLAD)
--SELECT DISTINCT P.LINK, O.OKLAD FROM DBO.POST P INNER JOIN @SA_PKG_POST_FN O ON O.LINK = P.LINK_PKG

CREATE TABLE #PKG_POST_OKLAD (POST_LINK INT, PKG_OKLAD NUMERIC(18,2))
INSERT INTO #PKG_POST_OKLAD ( POST_LINK, PKG_OKLAD)
SELECT LINK_POST, PKG.OKLAD
FROM
	dbo.[PKG_POST_DATE] PPD
	CROSS APPLY (SELECT MIN(DATE_BEGIN)-1 AS DATE_END FROM dbo.[PKG_POST_DATE] PPD2 WHERE PPD.LINK_POST = PPD2.LINK_POST AND PPD2.DATE_BEGIN > PPD.DATE_BEGIN) D
	OUTER APPLY (SELECT TOP 1 SUMMA AS OKLAD FROM dbo.PKG_OKLAD PO WITH (NOLOCK) WHERE PO.link_up = PPD.LINK_PKG and PO.date_begin <= @PeriodBegin order by PO.date_begin desc) PKG
WHERE
	@PeriodBegin BETWEEN DATE_BEGIN AND ISNULL(D.DATE_END,@PeriodBegin)

INSERT INTO #STO_TAR_EMPL ( LINK, link_empl, FIO, TAB, pers_link, date_begin, 
	date_end, link_post, POST_NAME, inst_chief_acc, link_kateg, kateg_name,
	razr_base, inc_ets1, inc_ets1_name, inc_ets1_value, inc_ets2, inc_ets2_name, 
	inc_ets2_value, inc_ets3, inc_ets3_name, inc_ets3_value, RAZR, IRAZR,
	DEP_LINK, NUM_STAKE, LINK_KBK, SUBDIV_NAME, [status], NOTWORK, subdiv_head,
	KOEF, FOT, pkg_oklad)

SELECT T.LINK, T.link_empl, T.FIO, T.TAB, T.pers_link, T.date_begin, 
	T.date_end, T.link_post, T.POST_NAME, T.inst_chief_acc, T.link_kateg, T.kateg_name,
	convert(varchar(10),T.razr_base), T.inc_ets1, T.inc_ets1_name, T.inc_ets1_value, T.inc_ets2, T.inc_ets2_name, 
	T.inc_ets2_value, T.inc_ets3, T.inc_ets3_name, T.inc_ets3_value, convert(varchar(10),T.RAZR), T.RAZR,
	T.DEP_LINK, T.NUM_STAKE, T.LINK_KBK, SUBDIV_NAME, ISNULL([STATUS],1), ISNULL(E.NOTWORK,0), subdiv_head,
	T.KOEF, T.FOT, pkg_oklad
FROM 
	dbo.STO_TAR_EMPL_FN(DEFAULT, @PeriodBegin, DEFAULT, @DEP_LINK) T
	INNER JOIN #PKG_POST_OKLAD pkg on pkg.POST_LINK = t.link_post
	INNER JOIN dbo.EMPL E ON E.LINK = T.LINK_EMPL
	INNER JOIN #C C ON C.linkCategor = T.link_kateg --Для определенного списка категорий
	LEFT JOIN dbo.empl_status(@PeriodBegin) s on s.EMPL_LINK = T.LINK_EMPL
WHERE
	T.dep_link = @DEP_LINK
	and (@VNS <> 2 or @VNS = 2 AND ISNULL([STATUS],1) <> 3)
	AND @PeriodBegin between T.DATE_BEGIN and ISNULL(T.DATE_END, @PeriodBegin)
	and T.FOT = 1
	----!!!
	--AND T.link_empl = 2125

---- Это доп вакансии
--CREATE TABLE #NOT_WORK (subdiv_head INT, link_post INT, NUM_STAKE NUMERIC(18,2))

--INSERT INTO #NOT_WORK (subdiv_head, link_post, NUM_STAKE)
--SELECT subdiv_head, link_post, SUM(NUM_STAKE)
--FROM #STO_TAR_EMPL WHERE NOTWORK = 1 
--GROUP BY subdiv_head, link_post


CREATE TABLE #DICTIONARY_STAFF_FN (LINK INT, LINK_KBK INT, FREE_STAKES NUMERIC(18,3), deleted TINYINT, date_begin DATETIME, 
									date_end DATETIME, post_link INT, post_name VARCHAR(254), kat_link INT, kat_name VARCHAR(254), 
									ets_razr INT, ets_razr2 INT, dep_link INT, subdiv_name VARCHAR(254), subdiv_link INT, pkg_oklad numeric(18,2))
INSERT INTO #DICTIONARY_STAFF_FN (LINK, LINK_KBK, FREE_STAKES, deleted, date_begin, date_end, post_link, post_name,
					kat_link, kat_name, ets_razr, ets_razr2, dep_link, subdiv_name, subdiv_link, pkg_oklad)
SELECT LINK, LINK_KBK, FREE_STAKES, deleted, date_begin, date_end, T.post_link, post_name,
					kat_link, kat_name, ets_razr, ets_razr2, dep_link, subdiv_name, subdiv_link, pkg_oklad
FROM 
	dbo.DICTIONARY_STAFF_FN(@PeriodBegin) T
	INNER JOIN #PKG_POST_OKLAD pkg on pkg.POST_LINK = t.post_link

--Вакансии из штатного
INSERT INTO #STO_TAR_EMPL ( LINK, link_empl, FIO, TAB, pers_link, date_begin, 
	date_end, link_post, POST_NAME, inst_chief_acc, link_kateg, kateg_name,
	razr_base, inc_ets1, inc_ets1_name, inc_ets1_value, inc_ets2, inc_ets2_name, inc_ets2_value, 
	inc_ets3, inc_ets3_name, inc_ets3_value, RAZR, IRAZR, 
	DEP_LINK, NUM_STAKE, LINK_KBK, SUBDIV_NAME, [status], NOTWORK, pkg_oklad)
SELECT 
	link, 0, '', '', 0, date_begin, 
	date_end, post_link, post_name, 2, kat_link, kat_name,
	convert(varchar(10),ISNULL(ets_razr,0)) + CASE WHEN ISNULL(ets_razr2,0) > 0 THEN '..' + convert(varchar(10),ets_razr2) ELSE '' END, null, '', 0, null, '', 0,
	null, '', 0, convert(varchar(10),ISNULL(ets_razr,0)) + CASE WHEN ISNULL(ets_razr2,0) > 0 THEN '..' + convert(varchar(10),ets_razr2) ELSE '' END, ets_razr,
	dep_link, 
	ISNULL(free_stakes,0), --ISNULL(free_stakes,0) + ISNULL(NW.NUM_STAKE,0), 
	LINK_KBK, subdiv_name, 0, 0, pkg_oklad
FROM 
	#DICTIONARY_STAFF_FN S
	INNER JOIN #C C ON C.linkCategor = S.kat_link --Для определенного списка категорий
	INNER JOIN #K K ON K.linkKBK = S.LINK_KBK
	--LEFT JOIN #NOT_WORK NW ON NW.subdiv_head = S.subdiv_link AND NW.link_post = S.post_link
where 
	deleted = 0  AND free_stakes > 0 --(free_stakes > 0 OR NW.NUM_STAKE IS NOT NULL)

-------------------------------------------
DECLARE @BUFF_ID VARCHAR(20)
EXEC X_GET_TABLE_NAME @BUFF_ID OUTPUT

DECLARE @SQL_SCRIPT VARCHAR(1000)

SET @SQL_SCRIPT = 
'
INSERT INTO DBO.BUFFER (ID, LINK)
SELECT DISTINCT ''' + @BUFF_ID + ''', link_empl FROM #STO_TAR_EMPL '
EXEC (@SQL_SCRIPT)

--------------------------------------------
CREATE TABLE #all_pays_tar_empl ( link_empl int, link_tar_empl int, link_les int, link_pay int, perc NUMERIC(18,4), summa NUMERIC(18,2), link_kbk int, way_calc int, link_ets int)
INSERT INTO #all_pays_tar_empl ( link_empl, link_tar_empl, link_les, link_pay, perc, summa, link_kbk, way_calc, link_ets)
SELECT 
	PTE.LINK_EMPL, PTE.LINK_SOVM, LINK_LES = NULL, PTE.LINK_PAY, PTE.PERC,  SUM(PTE.SUMMA),  PTE.LINK_KBK, P.WAY_CALC, P.LINK_ETS
FROM 
	DBO.SA_ALL_PAYS_ALL0(DEFAULT, @PeriodBegin, @BUFF_ID, @DEP_LINK, DEFAULT) PTE
	INNER JOIN  DBO.PAYS P ON PTE.LINK_PAY = P.LINK
GROUP BY 
	PTE.LINK_EMPL, PTE.LINK_SOVM, PTE.LINK_PAY, PTE.PERC,  PTE.LINK_KBK, P.WAY_CALC, P.LINK_ETS

---
EXEC( 'DELETE FROM DBO.BUFFER WHERE ID = ''' +  @BUFF_ID + '''')

----ФОТ для вакансии
CREATE TABLE #sa_all_pays_staff_date (link_staff INT, link_pay INT, perc NUMERIC(18,2), SUMMA NUMERIC(18,2))
INSERT INTO #sa_all_pays_staff_date (link_staff, link_pay, perc, SUMMA)
SELECT link_staff, link_pay, perc, SUMMA FROM dbo.sa_all_pays_staff_date(DEFAULT, @PeriodBegin)

INSERT INTO #all_pays_tar_empl ( link_empl, link_tar_empl, link_les, link_pay, perc, summa, link_kbk, way_calc, link_ets)
SELECT 
	0, PTE.link_staff, LINK_LES = NULL, PTE.link_pay, PTE.perc,  
	SUM(PTE.SUMMA * ISNULL(FREE_STAKES,0)),--SUM(PTE.SUMMA * (ISNULL(free_stakes,0) + ISNULL(NW.NUM_STAKE,0))),  
	S.LINK_KBK, P.WAY_CALC, P.LINK_ETS
FROM 
	#DICTIONARY_STAFF_FN S
	INNER JOIN  #sa_all_pays_staff_date PTE ON S.link = PTE.link_staff
	INNER JOIN  DBO.PAYS P ON PTE.LINK_PAY = P.LINK
	INNER JOIN #K K ON K.linkKBK = LINK_KBK
	--LEFT JOIN #NOT_WORK NW ON NW.subdiv_head = S.subdiv_link AND NW.link_post = S.post_link	
GROUP BY 
	PTE.link_staff, PTE.link_pay, PTE.perc, S.LINK_KBK, P.WAY_CALC, P.LINK_ETS

DROP TABLE #DICTIONARY_STAFF_FN
DROP TABLE #sa_all_pays_staff_date	

--------------------------------------------
declare @ray_koef numeric(18,2)
	Set @ray_koef = (Select koef from dbo.DICTIONARY_MROT  where PERIOD = (Select max(PERIOD) from DICTIONARY_MROT where PERIOD <= @PeriodEnd) )
----------------------------------------------
DECLARE @linkForm int
	SET @linkForm = ISNULL( ((SELECT TOP 1 linkForm FROM STO_TLIST_HEAD WHERE link = @linkTL)),0)
----------------------------------------------
CREATE TABLE #tmp0
(
	link_pay INT, 
	way_calc INT, 
	link_les INT, 
	sys_0 INT, 
	sys_1 INT, 
	col_1 VARCHAR(254), 
	SUBDIV VARCHAR(254), 
	kateg VARCHAR(254), 
	col_2 VARCHAR(254), 
	col_3 NUMERIC(18,2), 
	col_4 NUMERIC(18,4), 
	col_5 NUMERIC(18,2),
	col_7 NUMERIC(18,2),
	col_8 NUMERIC(18,2),
	col_9n NUMERIC(18,2),
	col_9 VARCHAR(254), 
	col_10 NUMERIC(18,2), 
	col_11 VARCHAR(254), 
	col_13 NUMERIC(18,2), 
	col_16 NUMERIC(18,2), 
	col_18 NUMERIC(18,2), 
	col_20 NUMERIC(18,2), 
	col_22 NUMERIC(18,2), 
	col_24 VARCHAR(254), 
	[status] INT, 
	IRAZR INT, 
	NOTWORK INT, 
	LINK_KBK INT, 
	NUM_STAKE NUMERIC(6,3)
)

INSERT INTO #tmp0 (
	link_pay, way_calc, link_les, sys_0, sys_1, col_1, SUBDIV, kateg, col_2, col_3, col_4, col_5,col_7,
	col_8, col_9n, col_9, col_10, col_11, col_13, col_16, col_18, col_20, col_22, col_24, [status], IRAZR, NOTWORK, LINK_KBK, NUM_STAKE
)	
SELECT 
	pte.link_pay,
	pte.way_calc,
	pte.link_les,
	sys_0= te.link_empl,
	sys_1= pte.link_tar_empl,
	col_1= COALESCE((rtrim(ltrim(pers.fm)) + ' ' + rtrim(ltrim(IM)) + ' ' + rtrim(ltrim(OT))),''),
	SUBDIV = rtrim(ltrim(te.SUBDIV_NAME)),
	kateg = rtrim(ltrim(te.kateg_name)),
	col_2= (rtrim(ltrim(te.POST_NAME))),
	col_3= ISNULL((pkg_oklad),0),  --Размер базовой единицы, руб
	--Базовый коэффициент
	col_4=  CONVERT(NUMERIC(18,4),
				CASE WHEN ISNULL((pkg_oklad),0) > 0 THEN 
					ISNULL(CASE WHEN PTE.WAY_CALC = 8 THEN (CASE WHEN TE.NUM_STAKE <> 0 THEN PTE.SUMMA / TE.NUM_STAKE ELSE 0 END) ELSE 0 END,0) / ISNULL((pkg_oklad),0)
				ELSE 1 END
			),
	--	--Coalesce((KOEF),0),
	col_5= Convert(numeric(18,2), (Case when TE.NUM_STAKE <> 0 then pte.summa / TE.NUM_STAKE else 0 end)), --Здесь только оклыды
	col_7= 0, --Коэффициент управления (Ку)
	col_8= 0, --Коэффициент за работу на селе
	col_9n= TE.NUM_STAKE,
	col_9= LTRIM(RTRIM(convert(VARCHAR(6),TE.NUM_STAKE))) + SPACE(1) + CASE WHEN COALESCE(te.LINK_EMPL,0) = 0 THEN 'вакант.' ELSE (CASE [STATUS] WHEN 1 THEN 'осн.ст.' WHEN 2 THEN 'сов-во' WHEN 3 THEN 'вн.совм.' END) END,
	col_10= 0,
	col_11= Coalesce(
		(select top 1 LTRIM(RTRIM(COALESCE(KC.[CODE],''))) + ' ' + LTRIM(RTRIM(COALESCE(S.[NAME],''))) + case when [DATE] is not null then ' ' + CONVERT(varchar(10), [DATE], 104) else '' end 
			from dbo.EMPL_ATTEST EA LEFT JOIN dbo.PROFESSIONAL_SKILL S ON S.LINK = EA.LINK_SKILL
					LEFT JOIN dbo.KV_CATEGORY KC ON KC.LINK = EA.LINK_KV_CATEG
			where EMPL_LINK = te.link_empl and @PeriodEnd between DATE_BEGIN and coalesce(DATE_END,@PeriodEnd))
		,''),
	col_13= 0, --Коэффициент квалификации (Ккв)
	col_16= 0, --Коэффициент ученой степени  (Куч)
	col_18= 0, --Коэффициент специфики работы  (Ксп)
	col_20= 0, --Коэффициент стажа работы  (Кст)
	col_22= 0, --Другие повышения
	col_24 = CASE WHEN COALESCE(te.link_empl,0) = 0 THEN 'вакант.' else case [status] when 1 then 'осн.ст.' when 2 then 'сов-во' when 3 then 'вн.совм.' end end,
	[status],
	IRAZR,
	TE.NOTWORK,
	LINK_KBK = ISNULL(pte.link_kbk,te.LINK_KBK),
	NUM_STAKE = TE.NUM_STAKE	
FROM	
	#STO_TAR_EMPL as te
	INNER JOIN #all_pays_tar_empl as pte on pte.link_tar_empl = te.link AND PTE.LINK_EMPL = TE.LINK_EMPL
	INNER JOIN DBO.WAY_CALC W ON W.TYPE = 1 AND W.CODE = PTE.WAY_CALC
	INNER JOIN #K K ON K.linkKBK = ISNULL(pte.link_kbk,te.LINK_KBK) --Для определенного списка КБК
	LEFT JOIN dbo.person as pers on te.pers_link = pers.link
WHERE
	--Для определенного списка нагрузок
	(pte.link_pay is null or pte.link_pay in ( SELECT linkPayWH FROM STO_TLIST_WHOURS WHERE linkTListHead = @linkTL ))
	and
	ISNULL(W.OKLAD,1) = 1

INSERT INTO #tmp0 (
	link_pay, way_calc, link_les, sys_0, sys_1, col_1, SUBDIV, kateg, col_2, col_3, col_4, col_5,col_7,
	col_8, col_9n, col_9, col_10, col_11, col_13, col_16, col_18, col_20, col_22, col_24, [status], IRAZR, NOTWORK, LINK_KBK, NUM_STAKE
)	
SELECT DISTINCT
	pte.link_pay,
	pte.way_calc,
	pte.link_les,
	sys_0,
	sys_1,
	col_1,
	SUBDIV,
	kateg,
	col_2,
	col_3,  --Размер базовой единицы, руб
	col_4,  --Размер базовой единицы, руб
	col_5= 0, --Здесь только оклыды
	col_7= Convert(numeric(18,2), (Case when TE.NUM_STAKE <> 0 then coalesce( (case when dbo.STO_COLUMN(pte.link_pay, 7, @linkForm) = 1 then pte.summa else 0 end),0) / TE.NUM_STAKE else 0 end)) ,
	col_8= Convert(numeric(18,2), (Case when TE.NUM_STAKE <> 0 then coalesce( (case when dbo.STO_COLUMN(pte.link_pay, 8, @linkForm) = 1 then pte.summa else 0 end),0) / TE.NUM_STAKE else 0 end)) ,
	col_9n,
	col_9,
	col_10= 0,
	col_11= Coalesce(
		(select top 1 LTRIM(RTRIM(COALESCE(KC.[CODE],''))) + ' ' + LTRIM(RTRIM(COALESCE(S.[NAME],''))) + case when [DATE] is not null then ' ' + CONVERT(varchar(10), [DATE], 104) else '' end 
			from dbo.EMPL_ATTEST EA LEFT JOIN dbo.PROFESSIONAL_SKILL S ON S.LINK = EA.LINK_SKILL
					LEFT JOIN dbo.KV_CATEGORY KC ON KC.LINK = EA.LINK_KV_CATEG
			where EMPL_LINK = te.sys_0 and @PeriodEnd between DATE_BEGIN and coalesce(DATE_END,@PeriodEnd))
		,''),
	col_13= ISNULL( (case when dbo.STO_COLUMN(pte.link_pay, 13, @linkForm) = 1 then pte.summa else 0.0 end),0.0), --Коэффициент квалификации (Ккв)
	col_16= ISNULL( (case when dbo.STO_COLUMN(pte.link_pay, 16, @linkForm) = 1 then pte.summa else 0.0 end),0.0), --Коэффициент ученой степени  (Куч)
	col_18= ISNULL( (case when dbo.STO_COLUMN(pte.link_pay, 18, @linkForm) = 1 then pte.summa else 0.0 end),0.0), --Коэффициент специфики работы  (Ксп)
	col_20= ISNULL( (case when dbo.STO_COLUMN(pte.link_pay, 20, @linkForm) = 1 then pte.summa else 0.0 end),0.0), --Коэффициент стажа работы  (Кст)
	col_22= ISNULL( (case when dbo.STO_COLUMN(pte.link_pay, 22, @linkForm) = 1 then pte.summa else 0.0 end),0.0), --Другие повышения
	col_24,
	[status],
	IRAZR,
	TE.NOTWORK,
	pte.link_kbk,
	NUM_STAKE
FROM	
	#tmp0 as te 
	INNER JOIN #all_pays_tar_empl as pte on pte.link_tar_empl = te.sys_1 AND PTE.LINK_EMPL = TE.sys_0 AND PTE.link_kbk = TE.link_kbk
	INNER JOIN DBO.WAY_CALC W ON W.TYPE = 1 AND W.CODE = PTE.WAY_CALC 
	
WHERE
	ISNULL(W.OKLAD,1) = 0

--------------------------------------------
SELECT ID_Num = IDENTITY(int, 1, 1), * into #tmp FROM #tmp0
----------------------------------------------

SELECT 
	sys_0,
	sys_1,
	col_1, -- ФИО
	SUBDIV,
	kateg,
	col_2, -- Должность
	col_3,  --Размер базовой единицы, руб
	col_4,  --Размер базовой единицы, руб
	col_5= sum(col_5), --Здесь только оклыды
	col_7= sum(col_5), --Коэффициент управления (Ку) сумма оклада
	col_8= sum(col_5), --Размер базового оклада для специалиста на селе  сумма оклада
	col_9n, --TE.NUM_STAKE,	
	col_9, --TE.NUM_STAKE,
	col_10= 0,
	col_11,
	col_13, --Коэффициент квалификации (Ккв)
	col_16, --Коэффициент ученой степени  (Куч)
	col_18, --Коэффициент специфики работы  (Ксп)
	col_20, --Коэффициент стажа работы  (Кст)
	col_22, --Другие повышения
	col_24,
	[status],
	IRAZR,
	NOTWORK,
	NUM_STAKE
INTO #TMP1	
FROM 
	#tmp A LEFT JOIN DBO.WAY_CALC W ON W.TYPE = 1 AND W.CODE = A.WAY_CALC
WHERE	
	ISNULL(W.OKLAD,1) = 1
group by
	sys_0, sys_1, col_1, SUBDIV, kateg, col_2, col_3, col_4, col_9n, col_9, col_11, col_13, col_16, col_18, col_20, col_22, col_24, [status], IRAZR, NOTWORK, NUM_STAKE
UNION ALL
SELECT 
	sys_0,
	sys_1,
	col_1, -- ФИО
	SUBDIV,
	kateg,
	col_2, -- Должность
	col_3,  --Размер базовой единицы, руб
	col_4,  --Базовый коэффи- циент
	col_5, --Здесь только оклыды
	col_7 = SUM(col_7), --Коэффициент управления (Ку) Сумма надбавки
	col_8 = SUM(col_8), --Размер базового оклада для специалиста на селе  Сумма надбавки
	col_9n,
	col_9,
	col_10 = 0,
	col_11,
	col_13= sum(col_13), --Коэффициент квалификации (Ккв)
	col_16= sum(col_16), --Коэффициент ученой степени  (Куч)
	col_18= sum(col_18), --Коэффициент специфики работы  (Ксп)
	col_20= sum(col_20), --Коэффициент стажа работы  (Кст)
	col_22= sum(col_22), --Другие повышения
	col_24,
	[status],
	IRAZR,
	NOTWORK,
	NUM_STAKE
FROM #tmp A LEFT JOIN DBO.WAY_CALC W ON W.TYPE = 1 AND W.CODE = A.WAY_CALC
WHERE	
	ISNULL(W.OKLAD,1) = 0
group by
	sys_0, sys_1, col_1, SUBDIV, kateg, col_2, col_3, col_4, col_5, col_9n, col_9, col_11, col_24,[status], IRAZR, NOTWORK, NUM_STAKE

----- печть пустой формы
INSERT INTO #tmp1 
	(sys_0, sys_1, col_1, SUBDIV, kateg, col_2, col_3, col_4, col_5, col_7, col_8, col_9n, col_9, col_10, col_11, col_13, col_16, col_18, col_20, col_22, col_24, [status], IRAZR, NOTWORK, NUM_STAKE) 
SELECT 
		0, 0, '', '', '', '', 0, 0, 0, 0, 0, 0, '', 0, '', 0, 0, 0, 0, 0, '', 1,  0, 0, 0
WHERE 
	NOT EXISTS (SELECT * FROM #tmp1)

EXEC X_GET_TABLE_NAME @BUFF_ID OUTPUT

SET @SQL_SCRIPT = 
'
INSERT INTO DBO.BUFFER (ID, LINK)
SELECT DISTINCT ''' + @BUFF_ID + ''', E.link_empl 
FROM #STO_TAR_EMPL E INNER JOIN dbo.STO_ADD_PAYMENT AP ON E.link_empl = AP.LINK_EMPL
WHERE AP.mode = 2 
'
EXEC (@SQL_SCRIPT)
	
CREATE TABLE #SA_TarEmpl_PercAddStage(LINK_TAREMPL INT, LINK_EMPL INT, LINK_KATEG INT, STAGE NUMERIC(5,2), PERC NUMERIC(5,2), EXPIR_LINK INT, MAX_PERC NUMERIC(5,2), MAX_EXPIR_LINK INT)
INSERT INTO #SA_TarEmpl_PercAddStage(LINK_TAREMPL, LINK_EMPL, LINK_KATEG, STAGE, PERC, EXPIR_LINK, MAX_PERC, MAX_EXPIR_LINK)
SELECT LINK_TAREMPL, LINK_EMPL, LINK_KATEG, STAGE, PERC, EXPIR_LINK, MAX_PERC, MAX_EXPIR_LINK
FROM dbo.SA_TarEmpl_PercAddStage(@PeriodBegin, DEFAULT, DEFAULT, @BUFF_ID, @DEP_LINK, DEFAULT)

EXEC( 'DELETE FROM DBO.BUFFER WHERE ID = ''' +  @BUFF_ID + '''')

--Информация о стаже на дату печати списка
create table #stage (link_tarEmpl int, link_empl int, link_kateg int, stage VARCHAR(20), perc NUMERIC(18,2), expir_link int, max_perc NUMERIC(18,2))
insert into #stage (link_tarEmpl, link_empl, link_kateg, stage, perc, expir_link, max_perc)
SELECT distinct 
	ST.link_tarEmpl, ST.link_empl, ST.link_kateg, 
	stage = convert(VARCHAR(5),convert(int,ST.stage)) + 'г.' + convert(VARCHAR(10),convert(int,round((ST.stage - convert(int,ST.stage)) * 12, 0))) + 'м.', 
	ST.perc, ST.expir_link, ST.max_perc 
FROM 
	dbo.STO_ADD_PAYMENT AP
	INNER JOIN #SA_TarEmpl_PercAddStage ST ON ST.LINK_TAREMPL = ap.link_tar_empl AND ST.LINK_EMPL = AP.LINK_EMPL 
WHERE
	AP.mode = 2
	AND
	max_perc > 0
	AND
	(ST.perc = ST.max_perc AND AP.link_expir IS NULL OR ST.expir_link = AP.link_expir)
order by 
	link_tarEmpl

DROP TABLE #SA_TarEmpl_PercAddStage
	
---------------------------------------------------
EXEC X_GET_TABLE_NAME @BUFF_ID OUTPUT

SET @SQL_SCRIPT = 
'
INSERT INTO DBO.BUFFER (ID, LINK)
SELECT DISTINCT ''' + @BUFF_ID + ''', E.link_empl 
FROM #STO_TAR_EMPL E INNER JOIN dbo.STO_ADD_PAYMENT AP ON E.link_empl = AP.LINK_EMPL
WHERE AP.mode = 2  AND E.link_empl NOT IN (SELECT link_empl FROM #stage)
'
EXEC (@SQL_SCRIPT)

-- инф. о стаже на конец периода списка
CREATE TABLE #SA_TarEmpl_PercAddStage2(LINK_TAREMPL INT, LINK_EMPL INT, LINK_KATEG INT, STAGE NUMERIC(5,2), PERC NUMERIC(5,2), EXPIR_LINK INT, MAX_PERC NUMERIC(5,2), MAX_EXPIR_LINK INT)
INSERT INTO #SA_TarEmpl_PercAddStage2(LINK_TAREMPL, LINK_EMPL, LINK_KATEG, STAGE, PERC, EXPIR_LINK, MAX_PERC, MAX_EXPIR_LINK)
SELECT LINK_TAREMPL, LINK_EMPL, LINK_KATEG, STAGE, PERC, EXPIR_LINK, MAX_PERC, MAX_EXPIR_LINK
FROM dbo.SA_TarEmpl_PercAddStage(@PeriodEnd, DEFAULT, DEFAULT, @BUFF_ID, @DEP_LINK, DEFAULT)

EXEC( 'DELETE FROM DBO.BUFFER WHERE ID = ''' +  @BUFF_ID + '''')

--Информация о стаже для тех, у кого не было надбавки за стаж на дату начала, но будет на дату окончания
create table #stage2 (link_tarEmpl int, link_empl int, link_kateg int, stage VARCHAR(20), perc NUMERIC(18,2), expir_link int, max_perc NUMERIC(18,2))
insert into #stage2 (link_tarEmpl, link_empl, link_kateg, stage, perc, expir_link, max_perc)
SELECT distinct 
	ST.link_tarEmpl, ST.link_empl, ST.link_kateg, 
	stage = convert(VARCHAR(5),convert(int,ST.stage)) + 'г.' + convert(VARCHAR(10),convert(int,round((ST.stage - convert(int,ST.stage)) * 12, 0))) + 'м.', 
	ST.perc, ST.expir_link, ST.max_perc 
FROM 
	dbo.STO_ADD_PAYMENT AP
	INNER JOIN #SA_TarEmpl_PercAddStage2 ST ON ST.LINK_TAREMPL = ap.link_tar_empl AND ST.LINK_EMPL = AP.LINK_EMPL 
WHERE
	AP.mode = 2
	AND
	max_perc > 0	
	AND
	(ST.perc = ST.max_perc AND AP.link_expir IS NULL OR ST.expir_link = AP.link_expir)
order by 
	link_tarEmpl

DROP TABLE #SA_TarEmpl_PercAddStage2


-- Две строки со стажем
SELECT 
	link_empl = sys_0,
	link_tar_empl = sys_1,
	date_new_ap_stazh = dbo.SA_TarEmpl_GetDateChangePercStazh(sys_0,@PeriodBegin, @PeriodEnd, st.expir_link),
	st.expir_link
into #st_info
FROM 
	(SELECT distinct sys_0, sys_1 FROM #tmp1) T
	INNER JOIN #stage ST on ST.link_tarEmpl = sys_1 AND ST.LINK_EMPL = SYS_0
	
-- Две строки со стажем для тех, у кого не было надбавки за стаж на дату начала, но будет на дату окончания
insert into #st_info (link_empl, link_tar_empl, date_new_ap_stazh, expir_link)
SELECT 
	link_empl = sys_0,
	link_tar_empl = sys_1,
	date_new_ap_stazh = dbo.SA_TarEmpl_GetDateChangePercStazh(sys_0,@PeriodBegin, @PeriodEnd, st.expir_link),
	st.expir_link
FROM 
	(SELECT distinct sys_0, sys_1 FROM #tmp1) T
	INNER JOIN #stage2 ST on ST.link_tarEmpl = sys_1 AND ST.LINK_EMPL = SYS_0	
where not exists (select * from #st_info i where i.link_empl = sys_0 and i.link_tar_empl = sys_1)


--
SELECT  
	i.link_empl,
	i.link_tar_empl,
	date_new_ap_stazh,
	new_calc_perc = dbo.SA_TarEmpl_GetPercAddStage(i.link_empl, i.link_tar_empl, date_new_ap_stazh,expir_link, @DEP_LINK)
into #st_info2
FROM 
	#st_info i
WHERE	
	i.date_new_ap_stazh is not null

---
declare @TL_NAME VARCHAR(254)
SET @TL_NAME = ISNULL( (SELECT TOP 1 name FROM sto_tlist_head WHERE link = @linkTL),'')

----- Вывод результата
SELECT 
	TL_Name= @TL_NAME,
	period = convert(VARCHAR(10),@PeriodBegin,104),
	sys_0,
	sys_1,
	col_1, -- ФИО
	SUBDIV = UPPER(COALESCE(SUBDIV,'')), kateg = LOWER(COALESCE(kateg,'')),
	col_2, -- Должность
	col_3, -- Размер базовой единицы
	col_4, -- Базовый коэффициент
	col_5 = SUM(col_5), -- Размер базового оклада,  руб. (гр.3хгр.4)
	col_6 = CASE WHEN SUM(col_5) > 0 THEN SUM(col_7) / SUM(col_5) ELSE 0 END, -- Коэффициент управления (Ку), Коэффициент
	col_7 = SUM(col_7), -- Коэффициент управления (Ку), Размер базового оклада в зависимости от коэффициента управления, руб. гр.5 + (гр5 * гр.6)
	col_8 = SUM(col_8), --Размер базового оклада для специалиста на селе, руб. гр7+ (гр.7* 0,25)
	col_9n,
	col_9, --Объем работы по данной должности (1,0; 0,75; 0,5; 0,25) с указанием вида работы (основная, совместительство),
	col_10 = (SUM(col_8) * NUM_STAKE), --Размер базового оклада  с учетом объема работы, руб.  гр.8 * гр. 9
	col_11, -- Наличие квалификационной категории, ученой степени (указать) № приказа, специальность
	col_12 = dbo.sa_round((CASE WHEN (SUM(col_8) * NUM_STAKE) > 0 THEN SUM(col_13) /  (SUM(col_8) * NUM_STAKE) ELSE 0 END), 0.0001,2), --Коэффициент квалификации (Ккв), Коэффициент
	col_13 = SUM(col_13),--Коэффициент квалификации (Ккв)
	col_14 = SPACE(100), --Наличие почетного звания (указать наименование)
	col_15 = dbo.sa_round(( CASE WHEN (SUM(col_8) * NUM_STAKE) > 0 THEN SUM(col_16) / (SUM(col_8) * NUM_STAKE) ELSE 0 END), 0.0001,2), --Коэффициент ученой степени  (Куч), Коэффициент
	col_16 = SUM(col_16), -- Коэффициент ученой степени  (Куч), Размер базового оклада с учетом  с коэф. Ученой степени (Ккв) руб.,(гр 10 *гр.15)
	col_17 = dbo.sa_round(( CASE WHEN ((SUM(col_8) * NUM_STAKE)) > 0 THEN SUM(col_18) / ((SUM(col_8) * NUM_STAKE)) ELSE 0 END), 0.0001,2), --Коэффициент специфики работы  (Ксп), Коэффициент
	col_18 = SUM(col_18), --  Коэффициент специфики работы  (Ксп), Размер базового оклада с учетом   коэф. специфики (Ксп) руб.,(гр 10)*гр17
	col_19 = dbo.sa_round(( CASE WHEN (SUM(col_8) * NUM_STAKE) > 0 THEN SUM(col_20) / (SUM(col_8) * NUM_STAKE) ELSE 0 END), 0.0001,2), --Коэффициент стажа работы  (Кст), Коэффициент
	col_20 = SUM(col_20), --Коэффициент стажа работы  (Кст), Размер повышения базовой ставки в соответствии с коэффициентом стажа работы, руб. (гр.10*гр.19)
	col_21 = dbo.sa_round(( CASE WHEN (SUM(col_8) * NUM_STAKE) > 0 THEN SUM(col_22) / (SUM(col_8) * NUM_STAKE) ELSE 0 END), 0.0001,2), -- Другие повышения, Коэффициент
	col_22 = SUM(col_22), -- Другие повышения, Размер повышения базовой ставки в соответствии с коэффициентом повышения, руб. (гр.10*гр.22)
	col_23 = (SUM(col_8) * NUM_STAKE) + SUM(col_13) + SUM(col_16) + SUM(col_18) + SUM(col_20) + SUM(col_22), --- Итого (гр10 + гр.13+ гр.16+ гр.18+гр.20+ гр.22)
	col_24 = 
		(	-- либо у кого меняется стаж
			CASE WHEN i.LINK_TAR_EMPL IS NOT NULL THEN 'изм.стаж' ELSE
				-- либо кто временно не работает,
				CASE WHEN NOTWORK > 0 THEN 'врем.не раб.' ELSE
					CASE WHEN @VNS=3 and [status] = 3 THEN 'внеш.совм' ELSE
						LTRIM(RTRIM(col_24)) + SPACE(1)+ coalesce(st.stage,COALESCE(dbo.sa_empl_nepr_stage( sys_0, @PeriodBegin),''))
					END
				END
			END
		),				
	MARK = --Выделяем тех, кто временно не работает, 
		(CASE WHEN 
			i.LINK_TAR_EMPL IS NOT NULL -- либо у кого меняется стаж
			OR NOTWORK > 0 -- либо кто временно не работает,
			OR @VNS=3 and [status] = 3 --либо если внешнего совместителя включают в список, но не включают в итоги
		THEN 1 ELSE 0 END),
	[summar] = --Выделяем тех, кто временно не работает, 
		(CASE WHEN 
			i.LINK_TAR_EMPL IS NOT NULL -- либо у кого меняется стаж
			OR NOTWORK > 0 -- либо кто временно не работает,
			OR @VNS=3 and [status] = 3 --либо если внешнего совместителя включают в список, но не включают в итоги
		THEN 0 ELSE 1 END),		
	--[summar] = CASE WHEN coalesce(i.link_tar_empl,0) > 0 or @VNS=3 and [status] = 3 THEN 0 ELSE 1 END,
	irazr,
	NUM_STAKE
INTO
	#RES
FROM 
	#tmp1 T LEFT JOIN dbo.sa_ets_actual(@PeriodBegin) AS ets18 on ets18.link = NUM_STAKE AND ets18.razr = 18
	LEFT JOIN #stage as St on St.link_tarEmpl = sys_1 AND ST.LINK_EMPL = SYS_0
	LEFT JOIN #st_info2 i on i.link_empl = t.sys_0 and i.link_tar_empl = t.sys_1
group by
	sys_0, sys_1, i.link_tar_empl, col_1, SUBDIV, kateg, col_2, col_3, col_4, col_9n, col_9, col_11, col_24, st.stage, [status], irazr, NOTWORK, NUM_STAKE
union all
SELECT 
	TL_Name= @TL_NAME,
	period = convert(VARCHAR(10),@PeriodBegin,104),
	sys_0,
	sys_1,
	col_1, -- ФИО
	SUBDIV = UPPER(COALESCE(SUBDIV,'')), kateg = LOWER(COALESCE(kateg,'')),
	col_2, -- Должность
	col_3, -- Размер базовой единицы
	col_4, -- Базовый коэффициент
	col_5 = SUM(col_5), -- Размер базового оклада,  руб. (гр.3хгр.4)
	col_6 = CONVERT(NUMERIC(18,4), CASE WHEN SUM(col_5) > 0 THEN (SUM(col_7) + SUM(col_5)) / SUM(col_5) ELSE 0 END), -- Коэффициент управления (Ку), Коэффициент
	col_7 = SUM(col_7), -- Коэффициент управления (Ку), Размер базового оклада в зависимости от коэффициента управления, руб. гр.5 + (гр5 * гр.6)
	col_8 = SUM(col_8), --Размер базового оклада для специалиста на селе, руб. гр7+ (гр.7* 0,25)
	col_9n,
	col_9, --Объем работы по данной должности (1,0; 0,75; 0,5; 0,25) с указанием вида работы (основная, совместительство),
	col_10 = (SUM(col_8) * NUM_STAKE), --Размер базового оклада  с учетом объема работы, руб.  гр.8 * гр. 9
	col_11, -- Наличие квалификационной категории, ученой степени (указать) № приказа, специальность
	col_12 = dbo.sa_round(( CASE WHEN (SUM(col_8) * NUM_STAKE) > 0 THEN CONVERT(NUMERIC(18,8),SUM(col_13)) /  CONVERT(NUMERIC(18,8),(SUM(col_8) * NUM_STAKE)) ELSE 0 END), 0.0001,2), --Коэффициент квалификации (Ккв), Коэффициент
	col_13 = SUM(col_13),--Коэффициент квалификации (Ккв)
	col_14 = '', --Наличие почетного звания (указать наименование)
	col_15 = dbo.sa_round(( CASE WHEN (SUM(col_8) * NUM_STAKE) > 0 THEN SUM(col_16) / (SUM(col_8) * NUM_STAKE) ELSE 0 END), 0.0001,2), --Коэффициент ученой степени  (Куч), Коэффициент
	col_16 = SUM(col_16), -- Коэффициент ученой степени  (Куч), Размер базового оклада с учетом  с коэф. Ученой степени (Ккв) руб.,(гр 10 *гр.15)
	col_17 = dbo.sa_round(( CASE WHEN ((SUM(col_8) * NUM_STAKE)) > 0 THEN SUM(col_18) / ((SUM(col_8) * NUM_STAKE)) ELSE 0 END), 0.0001,2), --Коэффициент специфики работы  (Ксп), Коэффициент
	col_18 = SUM(col_18), --  Коэффициент специфики работы  (Ксп), Размер базового оклада с учетом   коэф. специфики (Ксп) руб.,(гр 10)*гр17
	col_19 = new_calc_perc, --Коэффициент стажа работы  (Кст), Коэффициент
	col_20 = convert(numeric(18,2), (SUM(col_8) * NUM_STAKE) * new_calc_perc), --Коэффициент стажа работы  (Кст), Размер повышения базовой ставки в соответствии с коэффициентом стажа работы, руб. (гр.10*гр.19)
	col_21 = dbo.sa_round(( CASE WHEN (SUM(col_8) * NUM_STAKE) > 0 THEN SUM(col_22) / (SUM(col_8) * NUM_STAKE) ELSE 0 END), 0.0001,2), -- Другие повышения, Коэффициент
	col_22 = SUM(col_22), -- Другие повышения, Размер повышения базовой ставки в соответствии с коэффициентом повышения, руб. (гр.10*гр.22)
	col_23 = (SUM(col_8) * NUM_STAKE) + SUM(col_13) + SUM(col_16) + SUM(col_18) + SUM(col_20) + SUM(col_22), --- Итого (гр10 + гр.13+ гр.16+ гр.18+гр.20+ гр.22)
	col_24 = ltrim(rtrim(col_24)) + SPACE(1) + convert(varchar(10),date_new_ap_stazh,104),
	MARK = 0,
	[summar] = CASE WHEN @VNS=3 and [status] = 3 THEN 0 ELSE 1 END,		
	irazr,
	NUM_STAKE
FROM 
	#tmp1 T INNER JOIN #st_info2 i on i.link_empl = t.sys_0
	LEFT JOIN dbo.sa_ets_actual(@PeriodBegin) AS ets18 on ets18.link = NUM_STAKE AND ets18.razr = 18
	LEFT JOIN #stage as St on St.link_tarEmpl = sys_1 AND ST.LINK_EMPL = SYS_0
WHERE
	NOTWORK = 0	
group by
	sys_0, sys_1, i.link_tar_empl, col_1, SUBDIV, kateg, col_2, col_3, col_4, col_9n, col_9, col_11, col_16, col_24,  st.stage, [status], date_new_ap_stazh, new_calc_perc, NOTWORK, irazr, NUM_STAKE
order by
	SUBDIV, kateg asc, irazr desc, sys_0, sys_1 asc

SET NOCOUNT OFF

---
IF @SVOD = 0
	SELECT * FROM #RES order by  SUBDIV, kateg asc, (CASE WHEN sys_0 = 0 THEN 1 ELSE 0 END), irazr desc, col_1, sys_1 asc, MARK desc

IF @SVOD = 1 BEGIN

	SELECT SUB = SUBDIV, A = 'A', ST = SUM(NUM_STAKE), S = SUM(COL_23)--, CNT_STAKE = SUM(COL_12), OKLAD_ETS = SUM(COL_13), ADD_VRED = SUM(COL_15), ADD_STAGE = SUM(COL_21), ITOGO = SUM(COL_22)
	INTO #RES1	
	FROM #RES
	WHERE summar = 1
	group by SUBDIV
	order by SUBDIV

	DECLARE @TABLE1 VARCHAR(100), @TABLE2 VARCHAR(100), @TABLE3 VARCHAR(100), @TABLE4 VARCHAR(100), @TABLE5 VARCHAR(100)
	EXEC X_GET_TABLE_NAME @TABLE1 OUTPUT
	SELECT @TABLE2 = @TABLE1+'2', @TABLE3 = @TABLE1 + '3', @TABLE4 = @TABLE1 + '4', @TABLE5 = @TABLE1 + '5'

	SELECT SUBDIV,KATEG, OKLAD = SUM(COL_10), VRED = SUM(COL_18), STAGE = SUM(COL_20), ITOG = SUM(COL_23)
	INTO #RES2	
	FROM #RES
	WHERE summar = 1
	group by SUBDIV,KATEG
	order by SUBDIV,KATEG

	SELECT SUBDIV,KAT = KATEG,CNT = SUM(NUM_STAKE)
	INTO #RES3	
	FROM #RES
	WHERE summar = 1
	group by SUBDIV,KATEG
	order by SUBDIV,KATEG

	EXEC M_CROSS_TABLE
		'SUBDIV', 
		'KAT', 'VARCHAR(254)', 
		'CNT', 'NUMERIC(20,2)', 'SUM(CNT) AS CNT',
		'#RES3', @TABLE1

	EXEC M_CROSS_TABLE
		'SUBDIV', 
		'KATEG', 'VARCHAR(254)', 
		'OKLAD', 'NUMERIC(20,2)', 'SUM(OKLAD) AS OKLAD',
		'#RES2', @TABLE2

	EXEC M_CROSS_TABLE
		'SUBDIV', 
		'KATEG', 'VARCHAR(254)', 
		'VRED', 'NUMERIC(20,2)', 'SUM(VRED) AS VRED',
		'#RES2', @TABLE3

	EXEC M_CROSS_TABLE
		'SUBDIV', 
		'KATEG', 'VARCHAR(254)', 
		'STAGE', 'NUMERIC(20,2)', 'SUM(STAGE) AS STAGE',
		'#RES2', @TABLE4

	EXEC M_CROSS_TABLE
		'SUBDIV', 
		'KATEG', 'VARCHAR(254)', 
		'ITOG', 'NUMERIC(20,2)', 'SUM(ITOG) AS ITOG',
		'#RES2', @TABLE5

	EXEC (' SELECT R0.SUB, R0.ST, R0.S, R1.*, R2.*, R3.*, R4.*, R5.* FROM #RES1 R0
			LEFT JOIN ' + @TABLE1 + ' R1 ON R1.SUBDIV = R0.SUB
			LEFT JOIN ' + @TABLE2 + ' R2 ON R2.SUBDIV = R0.SUB
			LEFT JOIN ' + @TABLE3 + ' R3 ON R3.SUBDIV = R0.SUB
			LEFT JOIN ' + @TABLE4 + ' R4 ON R4.SUBDIV = R0.SUB
			LEFT JOIN ' + @TABLE5 + ' R5 ON R5.SUBDIV = R0.SUB
	')

END

return 0

GO


GRANT EXECUTE ON dbo.[STS_LIST_M0901] TO PUBLIC

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_SET_STATIC_NASTR]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SET_STATIC_NASTR]

GO

CREATE  PROCEDURE DBO.SA_SET_STATIC_NASTR @CODE VARCHAR(20)
AS
---ЗАРПЛАТА-КС: ОБНОВЛЕНИЕ СТАВОК
BEGIN

	DECLARE @TITLE VARCHAR(254)
	SET @TITLE = 'Установлены статические настройки Зарплата-КС'

	DECLARE	@TD_LINK INT

	DELETE FROM DBO.SAL_WORNINGS WHERE TASK = 'SALARY' AND SID = SUSER_SID()

	IF @CODE = '2012' BEGIN

		SET @TITLE = @TITLE + ' на 01 ЯНВАРЯ 2012г.'

		--Мин. размер пособия по уходу за 1 ребенком
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT1', 0, '2326.00'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Мин. размер пособия по уходу за 1 ребенком = 2326.00', '', 'SALARY'


		--Мин. размер пособия по уходу за 2 и более дет.          
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT2', 0, '4651.99'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Мин. размер пособия по уходу за 2 и более дет. = 4651.99', '', 'SALARY'


		--Макс. размер пособия по уходу за 1 ребенком                                                                                                              
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT3', 0, '14625.32'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Макс. размер пособия по уходу за 1 ребенком = 9303.99', '', 'SALARY'


		--Макс.  размер пособия по уходу за 2 и более дет.                                                                                                                                                                 
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT4', 0, '14625.32'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Макс.  размер пособия по уходу за 2 и более дет. = 9303.99', '', 'SALARY'


		--Предельный размер пособия по нетрудоспособности                                                                                                                                                                
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT1', 0, '42666.66'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Предельный размер пособия по нетрудоспособности = 42666.66', '', 'SALARY'

		--Максимальный размер пособия по беременности и родам                                                                                                                                                             
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT6', 0, '42666.66'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Максимальный размер пособия по беременности и родам = 42666.66', '', 'SALARY'
		
		--Предельный размер пособия по нетрудоспособности в минувшем году                                                                                                                                                        
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT7', 0, '38583.33'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Предельный размер пособия по нетрудоспособности в минувшем году = 38583.33', '', 'SALARY'

		--Максимальный размер пособия по беременности и родам в минувшем году                                                                                                                                                      
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT8', 0, '38583.33'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Максимальный размер пособия по беременности и родам в минувшем году = 38583.33', '', 'SALARY'		

		-- УДАЛЕНИЕ ВСЕХ ПРАЗДНИКОВ 
		DELETE	FROM HOLIDAYS

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE WORK_D = 11)
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРАЗДНИЧНЫХ ДНЕЙ
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL)
			SELECT	'1 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 1, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'2 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 2, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'3 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 3, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'4 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 4, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'5 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 5, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'7 ЯНВАРЯ (РОЖДЕСТВО ХРИСТОВО)', 7, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'23 ФЕВРАЛЯ (ДЕНЬ ЗАЩИТНИКА ОТЕЧЕСТВА)', 23, 2, @TD_LINK, 1
			UNION ALL
			SELECT	'8 МАРТА (МЕЖДУНАРОДНЫЙ ЖЕНСКИЙ ДЕНЬ)', 8, 3, @TD_LINK, 1
			UNION ALL
			SELECT	'1 МАЯ (ПРАЗДНИК ВЕСНЫ И ТРУДА)', 1, 5, @TD_LINK, 1
			UNION ALL
			SELECT	'9 МАЯ (ДЕНЬ ПОБЕДЫ)', 9, 5, @TD_LINK, 1
			UNION ALL
			SELECT	'12 ИЮНЯ (ДЕНЬ РОССИИ)', 12, 6, @TD_LINK, 1
			UNION ALL
			SELECT	'4 НОЯБРЯ (ДЕНЬ НАРОДНОГО ЕДИНСТВА)', 4, 11, @TD_LINK, 1

		SET @TITLE = 'Установлены праздничные дни'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 1 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРЕДПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB = 'П')
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРЕДПРАЗДНИЧНЫХ ДНЕЙ ГОД
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'22 ФЕВРАЛЯ', 22, 2, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'7 МАРТА', 7, 3, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'28 АПРЕЛЯ (предпраздничный день за 30 апреля)', 28, 4, @TD_LINK, 2, 30, 4
			UNION ALL
			SELECT	'9 ИЮНЯ (предпраздничный день за 11 июня)', 9, 6, @TD_LINK, 2, 11, 6
			UNION ALL
			SELECT	'29 ДЕКАБРЯ (предпраздничный день за 31 декабря)', 29, 12, @TD_LINK, 2, 31, 12
			UNION ALL
			SELECT	'12 МАЯ (предпраздничный день за 8 мая)', 12, 5, @TD_LINK, 2, 8, 5

		SET @TITLE = 'Установлены предпраздничные дни'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 2 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE WORK_D = 11)
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ ДОПОЛНИТЕЛЬНЫХ ДНЕЙ ОТДЫХА ГОД
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'6 ЯНВАРЯ (перенос выходного с 1 января)', 6, 1, @TD_LINK, 3, 1, 1
			UNION ALL
			SELECT	'9 ЯНВАРЯ (перенос выходного с 7 января)', 9, 1, @TD_LINK, 3, 7, 1
			UNION ALL
			SELECT	'9 МАРТА (перенос выходного с 11 марта)', 9, 3, @TD_LINK, 3, 11, 3
			UNION ALL
			SELECT	'30 АПРЕЛЯ (перенос выходного с 28 апреля)', 30, 4, @TD_LINK, 3, 28, 4			
			UNION ALL
			SELECT	'7 МАЯ (перенос выходного с 5 мая)', 7, 5, @TD_LINK, 3, 5, 5			
			UNION ALL
			SELECT	'8 МАЯ (перенос выходного с 12 мая)', 8, 5, @TD_LINK, 3, 12, 5			
			UNION ALL			
			SELECT	'11 ИЮНЯ (перенос выходного с 9 июня)', 11, 6, @TD_LINK, 3, 9, 6									
			UNION ALL
			SELECT	'5 НОЯБРЯ (перенос выходного с 4 ноября)', 5, 11, @TD_LINK, 3, 4, 11
			UNION ALL
			SELECT	'31 ДЕКАБРЯ (перенос выходного с 29 декабря)', 31, 12, @TD_LINK, 3, 29, 12			

		SET @TITLE = 'Установлены дополнительные дни отдыха (перенос выходных)'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 3 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА РАБОЧИЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB IN ('Я','Ф'))
		IF COALESCE(@TD_LINK,0) > 0
		BEGIN
			-- ДОБАВЛЕНИЕ ПЕРЕНЕСЁННЫХ РАБОЧИХ ДНЕЙ
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'11 МАРТА (рабочий день за 9 марта)', 11, 3, @TD_LINK, 3, 9, 3

			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'5 МАЯ (рабочий день за 7 мая)', 5, 5, @TD_LINK, 3, 7, 5

		END
		
		SET @TITLE = 'Установлены переносы рабочих дней'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, '11 МАРТА (рабочий день за 9 марта)', '', 'SALARY'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, '28 АПРЕЛЯ (рабочий день за 30 апреля)', '', 'SALARY'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, '5 МАЯ (рабочий день за 7 мая)', '', 'SALARY'

	END --IF @CODE = '2012' BEGIN	

	IF @CODE = '2013' BEGIN

		SET @TITLE = @TITLE + ' на 01 ЯНВАРЯ 2013г.'

		--Мин. размер пособия по уходу за 1 ребенком
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT1', 0, '2453.93'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Мин. размер пособия по уходу за 1 ребенком = 2453.93', '', 'SALARY'


		--Мин. размер пособия по уходу за 2 и более дет.          
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT2', 0, '4907.85'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Мин. размер пособия по уходу за 2 и более дет. = 4907.85', '', 'SALARY'


		--Макс. размер пособия по уходу за 1 ребенком                                                                                                              
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT3', 0, '15429.71'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Макс. размер пособия по уходу за 1 ребенком = 15429.71', '', 'SALARY'


		--Макс.  размер пособия по уходу за 2 и более дет.                                                                                                                                                                 
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT4', 0, '15429.71'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Макс.  размер пособия по уходу за 2 и более дет. = 15429.71', '', 'SALARY'


		----Предельный размер пособия по нетрудоспособности                                                                                                                                                                
		--EXEC dbo.X_SET_OPTION 'ARCHE_OPT1', 0, '42666.66'

		--INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		--SELECT @TITLE, 'Предельный размер пособия по нетрудоспособности = 42666.66', '', 'SALARY'

		----Максимальный размер пособия по беременности и родам                                                                                                                                                             
		--EXEC dbo.X_SET_OPTION 'ARCHE_OPT6', 0, '42666.66'

		--INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		--SELECT @TITLE, 'Максимальный размер пособия по беременности и родам = 42666.66', '', 'SALARY'
		
		----Предельный размер пособия по нетрудоспособности в минувшем году                                                                                                                                                        
		--EXEC dbo.X_SET_OPTION 'ARCHE_OPT7', 0, '38583.33'

		--INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		--SELECT @TITLE, 'Предельный размер пособия по нетрудоспособности в минувшем году = 38583.33', '', 'SALARY'

		----Максимальный размер пособия по беременности и родам в минувшем году                                                                                                                                                      
		--EXEC dbo.X_SET_OPTION 'ARCHE_OPT8', 0, '38583.33'

		--INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		--SELECT @TITLE, 'Максимальный размер пособия по беременности и родам в минувшем году = 38583.33', '', 'SALARY'		

		-- УДАЛЕНИЕ ВСЕХ ПРАЗДНИКОВ 
		DELETE	FROM HOLIDAYS

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE WORK_D = 11)
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРАЗДНИЧНЫХ ДНЕЙ
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL)
			SELECT	'1 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 1, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'2 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 2, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'3 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 3, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'4 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 4, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'5 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 5, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'6 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 6, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'7 ЯНВАРЯ (РОЖДЕСТВО ХРИСТОВО)', 7, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'8 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 8, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'23 ФЕВРАЛЯ (ДЕНЬ ЗАЩИТНИКА ОТЕЧЕСТВА)', 23, 2, @TD_LINK, 1
			UNION ALL
			SELECT	'8 МАРТА (МЕЖДУНАРОДНЫЙ ЖЕНСКИЙ ДЕНЬ)', 8, 3, @TD_LINK, 1
			UNION ALL
			SELECT	'1 МАЯ (ПРАЗДНИК ВЕСНЫ И ТРУДА)', 1, 5, @TD_LINK, 1
			UNION ALL
			SELECT	'9 МАЯ (ДЕНЬ ПОБЕДЫ)', 9, 5, @TD_LINK, 1
			UNION ALL
			SELECT	'12 ИЮНЯ (ДЕНЬ РОССИИ)', 12, 6, @TD_LINK, 1
			UNION ALL
			SELECT	'4 НОЯБРЯ (ДЕНЬ НАРОДНОГО ЕДИНСТВА)', 4, 11, @TD_LINK, 1

		SET @TITLE = 'Установлены праздничные дни'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 1 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРЕДПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB = 'П')
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРЕДПРАЗДНИЧНЫХ ДНЕЙ ГОД
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'22 ФЕВРАЛЯ', 22, 2, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'7 МАРТА', 7, 3, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'30 АПРЕЛЯ', 30, 4, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'8 МАЯ', 8, 5, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'11 ИЮНЯ', 11, 6, @TD_LINK, 2, null, null
			UNION ALL
			SELECT	'31 ДЕКАБРЯ', 31, 12, @TD_LINK, 2, null, null
		SET @TITLE = 'Установлены предпраздничные дни'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 2 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE WORK_D = 11)
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ ДОПОЛНИТЕЛЬНЫХ ДНЕЙ ОТДЫХА ГОД
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'2 МАЯ (перенос выходного с 5 января)', 2, 5, @TD_LINK, 3, 5, 1
			UNION ALL
			SELECT	'3 МАЯ (перенос выходного с 6 января)', 3, 5, @TD_LINK, 3, 6, 1			
			UNION ALL
			SELECT	'10 МАЯ (перенос выходного с 25 февраля)', 10, 5, @TD_LINK, 3, 25, 2			

		SET @TITLE = 'Установлены дополнительные дни отдыха (перенос выходных)'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 3 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА РАБОЧИЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB IN ('Я','Ф'))
		IF COALESCE(@TD_LINK,0) > 0
		BEGIN
			-- ДОБАВЛЕНИЕ ПЕРЕНЕСЁННЫХ РАБОЧИХ ДНЕЙ
			/*	INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
				SELECT	'11 МАРТА (рабочий день за 9 марта)', 11, 3, @TD_LINK, 3, 9, 3

				INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
				SELECT	'5 МАЯ (рабочий день за 7 мая)', 5, 5, @TD_LINK, 3, 7, 5
			*/
			/*перенесенных рабочих дней за 2013 год нет */
		
		
			SET @TITLE = 'Установлены переносы рабочих дней'

			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			SELECT @TITLE, 'перенесенных рабочих дней за 2013 год нет', '', 'SALARY'
		end
	END --IF @CODE = '2013' BEGIN	

	IF @CODE = '2014' BEGIN

		SET @TITLE = @TITLE + ' на 01 ЯНВАРЯ 2014г.'

		--Мин. размер пособия по уходу за 1 ребенком
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT1', 0, '2576.63'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Мин. размер пособия по уходу за 1 ребенком = 2576.63', '', 'SALARY'


		--Мин. размер пособия по уходу за 2 и более дет.          
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT2', 0, '5153.24'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Мин. размер пособия по уходу за 2 и более дет. = 5153.24', '', 'SALARY'


		--Макс. размер пособия по уходу за 1 ребенком                                                                                                              
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT3', 0, '17990.11'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Макс. размер пособия по уходу за 1 ребенком = 17990.11', '', 'SALARY'

		--Макс.  размер пособия по уходу за 2 и более дет.                                                                                                                                                                 
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT4', 0, '17990.11'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Макс.  размер пособия по уходу за 2 и более дет. = 17990.11', '', 'SALARY'


		----Предельный размер пособия по нетрудоспособности                                                                                                                                                                
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT1', 0, '52000.00'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Предельный размер пособия по нетрудоспособности = 52000.00', '', 'SALARY'

		--Максимальный размер пособия по беременности и родам                                                                                                                                                             
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT6', 0, '52000.00'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Максимальный размер пособия по беременности и родам = 52000.00', '', 'SALARY'
		
		--Предельный размер пособия по нетрудоспособности в минувшем году                                                                                                                                                        
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT7', 0, '47333.33'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Предельный размер пособия по нетрудоспособности в минувшем году = 47333.33', '', 'SALARY'

		--Максимальный размер пособия по беременности и родам в минувшем году                                                                                                                                                      
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT8', 0, '47333.33'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Максимальный размер пособия по беременности и родам в минувшем году = 47333.33', '', 'SALARY'		
		
		--Среднемесячное  число календарных дней
		EXEC dbo.X_SET_OPTION 'FURLOUGH_OPT4','0','29.30'
		
		-- УДАЛЕНИЕ ВСЕХ ПРАЗДНИКОВ 
		DELETE	FROM HOLIDAYS

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE WORK_D = 11)
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРАЗДНИЧНЫХ ДНЕЙ
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL)
			SELECT	'1 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 1, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'2 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 2, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'3 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 3, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'4 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 4, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'5 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 5, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'6 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 6, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'7 ЯНВАРЯ (РОЖДЕСТВО ХРИСТОВО)', 7, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'8 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 8, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'23 ФЕВРАЛЯ (ДЕНЬ ЗАЩИТНИКА ОТЕЧЕСТВА)', 23, 2, @TD_LINK, 1
			UNION ALL
			SELECT	'8 МАРТА (МЕЖДУНАРОДНЫЙ ЖЕНСКИЙ ДЕНЬ)', 8, 3, @TD_LINK, 1
			UNION ALL
			SELECT	'1 МАЯ (ПРАЗДНИК ВЕСНЫ И ТРУДА)', 1, 5, @TD_LINK, 1
			UNION ALL
			SELECT	'9 МАЯ (ДЕНЬ ПОБЕДЫ)', 9, 5, @TD_LINK, 1
			UNION ALL
			SELECT	'12 ИЮНЯ (ДЕНЬ РОССИИ)', 12, 6, @TD_LINK, 1
			UNION ALL
			SELECT	'4 НОЯБРЯ (ДЕНЬ НАРОДНОГО ЕДИНСТВА)', 4, 11, @TD_LINK, 1

		SET @TITLE = 'Установлены праздничные дни'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 1 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРЕДПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB = 'П')
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРЕДПРАЗДНИЧНЫХ ДНЕЙ ГОД
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'7 МАРТА', 7, 3, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'30 АПРЕЛЯ', 30, 4, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'8 МАЯ', 8, 5, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'11 ИЮНЯ', 11, 6, @TD_LINK, 2, null, null
			UNION ALL
			SELECT	'31 ДЕКАБРЯ', 31, 12, @TD_LINK, 2, null, NULL
			UNION ALL
			SELECT	'24 ФЕВРАЛЯ', 24, 2, @TD_LINK, 2,null, NULL

		SET @TITLE = 'Установлены предпраздничные дни'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 2 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE WORK_D = 11)
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ ДОПОЛНИТЕЛЬНЫХ ДНЕЙ ОТДЫХА ГОД
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'10 МАРТА (перенос выходного с 8 марта)', 10, 3, @TD_LINK, 3, 8, 3
			UNION ALL
			SELECT	'2 МАЯ (перенос выходного с 4 января)', 2, 5, @TD_LINK, 3, 4, 1
			UNION ALL
			SELECT	'13 ИЮНЯ (перенос выходного с 5 января)', 13, 6, @TD_LINK, 3, 5, 1
			UNION ALL
			SELECT	'3 НОЯБРЯ (перенос выходного с 24 февраля)', 3, 11, @TD_LINK, 3, 24, 2			

		SET @TITLE = 'Установлены дополнительные дни отдыха (перенос выходных)'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 3 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА РАБОЧИЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB IN ('Я','Ф'))
		IF COALESCE(@TD_LINK,0) > 0
		BEGIN
			-- ДОБАВЛЕНИЕ ПЕРЕНЕСЁННЫХ РАБОЧИХ ДНЕЙ
			/*	INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
				SELECT	'11 МАРТА (рабочий день за 9 марта)', 11, 3, @TD_LINK, 3, 9, 3

				INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
				SELECT	'5 МАЯ (рабочий день за 7 мая)', 5, 5, @TD_LINK, 3, 7, 5
			*/
			/*перенесенных рабочих дней за 2014 год нет */
		
		
			SET @TITLE = 'Установлены переносы рабочих дней'

			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			SELECT @TITLE, 'перенесенных рабочих дней за 2014 год нет', '', 'SALARY'
		end
	END --IF @CODE = '2014' BEGIN				

END



GO


GRANT EXECUTE ON dbo.[SA_SET_STATIC_NASTR] TO PUBLIC

GO



GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_U_PERC_CALC]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_U_PERC_CALC]

GO

CREATE   PROCEDURE dbo.SA_U_PERC_CALC (@LINK_DOC INT)
AS

DECLARE
	@varKSRefPay 	int,
	@varKSdDate1	datetime,
	@varKSdDate2	datetime,		 
	@varKSLinkVKR	int,
	@nRound tinyint,
	@nTrunc tinyint,
	@varKSnMonth int,
	@varKSnYear int

select 
	@varKSnMonth = month(DATE),
	@varKSnYear = year(DATE)
from 
	dbo.sdoc
where 
	LINK = @LINK_DOC

select 
	@varKSRefPay = LINK_PAY, 
	@varKSLinkVKR = LINK_VKR,
	@varKSdDate1 = DATE1,
	@varKSdDate2 = DATE2,
	@nRound = nRound,
	@nTrunc  = nTrunc
from 
	dbo.SDOC_TPER
where 
	LINK_UP = @LINK_DOC

----
DELETE FROM dbo.SDOC_TPER_TABLE2 WHERE LINK_UP = @LINK_DOC

----
INSERT INTO dbo.SDOC_TPER_TABLE2 (LINK_UP, ORDERS, LINK_EMPL, LINK_PAY,  LINK_SFIN, SUMMA)
SELECT
	@LINK_DOC,
	1, 	
	E.LINK_EMPL,
	CJ.LINK_PAYS,
	CJ.LINK_VKR,
	SUM(CJ.SUMMA)
FROM 
	dbo.CALCULATE_JURNAL CJ 
	INNER JOIN dbo.group_tax(@varKSRefPay) T ON CJ.LINK_PAYS=T.TAX_LINK
	INNER JOIN dbo.SDOC_TPER_TABLE E ON E.LINK_EMPL = CJ.LINK_EMPL AND (COALESCE(E.LINK_SFIN,0) <> 0 AND CJ.LINK_VKR = E.LINK_SFIN OR COALESCE(E.LINK_SFIN,0) = 0)
WHERE
	E.LINK_UP = @LINK_DOC 
	AND CJ.PERIOD_BEGIN>=@varKSdDate1 AND CJ.PERIOD_END<=@varKSdDate2
GROUP BY  
	E.LINK_EMPL, CJ.LINK_PAYS, CJ.LINK_VKR
order by
	E.LINK_EMPL, CJ.LINK_PAYS

--Нумерация
declare @LINK_EMPL int, @num int
select @LINK_EMPL = 0, @num = 1
update dbo.SDOC_TPER_TABLE2
Set 
	@num = case when LINK_EMPL = @LINK_EMPL then @num + 1 else 1 end,
	@LINK_EMPL = LINK_EMPL,
	orders = @num
from
	dbo.SDOC_TPER_TABLE2
where
	LINK_UP = @LINK_DOC

---
DECLARE @PART NUMERIC(18,2)
SET @PART = (CASE @nRound 
				WHEN 1 THEN 0 --Не округлять
				WHEN 2 THEN 0.10 --Округлять до 10 копеек				
				WHEN 3 THEN 1 --Округлять до 1 рубля
				WHEN 4 THEN 5 --Округлять до 5 рублей
				WHEN 5 THEN 10 --Округлять до 10 рублей
				WHEN 6 THEN 50 --Округлять до 50 рублей
				WHEN 7 THEN 100 --Округлять до 100 рублей
				WHEN 8 THEN 1000 --Округлять до 1000 рублей
				WHEN 9 THEN 10000 --Округлять до 10000 рублей
				ELSE 0 --Не округлять
			END)

UPDATE dbo.SDOC_TPER_TABLE
SET 
	SUMMA_BASE = COALESCE(B.SUMMA_BASE,0),
	SUMMA_ALL = COALESCE((B.SUMMA_BASE * PERC) / 100,0),
	SUMMA_UDER = COALESCE(U.SUMMA,0),
	SUMMA = dbo.SA_ROUND( COALESCE((B.SUMMA_BASE * PERC) / 100,0) - COALESCE(U.SUMMA,0) ,@PART ,@nTrunc) 
FROM 
	dbo.SDOC_TPER_TABLE A INNER JOIN --Список сотрудников
	(
		SELECT 
			T.LINK_EMPL,
			SUMMA_BASE = SUM(T2.SUMMA)
		FROM 
			dbo.SDOC_TPER_TABLE T
			INNER JOIN dbo.SDOC_TPER_TABLE2 T2 ON T.LINK_UP = T2.LINK_UP AND T.LINK_EMPL = T2.LINK_EMPL
		WHERE 
			T.LINK_UP = @LINK_DOC
		GROUP BY
			T.LINK_EMPL
	) B ON A.LINK_EMPL = B.LINK_EMPL --База расчета
	LEFT JOIN 
	(
		SELECT E.LINK_EMPL, SUMMA = SUM(CJ.SUMMA)
		FROM 
			dbo.CALCULATE_JURNAL CJ 
			INNER JOIN dbo.SDOC_TPER_TABLE E ON E.LINK_EMPL = CJ.LINK_EMPL AND (COALESCE(E.LINK_SFIN,0) <> 0 AND CJ.LINK_VKR = E.LINK_SFIN OR COALESCE(E.LINK_SFIN,0) = 0)
		WHERE 
			E.LINK_UP = @LINK_DOC AND CJ.LINK_PAYS = @varKSRefPay AND MONTH(CJ.PERIOD_BEGIN) = @varKSnMonth AND YEAR(CJ.PERIOD_BEGIN) =@varKSnYear
		GROUP BY  E.LINK_EMPL
	) U ON A.LINK_EMPL  =U.LINK_EMPL --Уже удержано
WHERE
	LINK_UP = @LINK_DOC

GO


GRANT EXECUTE ON dbo.[SA_U_PERC_CALC] TO PUBLIC

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_U_VEDOM_DGH_SUM]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_U_VEDOM_DGH_SUM]

GO


CREATE   PROCEDURE [dbo].SD_U_VEDOM_DGH_SUM
	@varKSSumma numeric(15,2) output,
	@varKSnTypPay int =1,   
	@varKSnLinkEmpl int,
	@varKSdDate1 datetime	= 0,
	@varKSdDate2 datetime	= 0,
	@varKSLinkVKR INT, 
	@varKSLinkEKR int,
	@LINK_DEP INT
AS
SELECT @varKSSumma = SUM(SUMMA) 
FROM 
	dbo.CALCULATE_JURNAL J
	INNER JOIN dbo.PAYS P ON J.LINK_PAYS = P.LINK
WHERE 
	J.LINK_DEP = @LINK_DEP
	AND LINK_EMPL IS NULL 
	AND PERS_LINK = @varKSnLinkEmpl 
	AND P.[OBJECT] = @varKSnTypPay 
	AND PERIOD_BEGIN >= @varKSdDate1 
	AND PERIOD_END <= @varKSdDate2 
	AND SUMMA <> 0 
	and LINK_VKR = @varKSLinkVKR 
	and (COALESCE(J.LINK_EKR,P.LINK_EKR) = @varKSLinkEKR OR isnull(@varKSLinkEKR,0) = 0)

SELECT 
	[REF_PAY] = J.LINK_PAYS, 
	[NAME_PAY] = P.NAME,
	[CODE_PAY] = P.CODE,
	[SUMMA]  = SUM(J.SUMMA),
	[WAY]	 = P.[OBJECT],
	LINK_EKR = COALESCE(J.LINK_EKR,P.LINK_EKR),
	CODE_EKR = EKR.CODE
FROM
	dbo.CALCULATE_JURNAL J
	INNER JOIN dbo.PAYS P ON J.LINK_PAYS = P.LINK 
	LEFT JOIN dbo.KOSGU EKR ON COALESCE(J.LINK_EKR,P.LINK_EKR) = EKR.LINK 
WHERE 
	J.LINK_DEP = @LINK_DEP
	AND J.LINK_EMPL IS NULL 
	AND J.PERS_LINK = @varKSnLinkEmpl 
	AND P.[OBJECT] =@varKSnTypPay 
	AND J.SUMMA<>0  
	AND J.PERIOD_BEGIN>=@varKSdDate1 
	and J.PERIOD_END<=@varKSdDate2 
	and J.LINK_VKR=@varKSLinkVKR 
	AND (COALESCE(J.LINK_EKR,P.LINK_EKR) = @varKSLinkEKR OR isnull(@varKSLinkEKR,0) = 0)
GROUP BY 
	J.LINK_PAYS, P.NAME, P.CODE, P.[OBJECT], COALESCE(J.LINK_EKR,P.LINK_EKR), EKR.CODE

GO

GRANT EXECUTE ON dbo.[SD_U_VEDOM_DGH_SUM] TO PUBLIC
GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_U_VEDOM_DGH_SUM_ALL]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_U_VEDOM_DGH_SUM_ALL]

GO

CREATE  PROCEDURE [dbo].SD_U_VEDOM_DGH_SUM_ALL
	@varKSSumma numeric(18,2) OUTPUT,
	@varKSnMonth int,
	@varKSnYear int,
	@varKSlinkEmpl int,		
	@varKSLinkVKR int,
	@varKSLinkEKR INT,
	@varKSnMonth1 int = 0,
	@LINK_DEP INT	
AS

SET @varKSSumma = COALESCE((
	SELECT 
		SUM( COALESCE(SUMMA,0) * CASE WHEN P.[OBJECT] = 1 THEN 1 ELSE -1 END ) AS SUMMA 
	FROM 
		dbo.CALCULATE_JURNAL J
		INNER JOIN dbo.PAYS P ON J.LINK_PAYS = P.LINK
	WHERE 
		J.LINK_DEP = @LINK_DEP
		AND LINK_EMPL IS NULL 
		AND PERS_LINK = @varKSlinkEmpl  
		AND MONTH(J.[PERIOD_BEGIN]) in (@varKSnMonth,@varKSnMonth1) 
		AND YEAR(J.[PERIOD_BEGIN]) = @varKSnYear 
		AND J.LINK_VKR = @varKSLinkVKR 
		AND (COALESCE(J.LINK_EKR,P.LINK_EKR) = @varKSLinkEKR OR isnull(@varKSLinkEKR,0) = 0)
		AND P.[OBJECT] IN (1,2)
),0)

RETURN 0




GO


GRANT EXECUTE ON dbo.[SD_U_VEDOM_DGH_SUM_ALL] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_U_VEDOM_DGH_PROV]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_U_VEDOM_DGH_PROV]

GO

CREATE PROCEDURE dbo.SD_U_VEDOM_DGH_PROV
@varKSparLINK int
AS

IF (SELECT SO.CODE FROM S_OBJECTS SO,SDOC DOC WHERE DOC.LINK = @varKSparLINK AND
		 DOC.OBJECT = SO.LINK) <> 'DOCUMENTS_DED_PAYROLL_DGH'
	RETURN 5

IF EXISTS (SELECT * FROM DBO.CALCULATE_JURNAL WHERE LINK_DOC = @varKSparLINK)
BEGIN
		RAISERROR('Документ уже проведен!', 11, 1)
		RETURN 0
END	

Declare @varKStrancount int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN


EXEC dbo.SALARY_SDOC_FLAG_JC @varKSparLINK,0


DECLARE @LinkEKR226 int
SET @LinkEKR226 = COALESCE((SELECT TOP 1 LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '226'),0)

IF OBJECT_ID('TEMPDB..#TMP','U') IS NOT NULL
	DROP TABLE #TMP
	
CREATE TABLE #TMP (LINK INT, ORDERS INT, PERS_LINK INT, LINK_EKR INT, DISBURS NUMERIC(18,2))


IF EXISTS (SELECT * FROM dbo.SDOC_VEDOM_DGH_TABLE1 WHERE LINK_UP = @varKSparLINK AND LINK_EKR IS NULL)
--Для формирования операций по старым расчетам, где в таблице не было ЭКР
	/*Заготовка*/
	INSERT INTO #TMP (LINK, ORDERS, PERS_LINK, LINK_EKR, DISBURS) 
	SELECT 
		D.LINK, T1.ORDERS, T1.PERS_LINK, T.LINK_EKR,
		T1.DISBURS 
			* (CASE WHEN 
					COALESCE(SUM(case when T.TYP_PAY = 1 then T.summa else -T.summa end),0) <> 0 
				THEN 
					COALESCE(SUM(case when T.TYP_PAY = 1 then T.summa else -T.summa end),0) 
				ELSE 1 END)
			/ (CASE WHEN 
					COALESCE(R.SUMMA,0) <> 0 
				THEN 
					COALESCE(R.SUMMA,0) 
				ELSE 1 END) as DISBURS
	FROM 
		dbo.DOCUMENTS_DED_PR_DGH D 
		INNER JOIN dbo.DOCUMENTS_DED_PR_TABLE_DGH T1 ON D.LINK = T1.LINK 
		INNER JOIN 
		(
		SELECT DD.LINK, TT1.PERS_LINK, ISNULL(SUM(CASE WHEN TT.TYP_PAY = 1 then TT.SUMMA ELSE -TT.SUMMA END),0) as SUMMA
		FROM 
			dbo.DOCUMENTS_DED_PR_DGH DD 
			INNER JOIN dbo.DOCUMENTS_DED_PR_TABLE_DGH TT1 ON DD.LINK = TT1.LINK 
			left JOIN dbo.DOCUMENTS_DED_PR_DGH_TABLE2 TT ON TT1.LINK = TT.LINK AND TT1.PERS_LINK = TT.PERS_LINK
		WHERE 
			DD.LINK = @varKSparLINK 
		GROUP BY 
			DD.LINK, TT1.PERS_LINK 
		) R ON T1.LINK = R.LINK AND T1.PERS_LINK = R.PERS_LINK
		left JOIN dbo.DOCUMENTS_DED_PR_DGH_TABLE2 T ON T1.LINK = T.LINK AND T1.PERS_LINK = T.PERS_LINK	
	where 
		D.LINK = @varKSparLINK 
	GROUP BY 
		D.LINK, T1.ORDERS, T1.PERS_LINK, t.LINK_EKR, T1.DISBURS, R.SUMMA
ELSE
	--Когда в таблице появился ЭКР, то вычислять пропорции больше не нужно
	INSERT INTO #TMP (LINK, ORDERS, PERS_LINK, LINK_EKR, DISBURS) 
	SELECT 
		LINK_UP, ORDERS, PERS_LINK, LINK_EKR, DISBURS 
	FROM 
		dbo.SDOC_VEDOM_DGH_TABLE1		
	WHERE
		LINK_UP = @varKSparLINK	

---
DECLARE @VEDOM_OPTIONS_OPT11 TINYINT
SET @VEDOM_OPTIONS_OPT11 = dbo.SA_GET_OPTION_BY_CODE('VEDOM_OPTIONS_OPT11')

INSERT INTO dbo.CALCULATE_JURNAL 
	(
		LINK_EMPL,LINK_PAYS,LINK_DOC,PERIOD_BEGIN,PERIOD_END,DAYS,HOURS,SUMMA_BASE,SUMMA,ORDERS,DATE_BEGIN,DATE_END,LINK_DEP,LINK_ORG,PERS_LINK,LINK_VKR,LINK_EKR
	)
SELECT 
	[LINK_EMPL] = NULL,
	[LINK_PAYS] = SD.LINK_PAY,
	[LINK_DOC] = S.LINK,
	[PERIOD_BEGIN] = CASE WHEN @VEDOM_OPTIONS_OPT11 = 1 THEN dbo.DateBeginOfMonth(S.DATE_CALC) ELSE dbo.DateBeginOfMonth(S.[DATE]) END,	
	[PERIOD_END] = CASE WHEN @VEDOM_OPTIONS_OPT11 = 1 THEN dbo.DateEndOfMonth(S.DATE_CALC) ELSE dbo.DateEndOfMonth(S.[DATE]) END,	
	[DAYS] = 0,
	[HOURS] = 0,
	[SUMMA_BASE] = 0,
	[SUMMA] = TAB.DISBURS,
	[ORDERS] = TAB.ORDERS,
	[DATE_BEGIN] =dbo.DateBeginOfMonth(S.DATE_CALC),
	[DATE_END] = dbo.DateEndOfMonth(S.DATE_CALC),
	[LINK_DEP] = S.LINK_DEP,
	[LINK_ORG] = NULL,
	[PERS_LINK]	= TAB.PERS_LINK, 
	[LINK_VKR] = SD.LINK_VKR,
	COALESCE(TAB.LINK_EKR,COALESCE(SD.LINK_EKR,@LinkEKR226))
FROM 
	dbo.SDOC S 
	INNER JOIN dbo.SDOC_VEDOM_DGH SD ON S.LINK = SD.LINK_UP
	INNER JOIN #TMP TAB ON S.LINK = TAB.LINK
	LEFT JOIN dbo.PAYS P ON P.LINK = SD.LINK_PAY	
WHERE 
	S.LINK = @varKSparLINK 
	AND TAB.DISBURS<>0

EXEC dbo.SALARY_SDOC_FLAG_JC @varKSparLINK,1


IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0








GO


GRANT EXECUTE ON dbo.[SD_U_VEDOM_DGH_PROV] TO PUBLIC

GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FB_RESULT_FINANS_DOP_TABLE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FB_RESULT_FINANS_DOP_TABLE]
GO






CREATE        PROCEDURE FB_RESULT_FINANS_DOP_TABLE
	@varKSiLink	int,
	@varKSiYear	int,
	@varKSiPer_num	tinyint,
	@varKSdDate	datetime, 
	@varKSiDep_Acc	int
	
AS

DECLARE	@varKSintLimPer	tinyint,
		@varKSintSummaType	tinyint,
		@varKSintPerMnoj	numeric(8,3),
		@varKSiMonthNum1	tinyint,
		@varKSiMonthNum2	tinyint,
		@varKSiMonthNum3	tinyint,
		@iDep int

SELECT @varKSintSummaType = UM FROM FINANS_LIMIT_OPTIONS
SELECT @varKSintLimPer = max(FIN_LIM_PER) + 10 * max(FIN_LIM_TYPE) FROM WORKMODE 
select @varKSintPerMnoj = (case (@varKSiPer_num - FLOOR(@varKSiPer_num/3)*3) WHEN 1 THEN P1
										WHEN 2 THEN P2
										WHEN 0 THEN P3
										ELSE 0 END) / 100
FROM FB_RESULT_FINANS_OPTIONS


--select @iDEP = dep from g_prov where link = @varKSiLink 
select @iDEP = LINK_UP from DEPARTMENT_ACCOUNTS where link = @varKSiDep_Acc 

IF NOT (@varKSintLimPer = 2 OR @varKSintLimPer = 12)
	RETURN 0

SELECT FH.ACCOUNT, FH.PER_NUM, F.vkr, F.ekr, F.dop_cl, (F.p1 + F.p2 + F.p3 + F.p4 + F.p5 + F.p6 + F.p7 + F.p8 + F.p9 + F.p10  + F.p11 + F.p12) * @varKSintSummaType as summa
INTO #tFIN
from finanse F
inner join G_Prov GP on  F.link_up = GP.link
inner join dbo.s_objects SO on GP.object = SO.LINK
inner join FINANSE_HEAD FH on FH.LINK = GP.LINK 
where	GP.DEP = @iDEP 
		and GP.DATE_PROV is not null  
		and GP.DATE_PROV <= @varKSdDate
		and not GP.LINK = @varKSiLink
		and	FH.FYEAR = @varKSiYear
		and SO.CODE = 'FB_RESULT_FINANS'

SELECT ACCOUNT, vkr, ekr, dop_cl, summa = sum(summa)
INTO #tFIN_ALL
from #tFIN
group by ACCOUNT, vkr, ekr, dop_cl

SELECT ACCOUNT, vkr, ekr, dop_cl,  summa = sum(summa)
INTO #tFIN_M
from #tFIN 
where	PER_NUM = @varKSiPer_num
group by ACCOUNT, vkr, ekr, dop_cl

select ACCOUNT = DEP_ACC, vkr, ekr, dop_cl, summa =   
		P1 +  
		CASE WHEN @varKSiPer_num > 3 THEN   ISNULL(p4,0) else 0 end +  
		CASE WHEN @varKSiPer_num > 6 THEN   ISNULL(P7,0) else 0 end + 
		CASE WHEN @varKSiPer_num > 9 THEN ISNULL(P10,0) else 0 end
into #tLim
from dbo.FB_FINANS_POLUCH(@varKSiYear, null,@varKSdDate,@varKSiPer_num, @varKSintSummaType, 0,'FINANS_LIMIT', 2,'1')
where rbs_dep = @iDEP or rbs_dep is null and DEP = @iDep
		

create table #tAll_ROW (ACCOUNT int, VKR int, EKR int, DOP_CL int)
insert into #tAll_ROW
SELECT ACCOUNT, VKR, EKR, DOP_CL 
FROM #tFIN_ALL
union
SELECT ACCOUNT, VKR, EKR, DOP_CL 
FROM #tLim


--select * from #tAll_ROW
--select * from #tLim
--select * from #tFIN_ALL
--select * from #tFIN_M

			
Select 	[CHECKED] = 0,
	[ERROR] = 0,
	[UPD] = 0,
	[DEL] = 0,
	LINK = convert(int,0), 
	LINK_UP = convert(int,0),
	AR.VKR,
	AR.EKR,
	AR.DOP_CL,
	[PS1] = ISNULL(FM.summa,0),
	[PY1] = ISNULL(FSL.summa,0) - ISNULL(F.summa,0),
	[ITOGS] = ISNULL(F.summa,0),
	[ITOGY] = ISNULL(FSL.summa,0) - ISNULL(F.summa,0),
	[VKR_CODE] = VKR.CODE,
	[VKR_NAME] = VKR.NAME,
	[KBK_ADM]     = VKR.LINK_ADM,
	[EKR_CODE] = EKR.CODE,
	[EKR_NAME] = EKR.NAME,
	[DOP_CL_CODE] = DOP_CL.CODE,
	[DOP_CL_NAME] = DOP_CL.NAME,
	[P1]     = ISNULL(FSL.summa,0) * @varKSintPerMnoj 
From #tALL_ROW AR
LEFT OUTER JOIN #tLIM FSL
		ON (FSL.ACCOUNT = AR.ACCOUNT or (FSL.ACCOUNT IS NULL AND AR.ACCOUNT IS NULL)) AND 
			(FSL.vkr = AR.vkr or (FSL.vkr IS NULL AND AR.vkr IS NULL)) AND 
			(FSL.ekr = AR.ekr or (FSL.ekr IS NULL AND AR.ekr IS NULL)) AND 
			(FSL.DOP_CL = AR.DOP_CL or (FSL.DOP_CL IS NULL AND AR.DOP_CL IS NULL))
LEFT OUTER JOIN #tFIN_ALL F
		ON (F.ACCOUNT = AR.ACCOUNT or (F.ACCOUNT IS NULL AND AR.ACCOUNT IS NULL)) AND 
			(F.vkr = AR.vkr or (F.vkr IS NULL AND AR.vkr IS NULL)) AND 
			(F.ekr = AR.ekr or (F.ekr IS NULL AND AR.ekr IS NULL)) AND 
			(F.DOP_CL = AR.DOP_CL or (F.DOP_CL IS NULL AND AR.DOP_CL IS NULL))
LEFT OUTER JOIN #tFIN_M FM
		ON (FM.ACCOUNT = AR.ACCOUNT or (FM.ACCOUNT IS NULL AND AR.ACCOUNT IS NULL)) AND 
			(FM.vkr = AR.vkr or (FM.vkr IS NULL AND AR.vkr IS NULL)) AND 
			(FM.ekr = AR.ekr or (FM.ekr IS NULL AND AR.ekr IS NULL)) AND 
			(FM.DOP_CL = AR.DOP_CL or (FM.DOP_CL IS NULL AND AR.DOP_CL IS NULL))
LEFT OUTER JOIN dbo.KL_KBK VKR ON VKR.LINK = AR.VKR 
left outer JOIN dbo.DICTIONARY_ITEM EKR ON EKR.LINK = AR.EKR
left outer JOIN dbo.DOP_CLASSIF DOP_CL ON DOP_CL.LINK = AR.DOP_CL



RETURN 1




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_U_VEDOM_DGH_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_U_VEDOM_DGH_SAVE]

GO
/*
© Кейсистемс (Keysystems), 2005
*/
CREATE  PROCEDURE [dbo].SD_U_VEDOM_DGH_SAVE
	@varKSparLINK		int	OUTPUT,
	@varKSparNumber		varchar(15) = null,
	@varKSparDate		datetime = null,
	@varKSparDateS		datetime = null,
	@varKSparRefPay		int = null,
	@varKSparComments	varchar(100) = '',
	@varKSparFlag		tinyint	= 0,
	@varKSparNUM_PR		varchar(10),
	@varKSparNAME_PR	varchar(60),
	@varKSparSALDO		bit = 0,
	@varKSparNDFL		bit = 0,
	@varKSparTYP_PAYMENT	int = null,
	@varKSparTYP_ROUND	int = null,
	@varKSparTYPOKR		int = null,
	@varKSparSumma		numeric(15,2) = 0.0,	
	@varKSparREF_EMPL 	int = null,
	@varKSparVKR int,
	@varKSparEKR INT ,
	@varKSparCARD_LINK int,
	@LINK_DEP INT = NULL
AS

DECLARE @varKSERROR	tinyint,
		@varKSstrVALUE	varchar(7000),
		@varKStrancount	int,	@varKSsoLink int, @varKSRowCount int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN


IF @varKSparNumber IS NULL OR @varKSparNumber = '' or  @varKSparDate IS NULL  or @varKSparDateS IS NULL
BEGIN
	ROLLBACK
	RETURN 5
END

SELECT @varKSsoLink = LINK FROM s_objects  WHERE CODE = 'DOCUMENTS_DED_PAYROLL_DGH'

IF @varKSparEKR = 0
	SET @varKSparEKR = null

IF @varKSparREF_EMPL = 0
	SET @varKSparREF_EMPL = NULL

EXECUTE @varKSERROR = SALARY_UPD_SDOC @varKSparLINK OUTPUT, @varKSsoLink, @varKSparNumber,@varKSparDate,@varKSparComments,@varKSparFlag,@varKSparDateS,@varKSparSumma, @LINK_DEP
IF @varKSERROR <> 0
	RETURN @varKSERROR
	

IF not exists(select link_up from sdoc_vedom_dgh where link_up =@varKSparLINK)
	BEGIN
		
		INSERT INTO SDOC_VEDOM_DGH WITH (ROWLOCK) (LINK_UP,LINK_PAY,LINK_VKR,LINK_EKR, NUMBER_PR, NAME_PR,SALDO,NDFL,TYP_PAYMENT,REF_KASSIR,TYP_ROUND, TYPOKR, LINK_CARD) 
			VALUES (@varKSparLINK, @varKSparRefPay, @varKSparVKR, @varKSparEKR,@varKSparNUM_PR,@varKSparNAME_PR, @varKSparSALDO,@varKSparNDFL,@varKSparTYP_PAYMENT,@varKSparREF_EMPL,@varKSparTYP_ROUND, @varKSparTYPOKR, @varKSparCARD_LINK)
		SELECT @varKSERROR = @@ERROR
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
ELSE
	BEGIN
		UPDATE SDOC_VEDOM_DGH WITH (ROWLOCK) 
		SET 	LINK_PAY =@varKSparRefPay,
				LINK_VKR = @varKSparVKR,
				LINK_EKR = @varKSparEKR, 
				NUMBER_PR= @varKSparNUM_PR, 
				NAME_PR = @varKSparNAME_PR,
				SALDO	= @varKSparSALDO,
				NDFL = @varKSparNDFL,
				TYP_PAYMENT =@varKSparTYP_PAYMENT,
				REF_KASSIR = @varKSparREF_EMPL,
				TYP_ROUND =@varKSparTYP_ROUND,
				TYPOKR = @varKSparTYPOKR,
				LINK_CARD = @varKSparCARD_LINK
		WHERE LINK_UP=@varKSparLINK
		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END

DELETE FROM SDOC_VEDOM_DGH_TABLE1 WHERE LINK_UP = @varKSparLINK
DELETE FROM SDOC_VEDOM_DGH_TABLE2 WHERE LINK_UP = @varKSparLINK



declare @varKSEventText varchar(200)
SET @varKSEventText = 'Платежная ведомость (внештатные сотрудники) № ' + RTRIM(LTRIM(convert(varchar(10),@varKSparNumber))) + ' от ' + CONVERT(VARCHAR(10),@varKSparDate,104)
EXECUTE WF_GENERATEEVENT 'Сохранение документа', @varKSEventText, @varKSsoLink, 'SDOC',@varKSparLINK
WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN

RETURN 0






GO


GRANT EXECUTE ON dbo.[SD_U_VEDOM_DGH_SAVE] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[sa_vybor_dgh_ved]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[sa_vybor_dgh_ved]

GO


CREATE Procedure dbo.sa_vybor_dgh_ved (@period datetime, @LINK_DEP INT = NULL ) 
as
/*
Процедура отбирает за указанный период договора, за который не был сделан расчет
*/

declare @date_begin datetime, @date_end DATETIME, @avance_perc int

Set @date_begin = dbo.DateBeginOfMonth(@period)
Set @date_end = dbo.DateEndOfMonth(@period)

SELECT @LINK_DEP = COALESCE(@LINK_DEP,DEP_LINK) FROM USER_DEP

SET @avance_perc =  DBO.SA_GET_OPTION_BY_CODE('VEDOM_OPTIONS_AVANCE_SUM')


SELECT 
	CHECKED = 0,
	LINK_DOG= DOC.LINK, 
	NUM_DOG= DOC.NUMBER,
	DATE_DOG= convert(varchar(10),DOC.[DATE],104),
	PERS_LINK= DOC.PERS_LINK,
	FIO= DOC.FIO,
	DATE_BEGIN= convert(varchar(10),DOC.DATE1,104),
	DATE_END= convert(varchar(10),DOC.DATE2,104), 
	SUM_DOG= 0,
	COMM_DOG= DOC.COMMENT,
	PAYMENT= DOC.PAYMENT,
	AVANCE = 0 /*CASE WHEN @avance_perc = 0 and isnull(DOC.AVANCE,0) <> 0 then (isnull(DOC.SUMMA,0)* (convert( numeric (15,2), ISNULL(DOC.AVANCE,0))/100.00))
				  WHEN @avance_perc = 1 THEN isnull(DOC.AVANCE,0)
				  ELSE 0 END*/,
	LINK_KBK= DOC.LINK_KBK , 
	LINK_EKR = p.LINK_EKR,
	CODE_EKR = k.CODE
FROM 
	dbo.SALARY_REESTR_DGH DOC 
	INNER JOIN dbo.pays p ON p.link= DOC.link_pays
	LEFT JOIN dbo.KOSGU k ON k.LINK = p.LINK_EKR

WHERE  
	DOC.DEP_LINK = @LINK_DEP
	AND
	(DOC.DATE1 BETWEEN @date_begin AND @date_end 
	or DOC.DATE2 BETWEEN @date_begin AND @date_end
	or (DOC.DATE1 < @date_begin and DOC.DATE2 > @date_end)
	)  


Return 0


GRANT  ALL  ON [dbo].[sa_vybor_dgh_ved]  TO [public]




GO


GRANT EXECUTE ON dbo.[sa_vybor_dgh_ved] TO PUBLIC

GO


--Расширенные свойства--


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_4FSS_EXPORT_v05]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_4FSS_EXPORT_v05]

GO

/*EXEC dbo.BK_SELECT_EXPORT_FORMAT 2486*/
/*exec SA_4FSS_EXPORT_v05 2486*/
CREATE      PROCEDURE [dbo].SA_4FSS_EXPORT_v05 ( @Link int /*Ссылка на расчет*/ ) 
AS

CREATE TABLE #OUTPUT (ID int identity(1,1), F_NAME VARCHAR(254), OUT_TEXT TEXT)

SET NOCOUNT  ON

--Строка заголовка
CREATE TABLE #TASK_PROP (ID int identity(1,1), VAL VARCHAR (254))


INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MAJOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MINOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_FIX',1

declare @NAME_PROG varchar(254), @VERS_PROG VARCHAR(254)
Select @NAME_PROG = UPPER(RTRIM(LTRIM([NAME]))), 
	@VERS_PROG = (SELECT RTRIM(LTRIM(VAL)) FROM #TASK_PROP WHERE [ID] = 1)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 2)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 3)
from dbo.DICTIONARY_TASK where CODE = 'SALARY'
--------------------------------------------
-- Проставлять ОКАТО или ОКТМО по настройке
DECLARE @OKATO_OR_OKTMO int
SET @OKATO_OR_OKTMO = dbo.SA_GET_OPTION_BY_CODE('NASTR_USE_OKATO_OKTMO') 


DECLARE @LINK_DEP INT, @YEAR INT, @Version TINYINT, @Period_Number TINYINT, @LINK_FORM INT, 
		@Begin_Date DATETIME, @End_Date DATETIME, @modify_date DATETIME
SELECT 
	@LINK_DEP = LINK_ORGANIZATION, 
	@YEAR = YEAR(Begin_Date),
	@Version = [Version],
	@Period_Number = Period_Number,
	@LINK_FORM = LINK_FORM,
	@Begin_Date = dbo.DateBeginOfYear(Begin_Date),
	@End_Date = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,Period_Number*3,YEAR(Begin_Date))),
	@modify_date = modify_date
FROM dbo.REPORT_SAVED_FORMS 
WHERE LINK_SAVED_FORM = @link

DECLARE 
	@first_month_of_quarter TINYINT, 
	@second_month_of_quarter TINYINT, 
	@third_month_of_quarter TINYINT

IF @Period_Number = 1
	SELECT @first_month_of_quarter = 1, @second_month_of_quarter = 2, @third_month_of_quarter = 3
IF @Period_Number = 2
	SELECT @first_month_of_quarter = 4, @second_month_of_quarter = 5, @third_month_of_quarter = 6
IF @Period_Number = 3
	SELECT @first_month_of_quarter = 7, @second_month_of_quarter = 8, @third_month_of_quarter = 9
IF @Period_Number = 4
	SELECT @first_month_of_quarter = 10, @second_month_of_quarter = 11, @third_month_of_quarter = 12

SELECT  @first_month_of_quarter = ISNULL(@first_month_of_quarter,1), @second_month_of_quarter = ISNULL(@second_month_of_quarter,2), @third_month_of_quarter = ISNULL(@third_month_of_quarter,3)

SELECT top 1
	DD1.OKPO AS OKPO1, 
	DD1.INN AS INN1, DD1.KPP AS KPP1, 
	FULL_NAME = UPPER(DD1.FULL_NAME),
	UPPER(DD1.NAME) AS ORGNAME,
	DD2.NALOG AS IMNS_SONO, DD2.NAME AS IMNS_NAME, 
	DD2.NALOG AS SONO, 
	DD1.OGRN AS OGRN1,
	LTRIM(RTRIM(dbo.GetAddressBykladr(DD1.REF_LINK_A))) 
		+ CASE WHEN ISNULL(DD1.HOUSE, '') = '' THEN '' ELSE  ' ' + LTRIM(RTRIM(DD1.HOUSE)) END
		+ CASE WHEN ISNULL(DD1.FLAT, '') = '' THEN '' ELSE ' - ' + LTRIM(RTRIM(DD1.FLAT)) END
	AS ADDR_STR,
	CAST(NULL AS DATETIME) AS DATE_END,
	UPPER(RTRIM(CHIEF.FM) + ' ' + LEFT(CHIEF.IM, 1) + '. ' + LEFT(CHIEF.OT,1) + '.') AS CHIEF_FIO,
	RTRIM(CHIEF.PHONE) AS CH_PHONE,
	UPPER(RTRIM(GLBUH.FM) + ' ' + LEFT(GLBUH.IM, 1) + '. ' + LEFT(GLBUH.OT,1) + '.') AS GLBUH_FIO,
	RTRIM(GLBUH.PHONE) AS GL_PHONE,
	DD1.OGRN,
	DD1.OKATO,
	DD1.OKTMO,
	DD1.OKVED,
	DD1.OKPO,
	DD1.FSS_REG_NUM, --Регистрационный номер (код) страхователя ТФОМС
	DD1.FSS_KOD_P, --Код подчиненности - код, состоящий из пяти цифр, указывающий на территориальный орган Фонда, в котором страхователь зарегистрирован в текущий момент;	
	DD1.FSS_KOD_DOP, --Дополнительный код предусмотрен для обособленных подразделений организаций
	DD1.OKOPF, --- код Общероссийского классификатора организационно-правовых форм;
	DD1.OKFS, --- код Общероссийского классификатора форм собственности;
	DD1.PFNUMBER,
	DA.PINDEX, REGION = UPPER(DA.REGION), DA.REGCODE, RAION = UPPER(DA.RAION), GOROD = UPPER(DA.GOROD), 
	NASEL = UPPER(DA.NASEL), STREET = UPPER(DA.STREET), DA.HOUSE, DA.KORP, DA.FLAT,
	TFOMS_RNUM = DD1.TFOMS_REG_NUM,
	TFOMS_KT = DD1.TFOMS_KT,
	TaxType = DD1.FSS_KP_PC1,
	TaxType2 = DD1.FSS_KP_PC2,
	TaxType3 = DD1.FSS_KP_PC3
INTO #DEP_DATA	
FROM DICTIONARY_DEPARTMENT DD1 
	LEFT OUTER JOIN DICTIONARY_DEPARTMENT DD2 ON DD1.IMNS_LINK = DD2.LINK
	LEFT OUTER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Руководитель') chief on chief.link_dep = dd1.link
	LEFT OUTER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Главный бухгалтер') GLBUH ON GLBUH.link_dep = dd1.link
	LEFT JOIN DBO.DEP_ADRESS(@LINK_DEP) DA ON 1=1
WHERE DD1.LINK = @LINK_DEP

DECLARE @NumDotC VARCHAR(2), @NumDot INT
SELECT @NumDotC = ISNULL(dbo.RN_GET_ATR_VALUE(@LINK, 'REPORTS_ATR_NOM_OBR'),'00')
SET @NumDot = CASE WHEN ISNUMERIC(@NumDotC) =1 THEN CONVERT(INT,@NumDotC) ELSE 0 END

DECLARE @Cur0 CURSOR, @TAB_NUM TINYINT, @TAB_NAME VARCHAR(254), @Cur CURSOR, @Cur1 CURSOR, @NUM INT, @BLOK_NAME VARCHAR(254), @RAZDEL_NUM TINYINT, @RAZDEL_NAME VARCHAR(254)

DECLARE @lcFNAME varchar(254)
SELECT @lcFNAME = FSS_REG_NUM + '_' + CONVERT(VARCHAR(4),@YEAR)  + '_' +  (CASE @Period_Number WHEN 1 THEN '03' WHEN 2 THEN '06' WHEN 3 THEN '09' ELSE '12' END) + '.XML' FROM #DEP_DATA

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
  SELECT @lcFNAME, 'OEM' --Имя файла
  UNION ALL SELECT @lcFNAME, SPACE(0) + '<?xml version="1.0" encoding="windows-1251"?>'
  UNION ALL SELECT @lcFNAME, SPACE(0) + '<?F4FORM version="0.6"?>'
  UNION ALL SELECT @lcFNAME, SPACE(0) + '<F4REPORT>'
  
  /** Титул **/
  
	UNION ALL SELECT @lcFNAME, SPACE(1) + '<TITLE' 
		+ ' REG_NUM="' + LTRIM(RTRIM(FSS_REG_NUM)) + '"'
		+ ' KPS_NUM="' + LTRIM(RTRIM(FSS_KOD_P)) + '"'
		+ ' DOP_NUM="' + ISNULL(LTRIM(RTRIM(FSS_KOD_DOP)),'') + '"'
		+ ' INN="' + LTRIM(RTRIM(INN1)) + '"'
		+ ' KPP="' + LTRIM(RTRIM(KPP1)) + '"'
		+ ' OGRN="' + LTRIM(RTRIM(OGRN)) + '"'
		--+ ' OKOPF="' + LTRIM(RTRIM(OKOPF)) + '"'
		--+ CASE WHEN @OKATO_OR_OKTMO = 1 THEN  (' OKATO="' + REPLACE(LTRIM(RTRIM(OKATO)),' ','') + '"') ELSE (' OKTMO="' + REPLACE(LTRIM(RTRIM(OKTMO)),' ','') + '"') END
		--+ ' OKPO="' + LTRIM(RTRIM(OKPO)) + '"'
		--+ ' OKFS="' + LTRIM(RTRIM(OKFS)) + '"'
		--+ ' OKVED="' + LTRIM(RTRIM(OKVED)) + '"'
		+ ' QUART_NUM="' + (CASE @Period_Number WHEN 1 THEN '03' WHEN 2 THEN '06' WHEN 3 THEN '09' ELSE '12' END) + '"'
		+ ' YEAR_NUM="' + CONVERT(VARCHAR(4),@YEAR) + '"'
		+ ' NAME="' + LTRIM(RTRIM(REPLACE(FULL_NAME,'"','&quot;'))) + '"'
		+ ' CRE_DATE="' + convert(varchar(10),@modify_date,120) + '"'
		+ ' WRO="' + LEFT(FSS_REG_NUM,4) + '"'
		+ ' CEO="' + LTRIM(RTRIM(CHIEF_FIO)) + '"'
		+ ' CFO="' + LTRIM(RTRIM(GLBUH_FIO)) + '"'
		+ ' AUTHOR="' + ISNULL(dbo.AdminGetUserFIO(default),'') + '"'
		+ ' PHONE="' +(SELECT LTRIM(RTRIM(phone)) FROM DICTIONARY_OTV_FACE  WHERE Dep_LINK=dbo.GetOwnDepLink() and name = 'Главный бухгалтер') + '"'
		+ ' NumCorr="' + LTRIM(RTRIM(CONVERT(VARCHAR(3),@Version))) + '"' --Номер корректировки
		+ ' NumDot="' + LTRIM(RTRIM(CONVERT(VARCHAR(2),@NumDot))) + '"' --Номер корректировки
		+ ' TaxType="' + LEFT(LTRIM(RTRIM(TaxType)),3) + '"' --Шифр (первая часть)
		+ ' TaxType2="' + LEFT(LTRIM(RTRIM(TaxType2)),2) + '"' --Шифр (вторая часть)
		+ ' TaxType3="' + LEFT(LTRIM(RTRIM(TaxType3)),2) + '"' --Шифр (третья часть)		
		+ ' T1R1C2="' + LTRIM(RTRIM(CONVERT(VARCHAR(6),ISNULL((SELECT TOP 1 SUMMA FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 1, 1, 3)),0)))) + '"' --Численность работников	
		+ ' T1R2C2="' + LTRIM(RTRIM(CONVERT(VARCHAR(6),ISNULL((SELECT TOP 1 SUMMA FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 1, 2, 3)),0)))) + '"' --из них: женщин	
		+ ' T1R4C2="' + LTRIM(RTRIM(CONVERT(VARCHAR(6),ISNULL((SELECT TOP 1 SUMMA FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 1, 3, 3)),0)))) + '"' --из них: работающих инвалидов	
		+ ' T1R6C2="' + LTRIM(RTRIM(CONVERT(VARCHAR(6),ISNULL((SELECT TOP 1 SUMMA FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 1, 4, 3)),0)))) + '"' --из них: работающих, занятых на работах с вредными и (или) опасными производственными факторами	
		+ '/>'
		FROM #DEP_DATA
--  /** Раздел I **/

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '<F4INF1 '

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' OKVED="' + LTRIM(RTRIM(OKVED)) + '"' FROM #DEP_DATA
		--Таблица 1 строка 1 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 1, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 2 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 3, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' Ch' + LTRIM(STR(ROW +1 - 5)) + '="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, DEFAULT, 3) WHERE SUMMA2 <> 0 AND ROW IN (5,6,7)				
		--Таблица 1 строка 3 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' N0="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 9, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' N' + LTRIM(STR(ROW + 1 - 11)) + '="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, DEFAULT, 3) WHERE SUMMA2 <> 0 AND ROW IN (11,12,13)				
		--Таблица 1 строка 4 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 14, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 5 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NRe0="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 16, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NRe1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 18, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NRe2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 19, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R13="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 20, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 6 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2F0="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 22, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2F1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 24, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2F2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 25, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R16="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 26, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 7 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2N="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 27, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 9 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' FssDebt="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 29, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 11 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R18="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 31, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 12 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R19="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 32, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 14 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R20="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 34, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 15  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R21="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 36, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' Re' + LTRIM(STR(ROW + 1 - 38)) + '="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, DEFAULT, 3) WHERE SUMMA2 <> 0 AND ROW IN (38,39,40)				
		--Таблица 1 строка 16  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R27="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 42, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R29="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 44, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R30="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 45, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R26="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 46, 3) WHERE SUMMA2 <> 0
		--Таблица 1 строка 17  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R32="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 47, 3) WHERE SUMMA2 <> 0
		--Таблица 1 строка 19  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' InsDebt="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 49, 3) WHERE SUMMA2 <> 0
		--Таблица 1 строка 20  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' InsDelDebt="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 50, 3) WHERE SUMMA2 <> 0

		--Таблица 2 строка 1  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3QCase="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 1, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R1C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 1, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R1C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 1, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R1C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 1, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 2  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3QCase2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 2, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R2C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 2, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R2C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 2, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R2C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 2, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 3  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3QCase4="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 3, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R4C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 3, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R4C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 3, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R4C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 3, 6) WHERE SUMMA2 <> 0		
		--Таблица 2 строка 4 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3QCase3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 4, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R41C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 4, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R41C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 4, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R41C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 4, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 5  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R5C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 5, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R5C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 5, 5) WHERE SUMMA2 <> 0		
		--Таблица 2 строка 6  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R6C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 6, 4) WHERE SUMMA2<> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R6C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 6, 5) WHERE SUMMA2 <> 0		
		--Таблица 2 строка 7  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3RCP7="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 7, 3) WHERE SUMMA2 <> 0
		--Таблица 2 строка 8  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3RCP71="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 8, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R71C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 8, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R71C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 8, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R71C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 8, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 9  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3RCP72="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 9, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R72C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 9, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R72C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 9, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R72C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 9, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 10  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R3C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 10, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R3C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 10, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R3C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 10, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 11  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R8C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 11, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R8C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 11, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R8C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 11, 6) WHERE SUMMA2 <> 0				

		--Таблица 3 строка 1  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S1' + CASE WHEN COL = 3 THEN '' ELSE '_' + CONVERT(VARCHAR(3),COL-3) END +'="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 1, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		--Таблица 3 строка 2  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S2' + CASE WHEN COL = 3 THEN '' ELSE '_' + CONVERT(VARCHAR(3),COL-3) END +'="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 2, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		--Таблица 3 строка 3  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S4' + CASE WHEN COL = 3 THEN '' ELSE '_' + CONVERT(VARCHAR(3),COL-3) END +'="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 3, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		--Таблица 3 строка 5  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S3' + CASE WHEN COL = 3 THEN '' ELSE '_' + CONVERT(VARCHAR(3),COL-3) END +'="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 5, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		--Таблица 3 строка 6  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S6' + CASE WHEN COL = 3 THEN '' ELSE '_' + CONVERT(VARCHAR(3),COL-3) END +'="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 6, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		--Таблица 3 строка 7  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S7' + CASE WHEN COL = 3 THEN '' ELSE '_' + CONVERT(VARCHAR(3),COL-3) END +'="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 7, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		
		
		--Таблица 4 строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_C="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 1, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 1, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 1, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 1, 6) WHERE SUMMA2 <> 0				
		--Таблица 4 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_CI="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 2, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_CI1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 2, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_CI2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 2, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_CI3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 2, 6) WHERE SUMMA2 <> 0				
		
		--Таблица 4.1 строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_C="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 1, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 1, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 1, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 1, 6) WHERE SUMMA2 <> 0				
		--Таблица 4.1 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_CI="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 2, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_CI1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 2, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_CI2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 2, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_CI3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 2, 6) WHERE SUMMA2 <> 0				
		--Таблица 4.1 строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_S="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 4, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_S1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 4, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_S2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 4, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_S3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 4, 6) WHERE SUMMA2 <> 0				
		--Таблица 4.1 строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_SI="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 5, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_SI1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 5, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_SI2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 5, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_SI3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 5, 6) WHERE SUMMA2 <> 0				

		-- Таблица 4.2 строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT_WRK_CNT="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 1, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT2WRK_CNT1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 1, 6) WHERE SUMMA2 <> 0	
		-- Таблица 4.2 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT_PRF_ALL="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 2, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT2PRF_ALL="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 2, 6) WHERE SUMMA <> 0				
		-- Таблица 4.2 строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT_PRF_SPC="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 3, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT2PRF_SPC="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 3, 6) WHERE SUMMA <> 0				
		-- Таблица 4.2 строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT_ACC_DT="' 
							+ CASE LEN(LTRIM(RTRIM(LEFT(STR_VAL,10))))
								WHEN 10 THEN 
									SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),7,4)
									+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),4,2)
									+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),1,2)
								WHEN 8 THEN 
									'20' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),7,2)
									+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),4,2)
									+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),1,2)								
								ELSE
								''
							END	+ '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 5, 4) WHERE ISNULL(STR_VAL,'') <> ''
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT_ACC_NM="' + LEFT(STR_VAL,8) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 5, 5) WHERE ISNULL(STR_VAL,'') <> ''
	
		--Таблица 4.3 строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' OKV_S1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 3) WHERE SUMMA <> 0				
		--Таблица 4.3 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' OKV_S2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 2, 3) WHERE SUMMA <> 0				


		--Таблица 4.4 строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' CUL_SP1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 1, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' CUL_S1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 1, 4) WHERE SUMMA <> 0				
		--Таблица 4.4 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' CUL_SP2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 2, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' CUL_S2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 2, 4) WHERE SUMMA <> 0				
		--Таблица 4.4 строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' CUL_SP3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 3, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' CUL_S3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 3, 4) WHERE SUMMA <> 0				
		--Таблица 4.4 строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' CUL_SP4="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 4, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' CUL_S4="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 4, 4) WHERE SUMMA <> 0				
	
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(0) + ' >'

		/*Раздел I Платежное поручение*/
		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 44, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@first_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 44, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 44, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 45, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@second_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 45, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 45, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 46, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@third_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 46, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 46, 4)

		--Сведения об инвалидах
		CREATE TABLE #INVALID (
			LINK INT, FIO VARCHAR(254), FIO2 VARCHAR(254), NUM_SPR VARCHAR(30), DATE_SPR VARCHAR(10), 
			GRP VARCHAR(25), GRP2 VARCHAR(25), PER_BEG VARCHAR(10), PER_END VARCHAR(10), 
			SM_ALL 	NUMERIC(18,2), SM_QWART NUMERIC(18,2), SM1 NUMERIC(18,2), SM2 NUMERIC(18,2), SM3 NUMERIC(18,2) )

		CREATE TABLE #TAB5 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
		INSERT INTO #TAB5 (ROW_CODE, COL, SUMMA, STR_VAL)
		SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 5, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

		INSERT INTO #INVALID (FIO2, DATE_SPR, PER_END, SM_ALL, SM1, SM2, SM3)
		SELECT DISTINCT 
			FIO2 = (SELECT TOP 1 REPLACE(STR_VAL,SPACE(1), ', ') FROM #TAB5 T WHERE T.COL = 2 AND T.ROW_CODE = T5.ROW_CODE),
			DATE_SPR = (SELECT TOP 1 STR_VAL FROM #TAB5 T WHERE T.COL = 3 AND T.ROW_CODE = T5.ROW_CODE),
			PER_END = (SELECT TOP 1 STR_VAL FROM #TAB5 T WHERE T.COL = 4 AND T.ROW_CODE = T5.ROW_CODE),
			SM_ALL = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 5 AND T.ROW_CODE = T5.ROW_CODE),
			SM1 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 6 AND T.ROW_CODE = T5.ROW_CODE),
			SM2 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 7 AND T.ROW_CODE = T5.ROW_CODE),
			SM3 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 8 AND T.ROW_CODE = T5.ROW_CODE)
		FROM
			#TAB5 T5

		DROP TABLE #TAB5

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, 
			SPACE(1) + ' <F4INVAL'  + 
				' LNAME="' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,1,','),'')))) + '"' +
				' FNAME="' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,2,','),'')))) + '"' +
				' MNAME="' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,3,','),'')))) + '"' +
				' MSEDATE="' + CASE LEN(LTRIM(RTRIM(ISNULL(DATE_SPR,''))))
									WHEN 10 THEN 
										SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),7,4)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),4,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),1,2)
									WHEN 8 THEN 
										'20' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),7,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),4,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),1,2)								
									ELSE
										''
								END + '"' +
				CASE WHEN ISNULL(PER_END,'') <> ''
				THEN 
					' MSEDATEF="' 
								+ CASE LEN(LTRIM(RTRIM(ISNULL(PER_END,''))))
									WHEN 10 THEN 
										SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),7,4)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),4,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),1,2)
									WHEN 8 THEN 
										'20' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),7,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),4,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),1,2)								
									ELSE
									''
								END + '"'
				ELSE
					''	
				END +
				' S="' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM_ALL,0)))) + '"' +
				' S1="' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM1,0)))) + '"' +
				' S2="' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM2,0)))) + '"' +
				' S3="' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM3,0)))) + '"' +
			' />' 
		FROM #INVALID 
		ORDER BY FIO2

		DROP TABLE #INVALID

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '</F4INF1>'

/** Раздел II **/
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(1)


		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '<F4INFO '		
		--Таблица 5 Строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C8="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 12) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C18="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 13) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C7="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 14) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 17) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C12="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 18) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C22="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 19) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C11="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 20) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 17) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C12="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 18) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C22="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 19) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C11="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 20) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R3C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 3, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R3C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 3, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R3C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 3, 15) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 17) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 17) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 6
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 17) WHERE SUMMA2 <> 0				

		--Таблица 6 Строка 1
		UNION ALL SELECT @lcFNAME, SPACE(1)		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' OKVED="' + LTRIM(RTRIM(OKVED)) + '"' FROM #DEP_DATA
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T1R3C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T1R5C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NC="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 5) WHERE SUMMA2 <> 0
		--Таблица 6 Строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 3, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' I1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 3, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NC1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 3, 5) WHERE SUMMA2 <> 0
		--Таблица 6 Строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 4, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' I2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 4, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NC2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 4, 5) WHERE SUMMA2 <> 0
		--Таблица 6 Строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 5, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' I3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 5, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NC3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 5, 5) WHERE SUMMA2 <> 0
		--Таблица 6 графа 6
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RATE_MIS="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,1),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 6) WHERE SUMMA2 <> 0
		--Таблица 6 графа 7
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RATE_DEC="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 7) WHERE SUMMA2 <> 0
		--Таблица 6 графа 8
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' INC_DATE="' 
					+ CASE LEN(LTRIM(RTRIM(LEFT(STR_VAL,10))))
						WHEN 10 THEN 
							SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),7,4)
							+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),4,2)
							+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),1,2)
						WHEN 8 THEN 
							'20' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),7,2)
							+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),4,2)
							+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),1,2)								
						ELSE
						''
					END + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 8) WHERE ISNULL(STR_VAL,'') <> ''

		--Таблица 6 графа 9
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RATE_INC="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 9) WHERE SUMMA2 <> 0

		--Таблица 7 строка 1 
		UNION ALL SELECT @lcFNAME, SPACE(1)		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R1C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 1, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R3C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 3, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R5C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 5, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R6C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 6, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R7C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 7, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R9C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 8, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R13C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 9, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R11C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 10, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 6
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R16C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 11, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 7
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R17C61="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 12, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 9
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R18C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 14, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 10
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R19C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 15, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 11
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R21C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 17, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R23C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 19, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R24C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 20, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R25C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 21, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 12
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R27C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 23, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R29C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 25, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R30C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 26, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R31C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 27, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 13
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R38C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 28, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 15
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R34C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 30, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 16
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R35C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 31, 3) WHERE SUMMA2 <> 0


		--Таблица 8 строка 1
		UNION ALL SELECT @lcFNAME, SPACE(1)		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R3C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 1, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R3C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 1, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R13C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 2, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R13C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 2, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R4C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 3, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R4C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 3, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R8C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 4, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R8C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 4, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R14C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 5, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R14C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 5, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 6
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R9C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 6, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R9C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 6, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 7
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R5C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 7, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R5C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 7, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 8
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R6C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 8, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R6C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 8, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 9
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R10C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 9, 4) WHERE SUMMA2 <> 0

		--Таблица 9
		UNION ALL SELECT @lcFNAME, SPACE(1)
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' M' + CONVERT(VARCHAR(2),ROW) + '="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 16, DEFAULT, 3) WHERE ROW IN (1,2,3,5) AND SUMMA <> 0

		--Таблица 10 строка 1
		UNION ALL SELECT @lcFNAME, SPACE(1)
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' ATT_C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 17, 1, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' ATT_C2="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 17, 1, 4) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' ATT_CL3="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 17, 1, 6) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' ATT_CL4="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 17, 1, 7) WHERE SUMMA <> 0

		--Таблица 10 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' MED_C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 17, 2, 8) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' MED_C2="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 17, 2, 9) WHERE SUMMA <> 0
		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(0) + ' >'

		/*Раздел I Платежное поручение*/
		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 25, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@first_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 25, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 25, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 26, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@second_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 26, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 26, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 27, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@third_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 27, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 27, 4)
		
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '</F4INFO>'
	
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, SPACE(0) + '</F4REPORT>'

SET NOCOUNT OFF

select * from #OUTPUT order by [ID]








GO


GRANT EXECUTE ON dbo.[SA_4FSS_EXPORT_v05] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RSA_RSV_1_14_PFR_PREPARE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RSA_RSV_1_14_PFR_PREPARE]

GO

/*

 DECLARE @Res float
SET @Res = 0
 exec [dbo].RSA_RSV_1_14_PFR_PREPARE @Res output, '', '20140101', '20140331', 3, 0, 2494
 select @Res 	
 
 --SELECT * FROM REPORT_SAVED_FORMS ORDER BY Link_Saved_Form

*/

CREATE PROCEDURE dbo.RSA_RSV_1_14_PFR_PREPARE 
	@Res float output, @varcStr varchar(250), @vardBegin datetime = '20050101', @vardEnd datetime = '20051231', @variCol int, @variRow int, @variLSF int
AS 

DECLARE @OUT_VAL NUMERIC(20), @START_DATE DATETIME, @END_DATE DATETIME, @DEP_LINK INT, @TFOMS_KT int

DECLARE --Для выравнивания погрешности
	@C3S NUMERIC(18,6), @C4S NUMERIC(18,6), @C5S NUMERIC(18,6), @C6S NUMERIC(18,6),
	@C3N NUMERIC(18,6), @C4N NUMERIC(18,6), @C5N NUMERIC(18,6), @C6N NUMERIC(18,6),
	@C3SS NUMERIC(18,6), @C4SS NUMERIC(18,6), @C5SS NUMERIC(18,6), @C6SS NUMERIC(18,6),
	@C3NS NUMERIC(18,6), @C4NS NUMERIC(18,6), @C5NS NUMERIC(18,6), @C6NS NUMERIC(18,6)	

select @DEP_LINK = Link_Organization from report_saved_forms where link_saved_form =  @variLSF

set @TFOMS_KT = (select  (case when TFOMS_KT = '' then '01' else TFOMS_KT end)  from dictionary_department where link = @DEP_LINK)

set @res = 0
SELECT @START_DATE = @vardBegin, @END_DATE = @vardEnd

DECLARE @BYearDate	datetime
SET @BYearDate = dbo.DateBeginOfYear (@START_DATE)

DECLARE @nYEAR INT, @nMONTH1 INT, @nMONTH2 INT, @nMONTH3 INT

SELECT 
	@nYEAR = YEAR(@START_DATE),
	@nMONTH1 = MONTH(@START_DATE),
	@nMONTH2 = MONTH(@START_DATE)+1,
	@nMONTH3 = MONTH(@START_DATE)+2

create table #SPR_ESN ([MONTH_BASE] TINYINT, SUMMA_BASE numeric(12,2) default 0.00, DED_M numeric(12,2) default 0.00, INV_M numeric(12,2) default 0.00, SUMMA numeric(12,2) default 0.00, WAY_CALC int default 0.00, REF_PHYS_PERS int default 0, FACE_GROUP TINYINT, I TINYINT, E TINYINT , SP VARCHAR(4))

Insert InTo #SPR_ESN ([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, FACE_GROUP, I, E, SP)
Select [MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, 
	( CASE WHEN P.RESIDENT = 0 THEN 3 
		   WHEN YEAR(birthdate)<= 1966 THEN 1 
		   WHEN YEAR(birthdate)>= 1967 THEN 2 END ) AS FACE_GROUP, 
	dbo.is_invalid(REF_PHYS_PERS,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH_BASE,@nYEAR))),
	F.ENVD,
	SP = isnull(s4.code,'')
from dbo.SA_ESN_VIEW(@nYEAR, @nMONTH3, @DEP_LINK, 0) S
	inner join PERSON P on S.REF_PHYS_PERS = P.link
	inner join dbo.SAL_SFIN F on F.LINK = S.LINK_VKR
	LEFT JOIN SA_SZV4_SPR  s4 ON  s4.link = S.SPECO  AND s4.spr_code = 'SPO_USL_TRUDA'
WHERE  WAY_CALC not in (5)

--Суммы по договорникам
INSERT INTO #SPR_ESN 
	([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, FACE_GROUP, I, E)
SELECT 
	MONTH(G.[DATE]) AS MONTH_BASE, GT.SUMMA_BASE, 0, 0, GT.SUMMA, GT.WAY_CALC, GT.PERS_LINK, 
	( CASE WHEN P.RESIDENT = 0  THEN 3
		   WHEN YEAR(birthdate)<= 1966 THEN 1 
		   WHEN YEAR(birthdate)>= 1967 THEN 2 END) AS FACE_GROUP , 
	dbo.is_invalid(GT.PERS_LINK,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,G.[MONTH],@nYEAR))),
	F.ENVD
	
FROM 
	DOCUMENTS_DGH G INNER JOIN DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
	inner join PERSON P on GT.PERS_LINK = P.link
	inner join dbo.SAL_SFIN F on F.LINK = GT.LINK_VKR
WHERE 
	FLAG_JC = 1
	AND GT.WAY_CALC  not in (5)
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3
	AND LINK_DEP = @DEP_LINK


DELETE FROM #SPR_ESN
WHERE  EXISTS (SELECT * FROM dbo.KJ_PERS_PENSION K WHERE K.PERS_LINK = REF_PHYS_PERS  and K.CHECK_SZV = 0)


CREATE TABLE #RES2(CODE_STR VARCHAR(10), C1 NUMERIC(18,2), C2 NUMERIC(18,2),  C3 NUMERIC(18,2), C4 NUMERIC(18,2), C5 NUMERIC(18,2), C6 NUMERIC(18,2), C7 NUMERIC(18,2), C8 NUMERIC(18,2))
/*
для заполнения показателя "количество застрахованных лиц", указывается количество застрахованных лиц,
за которых должны быть представлены сведения индивидуального (персонифицированного) учета за отчетный период.
*/

declare @EndYear datetime
Set @EndYear = dbo.DateEndOfYear(@START_DATE)

DECLARE @C1_PERIOD_BEG DATETIME, @C1_PERIOD_END DATETIME

SELECT @C1_PERIOD_BEG = @START_DATE,
	   @C1_PERIOD_END = @END_DATE
		   
--------------
DECLARE @BDate datetime, @EndDate datetime, @EDate datetime, @NAvgCount int
SELECT @NAvgCount = COUNT(pers_link) 
FROM
(
	SELECT DISTINCT E.pers_link
	FROM 
		dbo.EMPL E inner join dbo.ITEM_MOVE P on E.link = P.empl_link and P.NEW_FACE = 1 AND P.ACTIVE=1
		left join dbo.ITEM_DIS_FACE U on E.link = U.empl_link AND U.ACTIVE=1
	WHERE 
		P.DATE_BEGIN <= @C1_PERIOD_END
		and
		coalesce(U.DIS_DATE,'20990101') >= @C1_PERIOD_BEG
		And 
		E.DEP_LINK = @DEP_LINK
	UNION 
	Select DISTINCT
		DFG.link
	FROM PERSON DFG inner join SALARY_REESTR_DGH DGH on DFG.link = DGH.PERS_LINK
	WHERE 
		DGH.DATE1 = (
			Select max(DATE1)  from SALARY_REESTR_DGH as DGH0 
					where DGH.PERS_LINK = DGH0.PERS_LINK AND DGH0.DEP_LINK = DGH.DEP_LINK
						AND
						(
							ISNULL(DATE1, '19000101') between  @C1_PERIOD_BEG and @C1_PERIOD_END
							or ISNULL(DATE2, '20990101') between @C1_PERIOD_BEG and @C1_PERIOD_END
						)
					)
		And 
		DGH.DEP_LINK = @DEP_LINK
) AS T		


--
INSERT INTO #RES2(CODE_STR, C1)
SELECT '1', ISNULL(@NAvgCount,0)



/********СРЕДНЕСПИСОЧНАЯ ЧИСЛЕННОСТЬ**********/
SELECT @BDate = @START_DATE, @EndDate = @END_DATE
SET @EDate = dateadd(year,1,convert(varchar, YEAR(@BDate))+'0101')

/* Среднесписочная численность мужчин и женщин */
Set @NAvgCount = convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 0, DEFAULT))
--
UPDATE #RES2 SET C2 = ISNULL(@NAvgCount,0) WHERE CODE_STR = '1'
--Раздел 2. Расчет страховых взносов по тарифу, установленному для плательщика страховых взносов
Declare @StBase2 table (link int)
Insert into @StBase2 (link)
select distinct link_pays from tax_ref where link_tax = (select top 1 link from pays where object = 3 and way_calc = 6)


--Фактическая база для договорников
SELECT 
	GT.PERS_LINK, MONTH(G.[DATE]) AS MONTH_BASE, F.ENVD, SUMMA_BASE = sum(GT.SUMMA_BASE)
INTO #DGH_FAKT_BASE
FROM 
	dbo.DOCUMENTS_DGH G INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
	INNER JOIN dbo.SAL_SFIN F on F.LINK = GT.LINK_VKR
WHERE 
	FLAG_JC = 1
	AND GT.WAY_CALC  = 6
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3
	AND LINK_DEP = @DEP_LINK 
GROUP BY 
	GT.PERS_LINK, MONTH(G.[DATE]), F.ENVD

SELECT  PERS_LINK, MONTH_BASE, SUMMA_BASE = SUM(SUMMA_BASE)
INTO #DGH_FAKT_BASE1
FROM #DGH_FAKT_BASE
GROUP BY PERS_LINK, MONTH_BASE

DECLARE @LINK_EKR213 INT
SET @LINK_EKR213 = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '213')

DECLARE @ESN_213 INT --Начислять страховые взносы на доходы с 213 ЭКР                                                    
SET @ESN_213 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_5')

------
CREATE TABLE #CALCULATE_JURNAL (LINK_PAYS INT, PERIOD_BEGIN DATETIME, LINK_DOC INT, PERS_LINK INT, LINK_VKR INT, LINK_EKR INT, LINK_EMPL INT, SUMMA NUMERIC(18,2), WAY_CALC TINYINT , SPECO int)
INSERT INTO #CALCULATE_JURNAL (LINK_PAYS, PERIOD_BEGIN, LINK_DOC, PERS_LINK, LINK_VKR, LINK_EKR, LINK_EMPL, SUMMA,way_calc , SPECO)
SELECT CJ.LINK_PAYS, CJ.PERIOD_BEGIN, CJ.LINK_DOC, CJ.PERS_LINK, CJ.LINK_VKR, cj.LINK_EKR, CJ.LINK_EMPL, SUMMA = SUM(CJ.SUMMA), p.way_calc , SPECO
FROM dbo.CALCULATE_JURNAL CJ INNER JOIN dbo.PAYS P ON  CJ.LINK_PAYS = p.link
WHERE
	Year(period_begin) = @nYEAR 
	and Month(period_begin) <= @nMONTH3 
	and CJ.LINK_DEP = @DEP_LINK
GROUP BY
	cj.LINK_PAYS, cj.PERIOD_BEGIN, cj.LINK_DOC, cj.PERS_LINK, cj.LINK_VKR, cj.LINK_EKR, cj.LINK_EMPL, P.WAY_CALC,cj.SPECO


------	у кого была инвалидность в заданном периоде
SELECT DISTINCT PERS_LINK 
INTO #PERS_INV
FROM dbo.PERS_INVALID I
WHERE COALESCE(I.DATE_BEGIN,@BYearDate) <= @EndYear AND COALESCE(I.DATE_END,@EndYear) >= @BYearDate

------	у кого есть расчеты по доп тарифам со спец оценками в заданном периоде 
SELECT DISTINCT sd.LINK, DOP = (CASE when S.COD_POS_SPISOK is NOT NULL then 1 else 2 end) , SPO = isnull(s4.code,'')
INTO #EMPL_DT
FROM DBO.KU_EMPL_PLACING SD
	left JOIN (select * from STAFF WHERE dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@nMONTH3,@nYEAR)) BETWEEN DATE_BEGIN AND DATE_END  ) S ON S.LINK_up = SD.STAFF_HEAD  AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@nMONTH3,@nYEAR )) BETWEEN S.DATE_BEGIN AND S.DATE_END
	LEFT JOIN SA_SZV4_SPR  s4 ON  s4.link = s.COD_SPO_USL_TRUD  AND s4.spr_code = 'SPO_USL_TRUDA'
	WHERE 
		(S.COD_POS_SPISOK is NOT NULL OR S.COD_POS_SPISOK2 is NOT NULL) 


--Заготовка для #SALARY_SUM2
CREATE TABLE #SALARY_SUM_DATA (PERS_LINK INT, PERIOD_BEGIN DATETIME, SUMMA_ALL NUMERIC(18,2), SUMMA_NO NUMERIC(18,2), SUMMA_ALL_I NUMERIC(18,2), SUMMA_NO_I NUMERIC(18,2), SUMMA_ALL_E NUMERIC(18,2), SUMMA_NO_E NUMERIC(18,2), INV TINYINT 
		/*,SUMMA_ALL_D1 NUMERIC(18,2)*/, SUMMA_NO_D1 NUMERIC(18,2)/*, SUMMA_ALL_D2 NUMERIC(18,2)*/, SUMMA_NO_D2 NUMERIC(18,2),    
	SUM_NO_D1_O4 NUMERIC(18,2) ,SUM_NO_D1_B34 NUMERIC(18,2) ,SUM_NO_D1_B33 NUMERIC(18,2),SUM_NO_D1_B32 NUMERIC(18,2), SUM_NO_D1_B31 NUMERIC(18,2),
		SUM_NO_D2_O4 NUMERIC(18,2) ,SUM_NO_D2_B34 NUMERIC(18,2) ,SUM_NO_D2_B33 NUMERIC(18,2),SUM_NO_D2_B32 NUMERIC(18,2), SUM_NO_D2_B31 NUMERIC(18,2) 
		)
--Сотрудники
INSERT INTO #SALARY_SUM_DATA (PERS_LINK, PERIOD_BEGIN, SUMMA_ALL, SUMMA_NO, SUMMA_ALL_I, SUMMA_NO_I, SUMMA_ALL_E, SUMMA_NO_E, INV 
		/*,SUMMA_ALL_D1*/, SUMMA_NO_D1/*, SUMMA_ALL_D2*/, SUMMA_NO_D2,SUM_NO_D1_O4,SUM_NO_D1_B34,SUM_NO_D1_B33, SUM_NO_D1_B32, SUM_NO_D1_B31,
		SUM_NO_D2_O4,SUM_NO_D2_B34,SUM_NO_D2_B33, SUM_NO_D2_B32, SUM_NO_D2_B31
	)
select
	E.PERS_LINK, 
	CJ.PERIOD_BEGIN,
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(CASE WHEN B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0 THEN SUMMA ELSE 0 END), --на которые не начисляются страховые взносы
	SUMMA_ALL_I = 0,
	SUMMA_NO_I = 0,
	SUMMA_ALL_E = SUM(CASE WHEN F.ENVD = 1 THEN SUMMA ELSE 0 END),
	SUMMA_NO_E = SUM(CASE WHEN F.ENVD = 1 AND (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) THEN SUMMA ELSE 0 END),
	INV = CASE WHEN I.PERS_LINK IS NULL THEN 0 ELSE 1 END,

	--SUMMA_ALL_D1 = SUM(CASE WHEN CJ.way_calc = 10 then  SUMMA ELSE 0 end ),
	SUMMA_NO_D1 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and ED.DOP = 1 AND isnull(SPO,'') ='' THEN SUMMA ELSE 0 END),

	----SUMMA_ALL_D2 = SUM(CASE WHEN CJ.way_calc = 11 then  SUMMA ELSE 0 end ),
	SUMMA_NO_D2 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and ED.DOP = 2 and  isnull(SPO,'') ='' THEN SUMMA ELSE 0 END),
	SUM_NO_D1_O4 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='О4'  THEN SUMMA ELSE 0 END),
	SUM_NO_D1_B34 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.4' THEN SUMMA ELSE 0 END),
	SUM_NO_D1_B33 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.3' THEN SUMMA ELSE 0 END), 
	SUM_NO_D1_B32 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.2' THEN SUMMA ELSE 0 END), 
	SUM_NO_D1_B31 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.1' THEN SUMMA ELSE 0 END),	
	SUM_NO_D2_O4 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='О4' THEN SUMMA ELSE 0 END),
	SUM_NO_D2_B34 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.4' THEN SUMMA ELSE 0 END),
	SUM_NO_D2_B33 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.3' THEN SUMMA ELSE 0 END), 
	SUM_NO_D2_B32 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.2' THEN SUMMA ELSE 0 END), 
	SUM_NO_D2_B31 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.1' THEN SUMMA ELSE 0 END)

from 
	#CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
	INNER JOIN dbo.SAL_SFIN F on F.LINK = CJ.LINK_VKR
	INNER JOIN DBO.EMPL E ON E.LINK = CJ.LINK_EMPL
	LEFT JOIN @StBase2 B ON B.LINK = cj.LINK_PAYS
	LEFT JOIN #PERS_INV I ON I.PERS_LINK = E.PERS_LINK
	LEFT JOIN #EMPL_DT ED ON ED.link = CJ.LINK_EMPL
where 	
	P.[OBJECT] = 1
GROUP BY
	E.PERS_LINK, I.PERS_LINK, CJ.PERIOD_BEGIN


--Договрники
INSERT INTO #SALARY_SUM_DATA (PERS_LINK, PERIOD_BEGIN, SUMMA_ALL, SUMMA_NO, SUMMA_ALL_I, SUMMA_NO_I, SUMMA_ALL_E, SUMMA_NO_E, INV 
		--,SUMMA_ALL_D1, SUMMA_NO_D1, SUMMA_ALL_D2, SUMMA_NO_D2
		)
select
	CJ.PERS_LINK, 
	CJ.PERIOD_BEGIN,
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(SUMMA) - ISNULL((SELECT SUM(B1.SUMMA_BASE) FROM #DGH_FAKT_BASE1 B1 WHERE B1.PERS_LINK = CJ.PERS_LINK AND B1.MONTH_BASE = Month(CJ.PERIOD_BEGIN)),0), --на которые не начисляются страховые взносы
	SUMMA_ALL_I = 0,
	SUMMA_NO_I = 0,
	SUMMA_ALL_E = SUM(CASE WHEN F.ENVD = 1 THEN SUMMA ELSE 0 END),
	SUMMA_NO_E = SUM(CASE WHEN F.ENVD = 1 THEN SUMMA ELSE 0 END)  - ISNULL((SELECT SUM(B.SUMMA_BASE) FROM #DGH_FAKT_BASE B WHERE B.PERS_LINK = CJ.PERS_LINK AND B.MONTH_BASE = Month(CJ.PERIOD_BEGIN) AND B.ENVD = 1),0),
	INV = CASE WHEN I.PERS_LINK IS NULL THEN 0 ELSE 1 END

	--SUMMA_ALL_D1 = SUM(CASE WHEN CJ.way_calc = 10 then  SUMMA ELSE 0 end ),
	--SUMMA_NO_D1 = 0, 

	--SUMMA_ALL_D2 = SUM(CASE WHEN CJ.way_calc = 11 then  SUMMA ELSE 0 end ),
	--SUMMA_NO_D2 = 0
		
from 
	#CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
	INNER JOIN dbo.SAL_SFIN F on F.LINK = CJ.LINK_VKR
	INNER JOIN DBO.PERSON P1 ON P1.LINK = CJ.PERS_LINK
	--База по договорникам в разрезе ЕНВД
--	LEFT JOIN #DGH_FAKT_BASE B ON B.PERS_LINK = CJ.PERS_LINK AND B.MONTH_BASE = Month(CJ.PERIOD_BEGIN) AND B.ENVD = 1
	--Общая база по договорникам
--	LEFT JOIN #DGH_FAKT_BASE1 B1 ON B1.PERS_LINK = CJ.PERS_LINK AND B1.MONTH_BASE = Month(CJ.PERIOD_BEGIN)
	LEFT JOIN #PERS_INV I ON I.PERS_LINK = CJ.PERS_LINK
where 	
	P.[OBJECT] = 1
GROUP BY
	CJ.PERS_LINK, I.PERS_LINK, CJ.PERIOD_BEGIN, P1.RESIDENT, p1.birthdate


--корректировка в соотвествие с тем, в каком есяце кто был инвалидом
UPDATE D SET 
	SUMMA_ALL_I = (CASE WHEN EXISTS (SELECT * FROM dbo.PERS_INVALID I1 WHERE I1.PERS_LINK = D.PERS_LINK AND dbo.DateEndOfMonth(PERIOD_BEGIN) BETWEEN ISNULL(I1.DATE_BEGIN,PERIOD_BEGIN) AND  ISNULL(I1.DATE_END,dbo.DateEndOfMonth(PERIOD_BEGIN))) THEN SUMMA_ALL ELSE 0 END), 
	SUMMA_NO_I = (CASE WHEN EXISTS (SELECT * FROM dbo.PERS_INVALID I1 WHERE I1.PERS_LINK = D.PERS_LINK AND dbo.DateEndOfMonth(PERIOD_BEGIN) BETWEEN ISNULL(I1.DATE_BEGIN,PERIOD_BEGIN) AND  ISNULL(I1.DATE_END,dbo.DateEndOfMonth(PERIOD_BEGIN))) THEN SUMMA_NO ELSE 0 END), 
	SUMMA_ALL_E = (CASE WHEN NOT EXISTS (SELECT * FROM dbo.PERS_INVALID I1 WHERE I1.PERS_LINK = D.PERS_LINK AND dbo.DateEndOfMonth(PERIOD_BEGIN) BETWEEN ISNULL(I1.DATE_BEGIN,PERIOD_BEGIN) AND  ISNULL(I1.DATE_END,dbo.DateEndOfMonth(PERIOD_BEGIN))) THEN SUMMA_ALL_E ELSE 0 END), 
	SUMMA_NO_E = (CASE WHEN NOT EXISTS (SELECT * FROM dbo.PERS_INVALID I1 WHERE I1.PERS_LINK = D.PERS_LINK AND dbo.DateEndOfMonth(PERIOD_BEGIN) BETWEEN ISNULL(I1.DATE_BEGIN,PERIOD_BEGIN) AND  ISNULL(I1.DATE_END,dbo.DateEndOfMonth(PERIOD_BEGIN))) THEN SUMMA_NO_E ELSE 0 END)

FROM #SALARY_SUM_DATA D
WHERE INV = 1 --которые имели инвалидность в каком-то месяце периода	




--Данные о начисленной зарплате
SELECT MON = Month(PERIOD_BEGIN), 
	SUMMA_ALL = SUM(SUMMA_ALL), SUMMA_NO = SUM(SUMMA_NO), 
	SUMMA_ALL_I = SUM(SUMMA_ALL_I), SUMMA_NO_I = SUM(SUMMA_NO_I),
	SUMMA_ALL_E = SUM(SUMMA_ALL_E), SUMMA_NO_E = SUM(SUMMA_NO_E),
	SUMMA_NO_D1 = SUM(SUMMA_NO_D1), SUMMA_NO_D2 = SUM(SUMMA_NO_D2),
	SUM_NO_D1_O4  = SUM(SUM_NO_D1_O4), SUM_NO_D1_B34 = SUM(SUM_NO_D1_B34), 
	SUM_NO_D1_B33 = SUM(SUM_NO_D1_B33), SUM_NO_D1_B32 = SUM(SUM_NO_D1_B32), SUM_NO_D1_B31 = SUM(SUM_NO_D1_B31),
	SUM_NO_D2_O4  = SUM(SUM_NO_D2_O4), SUM_NO_D2_B34 = SUM(SUM_NO_D2_B34),
	SUM_NO_D2_B33 = SUM(SUM_NO_D2_B33), SUM_NO_D2_B32 = SUM(SUM_NO_D2_B32), SUM_NO_D2_B31 = SUM(SUM_NO_D2_B31) 

INTO #SALARY_SUM2
FROM #SALARY_SUM_DATA
GROUP BY
	Month(PERIOD_BEGIN)

--
DROP TABLE #SALARY_SUM_DATA	

--ОСТАТКИ ПО СЧЁТУ 303.09 (ВЗНОСЫ ПО ДОПТАРИФАМ) НА НАЧАЛО ГОДА
CREATE TABLE #REST_30309_KAU (LINK_KAU INT, REST NUMERIC(18,2))

DECLARE @Cur1 CURSOR, @LINK_ACC INT
SET @Cur1 = CURSOR FORWARD_ONLY

FOR SELECT LINK FROM dbo.S_ACCOUNTS WHERE CODE LIKE '303.09%'

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @LINK_ACC
WHILE (@@fetch_status <> -1)
BEGIN

	IF (@@fetch_status <> -2)
	BEGIN

			INSERT INTO #REST_30309_KAU (LINK_KAU, REST) 
			SELECT KAU, REST = coalesce(sum(K_SUMMA)-sum(D_SUMMA),0) FROM dbo.ARestGroupedTableByDate (@START_DATE, @LINK_ACC, DEFAULT) GROUP BY KAU

	END

	FETCH NEXT FROM @Cur1 INTO @LINK_ACC
END

CLOSE @Cur1
DEALLOCATE @Cur1

--ОСТАТКИ ПО СЧЁТУ 303.10 (ВЗНОСЫ ПО ДОПТАРИФАМ) НА НАЧАЛО ГОДА
CREATE TABLE #REST_30310(REST NUMERIC(18,2))

DECLARE @Cur2 CURSOR
SET @Cur2 = CURSOR FORWARD_ONLY

FOR SELECT LINK FROM dbo.S_ACCOUNTS WHERE CODE LIKE '303.10%'

OPEN @Cur2
FETCH NEXT FROM @Cur2 INTO @LINK_ACC
WHILE (@@fetch_status <> -1)
BEGIN

	IF (@@fetch_status <> -2)
	BEGIN

			INSERT INTO #REST_30310 (REST) 
			SELECT REST = coalesce(sum(K_SUMMA)-sum(D_SUMMA),0) FROM dbo.ARestGroupedTableByDate (@START_DATE, @LINK_ACC, DEFAULT)

	END

	FETCH NEXT FROM @Cur2 INTO @LINK_ACC
END

CLOSE @Cur2
DEALLOCATE @Cur2

--ОСТАТКИ ПО СЧЁТУ 303.07 (ВЗНОСЫ ПО ДОПТАРИФАМ) НА НАЧАЛО ГОДА
CREATE TABLE #REST_30307(REST NUMERIC(18,2))

DECLARE @Cur3 CURSOR
SET @Cur3 = CURSOR FORWARD_ONLY

FOR SELECT LINK FROM dbo.S_ACCOUNTS WHERE CODE LIKE '303.07%'

OPEN @Cur3
FETCH NEXT FROM @Cur3 INTO @LINK_ACC
WHILE (@@fetch_status <> -1)
BEGIN

	IF (@@fetch_status <> -2)
	BEGIN

			INSERT INTO #REST_30307 (REST) 
			SELECT REST = coalesce(sum(K_SUMMA)-sum(D_SUMMA),0) FROM dbo.ARestGroupedTableByDate (@START_DATE, @LINK_ACC, DEFAULT)

	END

	FETCH NEXT FROM @Cur3 INTO @LINK_ACC
END

CLOSE @Cur3
DEALLOCATE @Cur3

--ОСТАТОК НА НАЧАЛО ГОДА ПО КАУ ДЛЯ ВЗНОСОВ ПО ДОПТАРИФУ №1
DECLARE @KAU_S1 INT, @KAU_S2 INT

SET @KAU_S1 = (SELECT TOP 1 LINK_KAU FROM dbo.REPORT_OPTIONS WHERE Code = 'kau_RSV1_s1')
SET @KAU_S2 = (SELECT TOP 1 LINK_KAU FROM dbo.REPORT_OPTIONS WHERE Code = 'kau_RSV1_s2')

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6, C7, C8)
SELECT '100', 
	C3 = ISNULL((SELECT SUM(REST) FROM #REST_30310),0),  
	0,0, 
	С6 = ISNULL((SELECT SUM(REST) FROM #REST_30309_KAU WHERE LINK_KAU = @KAU_S1),0), 
	С7 = ISNULL((SELECT SUM(REST) FROM #REST_30309_KAU WHERE LINK_KAU = @KAU_S2),0),
	C8 = ISNULL((SELECT SUM(REST) FROM #REST_30307),0)

/*Страховая часть*/
CREATE TABLE #PLAT (VID TINYINT, Y INT, MON TINYINT, SUMMA NUMERIC(18,2), Y_p INT, MON_p TINYINT)

	exec dbo.BufferClear 'DT'
	exec dbo.BufferClear 'KT'

	INSERT INTO BUFFER (link, id)
	select link, 'DT' from s_accounts where cSinth = '303' and cAnalit = '10' --С 290экр НЕ ДОЛЖЕН БРАТЬСЯ

	INSERT INTO BUFFER (link, id)
	select link, 'KT' from s_accounts where cSinth = '304' and cAnalit = '05'

	INSERT INTO BUFFER (link, id)
	select link, 'KT' from s_accounts where cSinth = '201' and (cAnalit = '11' or cAnalit = '21' or cAnalit = '27')

	INSERT INTO #PLAT (VID, Y, MON, SUMMA,Y_P,MON_P)
	SELECT 1,
		Y = CONVERT(INT,YEAR(p.DATE_PROV)), 
		MON = CONVERT(INT,MONTH(p.DATE_PROV)),
		P.SUMMA,  
		Y_P = CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,3,'.')), 
		MON_P = CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.'))
	from 
		dbo.AProvByBufferConditionsShortDate(@BYearDate, @end_date, 'DT', 'KT') P	
		inner join dbo.DOCUMENTS_PAY_ADD PA on P.link = PA.link
		inner join dbo.g_prov G on G.link = PA.link
		LEFT JOIN dbo.KOSGU DG ON DG.LINK = P.DT_EKR
	WHERE
		P.DEP_LINK = @DEP_LINK
		AND
		G.DEP = @DEP_LINK
		--AND
		--CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.')) <= @M
		--AND
		--CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,3,'.')) = @Y
		AND
		DG.CODE <> '290'

	exec dbo.BufferClear 'DT'
	exec dbo.BufferClear 'KT'



/* DECLARE @Res float
SET @Res = 0
 exec [dbo].RSA_RSV_1_14_PFR_PREPARE @Res output, '', '20140101', '20140331', 3, 0, 2494
 select @Res 	
*/


INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6, C7, C8)
SELECT '140',
	С3 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT WHERE Y >= @nYEAR and (Y_p >= @nYEAR OR Y_p = 0 )),0), 
	С4 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT WHERE Y = @nYEAR AND Y <> 0 and Y_p < @nYEAR AND Y_p <> 0),0),
	 0, 0,0, 0

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6, C7, C8)
SELECT '141', 
	С3 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT WHERE Y >= @nYEAR  and MON = @nMONTH1  and (Y_p >= @nYEAR OR Y_p = 0 )),0), 
	С4 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT WHERE Y = @nYEAR AND Y <> 0 AND MON = @nMONTH1 and Y_p < @nYEAR AND Y_p <> 0),0),
	 0, 0,0,0
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6, C7, C8)
SELECT '142',
	С3 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT WHERE Y >= @nYEAR and MON = @nMONTH2 and (Y_p >= @nYEAR OR Y_p = 0 )),0), 
	С4 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT WHERE Y = @nYEAR AND Y <> 0 AND MON = @nMONTH2 and Y_p < @nYEAR AND Y_p <> 0),0),
	 0, 0,0,0	
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6, C7, C8)
SELECT '143', 
	С3 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT WHERE Y >= @nYEAR and MON = @nMONTH3 and (Y_p >= @nYEAR OR Y_p = 0 )),0), 
	С4 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT WHERE Y = @nYEAR AND Y <> 0 AND MON = @nMONTH3 and Y_p < @nYEAR AND Y_p <> 0),0),
	 0, 0,0,0
	 
/*Накопительная часть (для годов ниже 2014)*/
CREATE TABLE #PLAT_NAK (VID TINYINT, Y INT, MON TINYINT, SUMMA NUMERIC(18,2), Y_P INT, MON_P TINYINT)

	exec dbo.BufferClear 'DT'
	exec dbo.BufferClear 'KT'

	INSERT INTO BUFFER (link, id)
	select link, 'DT' from s_accounts where cSinth = '303' and cAnalit = '11' 
	
	INSERT INTO BUFFER (link, id)
	select link, 'KT' from s_accounts where cSinth = '304' and cAnalit = '05'

	INSERT INTO BUFFER (link, id)
	select link, 'KT' from s_accounts where cSinth = '201' and (cAnalit = '11' or cAnalit = '21' or cAnalit = '27')

	INSERT INTO #PLAT_NAK (VID, Y, MON, SUMMA, Y_P, MON_P)
	SELECT 1,
		Y = CONVERT(INT,YEAR(p.DATE_PROV)), 
		MON = CONVERT(INT,MONTH(p.DATE_PROV)), 
		P.SUMMA,
		Y_P = CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,3,'.')), 
		MON_P = CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.'))
	from 
		dbo.AProvByBufferConditionsShortDate(@START_DATE, @end_date, 'DT', 'KT') P	
		inner join dbo.DOCUMENTS_PAY_ADD PA on P.link = PA.link
		inner join dbo.g_prov G on G.link = PA.link
		LEFT JOIN dbo.KOSGU DG ON DG.LINK = P.DT_EKR
	WHERE
		P.DEP_LINK = @DEP_LINK
		AND
		G.DEP = @DEP_LINK
		--AND
		--CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.')) <= @M
		--AND
		--CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,3,'.')) = @Y
		AND
		DG.CODE >= '211'
		AND DG.CODE <'290'

	exec dbo.BufferClear 'DT'
	exec dbo.BufferClear 'KT'


UPDATE #RES2
SET C5 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT_NAK WHERE Y = @nYEAR AND Y <> 0 and Y_p < @nYEAR AND Y_p <> 0),0)
FROM #RES2
WHERE code_str = '140'

UPDATE #RES2
SET C5 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT_NAK WHERE Y = @nYEAR AND Y <> 0 AND MON = @nMONTH1 and Y_p < @nYEAR AND Y_p <> 0),0)
FROM #RES2
WHERE code_str = '141'
UPDATE #RES2
SET C5 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT_NAK WHERE Y = @nYEAR AND Y <> 0 AND MON = @nMONTH2 and Y_p < @nYEAR AND Y_p <> 0),0)
FROM #RES2
WHERE code_str = '142'
UPDATE #RES2
SET C5 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT_NAK WHERE Y = @nYEAR AND Y <> 0 AND MON = @nMONTH3 and Y_p < @nYEAR AND Y_p <> 0),0)
FROM #RES2
WHERE code_str = '143'

DROP TABLE #PLAT
DROP TABLE #PLAT_NAK
--Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соот-ветствии со ст. 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ
-- с 2012 года расчет ведется по физ лицам , инвалидам и ЕНВД вместе 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '200', 
			 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))	 					 	 					 			 					 
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
FROM #SALARY_SUM2		 


--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '201',
	
	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 3),0)) 
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 6),0))			
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 9),0))			
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 9),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 10) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 10),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 11) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 11),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 12) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 12),0))			
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = @nMONTH1),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = @nMONTH2),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = @nMONTH3),0))





----- Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ 
----- (отражаются суммы фактически произведенных и документально подтвержденных расходов, связанных с извлечением доходов, 
-----  полученных по договору авторского заказа, договору об отчуждении исключительного права на произведения науки, литературы, 
-----  искусства, издательскому лицензионному договору, лицензионному договору о предоставлении права использования произведения науки, 
-----  литературы, искусства или суммы расходов, которые не могут быть подтверждены документально и принимаемые к вычету)
-----  Сейчас заполняем нулями
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '202',
	
	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),0)
		WHEN 6 THEN
			CONVERT(numeric(18,2),0)
		WHEN 9 THEN
			CONVERT(numeric(18,2),0)
		WHEN 12 THEN
			CONVERT(numeric(18,2),0)
	END,	
	
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0)

-----


--Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную ст. 8 Федерального закона
DECLARE @LIMIT NUMERIC(18,2)

SELECT @LIMIT = MAX(S.PREDEL)
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3
WHERE 
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3 AND [DATE] < @END_DATE ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
	
SET @LIMIT = ISNULL(@LIMIT,0)

--  тариф, применяемый  свыше установленного предела величины базы (%)

-- по наемным рабочим
-- так как с 2014 года процент ставок одинаковый  для всех возрастов , берем процент  по возрасту "с 1967"
DECLARE 
	@PERCENT NUMERIC(18,2),
	-- накопительной части с 2014 года нет
	-- @PERCENT_N NUMERIC(18,2)  -- 
	@PERCENT_OMS NUMERIC(18,2), @IPERCENT_OMS NUMERIC(18,2) 
	
SELECT 
	@PERCENT = S.PERCENT3
FROM 
	dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 
WHERE
	predel = @LIMIT
	and tarif =1
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 AND [DATE] < @END_DATE where 	s1.predel = @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT3 > 0
	
SET @PERCENT = ISNULL(@PERCENT,0)	

--
SELECT @PERCENT_OMS = S.PERCENT1
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3
WHERE
	predel = @LIMIT
	and tarif =1
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3 AND [DATE] < @END_DATE where 	s1.predel = @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0

--
SELECT @IPERCENT_OMS = S.PERCENT1
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3
WHERE
	predel = @LIMIT
	and tarif =3
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3 AND [DATE] < @END_DATE where 	s1.predel = @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0	

SET @PERCENT_OMS = ISNULL(@PERCENT_OMS,0)	
SET @IPERCENT_OMS = ISNULL(@IPERCENT_OMS,0)

-- по инвалидам
   --- страховая часть 
DECLARE @IPERCENT NUMERIC(28,2)
SELECT @IPERCENT = S.PERCENT3
FROM 
	dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 
WHERE
	predel = @LIMIT
	and tarif = 3
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 AND [DATE] < @END_DATE where 	s1.predel = @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
SET @IPERCENT = ISNULL(@IPERCENT,0)

	
   --- накопительная часть  с 2014 года отсутствует 
/*   */
-----

SELECT MON = 1, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1 FROM #SPR_ESN WHERE WAY_CALC = 6 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 2, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 2 AND @nMONTH3 >= 3 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 3, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 3 AND @nMONTH3 >= 3 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 4, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 4 AND @nMONTH3 >= 6 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 5, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 5 AND @nMONTH3 >= 6 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 6, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 6 AND @nMONTH3 >= 6 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 7, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 7 AND @nMONTH3 >= 9 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 8, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 8 AND @nMONTH3 >= 9 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 9, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 9 AND @nMONTH3 >= 9 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 10, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 10 AND @nMONTH3 >= 12 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 11, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 11 AND @nMONTH3 >= 12 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 12, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 12 AND @nMONTH3 >= 12 AND I = 1  GROUP BY REF_PHYS_PERS

SELECT DISTINCT T.REF_PHYS_PERS, M.M, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
INTO #SPR_ESN2
FROM 
	#SPR_ESN1 T INNER JOIN dbo.months_ex(@BYearDate, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1 T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1
--WHERE
--	(ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)) > 0

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '203',

	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 9) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 10) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 11) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 12) ,0))										
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH3) ,0))

--Начислено страховых взносов на обяза-тельное пенсионное страхование
--страховая часть

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '205',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18,2),ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 ) ,0)) 
	ELSE
		CONVERT(numeric(18,2),ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0))
	END,	
	CONVERT(numeric(18,2),ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0))


DECLARE @PERC1 NUMERIC(28,2), @IPERC1 NUMERIC(28,2)
-- для рабочих
SELECT @PERC1 = S.PERCENT1

FROM 
	dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 
WHERE
	predel > @LIMIT
	and 
	tarif = 1
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 AND [DATE] < @END_DATE where 	s1.predel > @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
SET @PERC1 = ISNULL(@PERC1,0)	
-- для инвалидов
SELECT @IPERC1 = S.PERCENT1

FROM 
	dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 
WHERE
	predel > @LIMIT
	and 
	tarif = 3
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 AND [DATE] < @END_DATE where 	s1.predel > @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
SET @IPERC1 = ISNULL(@IPERC1,0)	


--- с сумм, превышающих предельную величину базы	
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '206',
	CASE WHEN @nMONTH3 > 3 THEN
		(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2) ,0)) * @PERC1)/100
	ELSE
		((CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE  M = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH3) ,0))) * @PERC1)/100 	
	END,	
	(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH1) ,0)) * @PERC1)/100,
	(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH2) ,0)) * @PERC1)/100,
	(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH3) ,0)) * @PERC1)/100	


update #RES2
	set C3 = (c3 - (select c3 from #RES2 where code_str = '206' )) , 
	C4 = (c4 - (select c4 from #RES2 where code_str = '206' )),
	C5= (c5 - (select c5 from #RES2 where code_str = '206' )),
	C6= (c6 - (select c6 from #RES2 where code_str = '206' ))
 from #RES2 
 where code_str = '205'

--SELECT * FROM #SPR_ESN WHERE  MONTH_BASE >= @nMONTH1 AND I = 1
--SELECT * FROM #SPR_ESN WHERE  MONTH_BASE >= @nMONTH1 AND I = 2

-- Количество чел , кому начислялись страховые взносы
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '207',
	CASE WHEN @nMONTH3 > 3 THEN
		ISNULL(
			(SELECT MAX(CNT)
			FROM
				(SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 1 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 2 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 3 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 4 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 5 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 6 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 7 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 8 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 9 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 10 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 11 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 12 AND MONTH_BASE <= @nMONTH3) T
			),0)
	ELSE
		ISNULL(
			(SELECT MAX(CNT)
			FROM
				(SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = @nMONTH1
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = @nMONTH2
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = @nMONTH3) T
			),0)
	END,	
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = @nMONTH3) ,0) 		


-- Количество чел , чей лимит превышен
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '208',
	CASE WHEN @nMONTH3 > 3 THEN
		ISNULL(
			(SELECT MAX(CNT)
			FROM
				(SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and M = 1 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 2 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 3 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 4 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 5 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 6 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 7 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 8 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 9 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 10 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 11 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 12 AND M <= @nMONTH3) T
			),0)
	ELSE
		ISNULL(
			(SELECT MAX(CNT)
			FROM
				(SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = @nMONTH1
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = @nMONTH2
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = @nMONTH3) T
			),0)
	END,	
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = @nMONTH3) ,0) 	
	
----- на обязательное медицинское страхование
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '210', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))	 					 	 					 			 					 
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
FROM #SALARY_SUM2		 


--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '211',
	
	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 3),0))
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 6),0))			
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 9),0))			
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 9),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 10) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 10),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 11) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 11),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = 12) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 12),0))			
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = @nMONTH1),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = @nMONTH2),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = @nMONTH3),0))

---- Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '212',

	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),0)
		WHEN 6 THEN
			CONVERT(numeric(18,2),0)
		WHEN 9 THEN
			CONVERT(numeric(18,2),0)
		WHEN 12 THEN
			CONVERT(numeric(18,2),0)
	END,
		
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0)


SELECT MON = 1, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1M FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS 
INSERT INTO #SPR_ESN1M SELECT MON = 2, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 2 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 3, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 3 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 4, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 4 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 5, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 5 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 6, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 6 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 7, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 7 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 8, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 8 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 9, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 9 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 10, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 10 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 11, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 11 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 12, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 12 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS

SELECT DISTINCT T.REF_PHYS_PERS, M.M, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
INTO #SPR_ESN2M 
FROM 
	#SPR_ESN1M T INNER JOIN dbo.months_ex(@BYearDate, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1M T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1M T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1

---  Суммы, превышающие предельную величину базы для начисления страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '213',

	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 9) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 10) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 11) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 12) ,0))										
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = @nMONTH3) ,0))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '215',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3  AND I = 1) ,0))
	ELSE
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0))	
	END,	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0))	


--ВЫРАВНИВАНИЕ ПОГРЕШНОСТИ ПО ОСНОВНОМУ ТАРИФУ
/*
--Способ заполнения страховых взносов
Выриант №1. Сумма всзносов по организации рассчитывается  по формулам расчёта для РСВ-1 от общих сумм дохода и необлагаемых сумм. 
Выриант №2. Сумма взносов по организации рассчитывается как сумма взносов, начисленных по физлицам. 
Выриант №3. Сумма взносов по организации рассчитывается как сумма взносов, начисленных по физлицам. 
Но при этом для того, чтобы выполнялись контрольные соотношения по форме, выполняется подгон необлагаемых сумм.
*/
DECLARE @SALARY_OPTIONS_OPT6_1 INT 
SET @SALARY_OPTIONS_OPT6_1 =  dbo.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPT6_1')

------------------------------------------------------------------------------------
----- расчет погрешностей для 2014 года
	IF ISNULL(@PERCENT,0) > 0
	BEGIN
		--Вычисление погрешности для страховой части	
		SELECT 
			@C3S = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 204 = 
						(CASE WHEN CODE_STR = '200' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '201' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '202' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '203' THEN C3 ELSE 0 END)
					)) * @PERCENT/100
					- CONVERT(NUMERIC(18,6), (SELECT SUM(C3) FROM #RES2 WHERE CODE_STR = '205'))
				) / (@PERCENT/100)	
			),

			@C3SS = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 204 = 
						(CASE WHEN CODE_STR = '200' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '201' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '202' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '203' THEN C3 ELSE 0 END)
					)) * @PERCENT/100
				)
			),

			@C4S = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 204 = 
						(CASE WHEN CODE_STR = '200' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '201' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '202' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '203' THEN C4 ELSE 0 END)
					)) * @PERCENT/100
					- CONVERT(NUMERIC(18,6),(SELECT SUM(C4) FROM #RES2 WHERE CODE_STR = '205'))
				) / (@PERCENT/100)	
			),

			@C4SS = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 204 = 
						(CASE WHEN CODE_STR = '200' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '201' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '202' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '203' THEN C4 ELSE 0 END)
					)) * @PERCENT/100
				)
			),			
			
			@C5S = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 204 = 
						(CASE WHEN CODE_STR = '200' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '201' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '202' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '203' THEN C5 ELSE 0 END)
					)) * @PERCENT/100
					- CONVERT(NUMERIC(18,6),(SELECT SUM(C5) FROM #RES2 WHERE CODE_STR = '205'))
				) / (@PERCENT/100)	
			),		

			@C5SS = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 204 = 
						(CASE WHEN CODE_STR = '200' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '201' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '202' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '203' THEN C5 ELSE 0 END)
					)) * @PERCENT/100
				)
			),					

			@C6S = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 204 = 
						(CASE WHEN CODE_STR = '200' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '201' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '202' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '203' THEN C6 ELSE 0 END)
					)) * @PERCENT/100
					- CONVERT(NUMERIC(18,6), (SELECT SUM(C6) FROM #RES2 WHERE CODE_STR = '205'))
				) / (@PERCENT/100)						
			),

			@C6SS = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 204 = 
						(CASE WHEN CODE_STR = '200' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '201' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '202' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '203' THEN C6 ELSE 0 END)
					)) * @PERCENT/100
				)
			)	
			
		FROM #RES2
		WHERE
			CODE_STR IN ('200', '201', '202', '203' )

		IF @SALARY_OPTIONS_OPT6_1 = 1
		BEGIN
			UPDATE #RES2
			SET
				C3 = CASE WHEN @nMONTH3 = 3 THEN ISNULL(@C4SS,0) + ISNULL(@C5SS,0) + ISNULL(@C6SS,0) 
						ELSE ISNULL(@C3SS,0)
					END,			
				C4 = ISNULL(@C4SS,0),
				C5 = ISNULL(@C5SS,0),
				C6 = ISNULL(@C6SS,0)
			WHERE 
				CODE_STR = '205'
			
		END
------------------------------------------------------------------------------------
		--Корректируем необлагаемые суммы на копейки округления
		
		--Досчет по базе закомментарил
		 
		IF @SALARY_OPTIONS_OPT6_1 = 3
		BEGIN
			UPDATE #RES2
			SET
				C3 = C3 + ISNULL(@C3S,0),
				C4 = C4 + ISNULL(@C4S,0),
				C5 = C5 + ISNULL(@C5S,0),
				C6 = C6 + ISNULL(@C6S,0)			 
			WHERE 
				CODE_STR = '201'
		END		
	
	END	

--- накопительной части в 2014 нет
	--IF @SALARY_OPTIONS_OPT6_1 = 1
	--BEGIN
	--		UPDATE #RES2
	--		SET
	--			C3 = CASE WHEN @nMONTH3 = 3 THEN ISNULL(@C4NS,0) + ISNULL(@C5NS,0) + ISNULL(@C6NS,0) ELSE ISNULL(@C3NS,0) END,
	--			C4 = ISNULL(@C4NS,0),
	--			C5 = ISNULL(@C5NS,0),
	--			C6 = ISNULL(@C6NS,0)
	--		WHERE 
	--			CODE_STR = '251'
	--END


	--IF @SALARY_OPTIONS_OPT6_1 = 3
	--BEGIN
	--	UPDATE #RES2
	--	SET
	--		C3 = C3 + ISNULL(@C3N,0),
	--		C4 = C4 + ISNULL(@C4N,0),
	--		C5 = C5 + ISNULL(@C5N,0),
	--		C6 = C6 + ISNULL(@C6N,0)			 
	--	WHERE 
	--		CODE_STR = '212'
	--END		

--END		


IF ISNULL(@PERCENT_OMS,0) > 0
BEGIN
	--Вычисление погрешности для ОМС	
	SELECT 
		@C3N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 215 = 
					(CASE WHEN CODE_STR = '210' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '211' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '213' THEN C3 ELSE 0 END)
				) * @PERCENT_OMS/100
				- (SELECT SUM(C3) FROM #RES2 WHERE CODE_STR = '215')
			) / (@PERCENT_OMS/100)
		),
		@C3NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 215 = 
					(CASE WHEN CODE_STR = '210' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '211' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '213' THEN C3 ELSE 0 END)
				) * @PERCENT_OMS/100
			)
		),
		@C4N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 215 = 
					(CASE WHEN CODE_STR = '210' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '211' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '213' THEN C4 ELSE 0 END)
				) * @PERCENT_OMS/100
				- (SELECT SUM(C4) FROM #RES2 WHERE CODE_STR = '215')
			) / (@PERCENT_OMS/100)
		),
		@C4NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 215 = 
					(CASE WHEN CODE_STR = '210' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '211' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '213' THEN C4 ELSE 0 END)
				) * @PERCENT_OMS/100
			)
		),
		@C5N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 215 = 
					(CASE WHEN CODE_STR = '210' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '211' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '213' THEN C5 ELSE 0 END)
				) * @PERCENT_OMS/100
				- (SELECT SUM(C5) FROM #RES2 WHERE CODE_STR = '215')
			) / (@PERCENT_OMS/100)
		),
		@C5NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 215 = 
					(CASE WHEN CODE_STR = '210' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '211' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '213' THEN C5 ELSE 0 END)
				) * @PERCENT_OMS/100
			)
		),		
		@C6N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 215 = 
					(CASE WHEN CODE_STR = '210' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '211' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '213' THEN C6 ELSE 0 END)
				) * @PERCENT_OMS/100
				- (SELECT SUM(C6) FROM #RES2 WHERE CODE_STR = '215')
			) / (@PERCENT_OMS/100)
		),
		@C6NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 215 = 
					(CASE WHEN CODE_STR = '210' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '211' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '213' THEN C6 ELSE 0 END)
				) * @PERCENT_OMS/100
			)
		)					
	FROM #RES2
	WHERE
		CODE_STR IN ('210', '211', '212', '213')

	IF @SALARY_OPTIONS_OPT6_1 = 1
	BEGIN
		UPDATE #RES2
		SET
			C3 = CASE WHEN @nMONTH3 = 3 THEN ISNULL(@C4NS,0) + ISNULL(@C5NS,0) + ISNULL(@C6NS,0) ELSE ISNULL(@C3NS,0) END,
			C4 = ISNULL(@C4NS,0),
			C5 = ISNULL(@C5NS,0),
			C6 = ISNULL(@C6NS,0)
		WHERE 
			CODE_STR = '215'
		
	END

	--Корректируем необлагаемые суммы на копейки округления
	IF @SALARY_OPTIONS_OPT6_1 = 3
	BEGIN
		UPDATE #RES2
		SET
			C3 = C3 + ISNULL(@C3N,0),
			C4 = C4 + ISNULL(@C4N,0),
			C5 = C5 + ISNULL(@C5N,0),
			C6 = C6 + ISNULL(@C6N,0)			 
		WHERE 
			CODE_STR = '211'
	END		
END		

--->>>--->>>>>>>
	-----ПО ИНВАЛИДАМ 
--->>>--->>>>>>>
--Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соот-ветствии со ст. 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ
-- с 2012 года расчет ведется по физ лицам , инвалидам и ЕНВД вместе 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2000', 
			 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL_I ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL_I ELSE 0 END))	 					 	 					 			 					 
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL_I ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL_I ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL_I ELSE 0 END))
FROM #SALARY_SUM2		 

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2010',
	
	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 3),0))
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 6),0))			
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND I = 1 AND E = 0 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 9),0))			
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 9),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 10) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 10),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 11) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 11),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 12) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 12),0))			
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = @nMONTH1),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = @nMONTH2),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = @nMONTH3),0))


--	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH1),0)),
/* DECLARE @Res float
SET @Res = 0
 exec RSA_RSV_1_13_PFR_PREPARE @Res output, '', '20130401', '20130630', 2, 2, 170
 select @Res 	
*/
----- Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ 
----- (отражаются суммы фактически произведенных и документально подтвержденных расходов, связанных с извлечением доходов, 
-----  полученных по договору авторского заказа, договору об отчуждении исключительного права на произведения науки, литературы, 
-----  искусства, издательскому лицензионному договору, лицензионному договору о предоставлении права использования произведения науки, 
-----  литературы, искусства или суммы расходов, которые не могут быть подтверждены документально и принимаемые к вычету)
-----  Сейчас заполняем нулями
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2020',
	
	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),0)
		WHEN 6 THEN
			CONVERT(numeric(18,2),0)
		WHEN 9 THEN
			CONVERT(numeric(18,2),0)
		WHEN 12 THEN
			CONVERT(numeric(18,2),0)
	END,	
	
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0)
	
----


SELECT MON = 1, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1I FROM #SPR_ESN WHERE WAY_CALC = 6 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 2, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 2 AND @nMONTH3 >= 3 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 3, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 3 AND @nMONTH3 >= 3 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 4, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 4 AND @nMONTH3 >= 6 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 5, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 5 AND @nMONTH3 >= 6 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 6, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 6 AND @nMONTH3 >= 6 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 7, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 7 AND @nMONTH3 >= 9 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 8, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 8 AND @nMONTH3 >= 9 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 9, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 9 AND @nMONTH3 >= 9 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 10, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 10 AND @nMONTH3 >= 12 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 11, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 11 AND @nMONTH3 >= 12 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 12, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 12 AND @nMONTH3 >= 12 AND I = 2  GROUP BY REF_PHYS_PERS

SELECT DISTINCT T.REF_PHYS_PERS, M.M, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
INTO #SPR_ESN2I
FROM 
	#SPR_ESN1I T INNER JOIN dbo.months_ex(@BYearDate, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1I T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1I T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1
--WHERE
--	(ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)) > 0


-- Суммы превышающие величину базы 

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2030',

	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 9) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 10) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 11) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 12) ,0))										
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH3) ,0))

--Начислено страховых взносов на обяза-тельное пенсионное страхование
--страховая часть

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2050',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 ) ,0)) 
	ELSE
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0))
	END,	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0))


--- с сумм, превышающих предельную величину базы	
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2060',
	CASE WHEN @nMONTH3 > 3 THEN
		(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I) ,0)) * @IPERC1)/100
	ELSE
		((CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE  M = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH3) ,0))) * @IPERC1)/100 	
	END,	
	(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH1) ,0)) * @IPERC1)/100,
	(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH2) ,0)) * @IPERC1)/100,
	(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH3) ,0)) * @IPERC1)/100	


update #RES2
	set C3 = (c3 - (select c3 from #RES2 where code_str = '2060' )) , 
	C4 = (c4 - (select c4 from #RES2 where code_str = '2060' )),
	C5= (c5 - (select c5 from #RES2 where code_str = '2060' )),
	C6= (c6 - (select c6 from #RES2 where code_str = '2060' ))
 from #RES2 
 where code_str = '2050'

-- Количество чел , чей лимит НЕ превышен
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2070',
	CASE WHEN @nMONTH3 > 3 THEN
		ISNULL(
			(SELECT MAX(CNT)
			FROM
				(SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and MONTH_BASE = 1 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 2 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 3 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 4 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 5 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 6 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 7 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 8 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 9 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 10 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 11 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 12 AND MONTH_BASE <= @nMONTH3) T
			),0)
	ELSE
		ISNULL(
			(SELECT MAX(CNT)
			FROM
				(SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = @nMONTH1
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = @nMONTH2
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = @nMONTH3) T
			),0)
	END,	
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = @nMONTH3) ,0) 		

-- Количество чел , чей лимит превышен

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2080',
	CASE WHEN @nMONTH3 > 3 THEN
		ISNULL(
			(SELECT MAX(CNT)
			FROM
				(SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and M = 1 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 2 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 3 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 4 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 5 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 6 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 7 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 8 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 9 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 10 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 11 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 12 AND M <= @nMONTH3) T
			),0)
	ELSE
		ISNULL(
			(SELECT MAX(CNT)
			FROM
				(SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = @nMONTH1
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = @nMONTH2
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = @nMONTH3) T
			),0)
	END,	
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = @nMONTH3) ,0) 	
	
----- на обязательное медицинское страхование
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2100', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL_I ELSE 0 END))	 					 	 					 			 					 
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL_I ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL_I ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL_I ELSE 0 END))
FROM #SALARY_SUM2		 


--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2110',
	
	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 3),0))
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 6),0))			
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 9),0))			
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 9),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 10) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 10),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 11) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 11),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 12) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 12),0))			
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = @nMONTH1),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = @nMONTH2),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = @nMONTH3),0))

---- Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2120',

	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),0)
		WHEN 6 THEN
			CONVERT(numeric(18,2),0)
		WHEN 9 THEN
			CONVERT(numeric(18,2),0)
		WHEN 12 THEN
			CONVERT(numeric(18,2),0)
	END,
		
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0)


SELECT MON = 1, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1IM FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 2, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 2 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 3, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 3 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 4, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 4 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 5, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 5 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 6, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 6 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 7, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 7 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 8, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 8 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 9, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 9 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 10, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 10 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 11, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 11 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 12, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 12 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS

SELECT DISTINCT T.REF_PHYS_PERS, M.M, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
INTO #SPR_ESN2IM 
FROM 
	#SPR_ESN1IM T INNER JOIN dbo.months_ex(@BYearDate, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1IM T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1IM T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1

---  Суммы, превышающие предельную величину базы для начисления страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2130',

	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 9) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 10) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 11) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 12) ,0))										
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = @nMONTH3) ,0))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2150',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3  AND I = 2) ,0))
	ELSE
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0))	
	END,	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0))	


--ВЫРАВНИВАНИЕ ПОГРЕШНОСТИ ПО ИНВАЛИДАМ
/*
--Способ заполнения страховых взносов
Выриант №1. Сумма всзносов по организации рассчитывается  по формулам расчёта для РСВ-1 от общих сумм дохода и необлагаемых сумм. 
Выриант №2. Сумма взносов по организации рассчитывается как сумма взносов, начисленных по физлицам. 
Выриант №3. Сумма взносов по организации рассчитывается как сумма взносов, начисленных по физлицам. 
Но при этом для того, чтобы выполнялись контрольные соотношения по форме, выполняется подгон необлагаемых сумм.
*/

	--Вычисление погрешности для накопительной части	
	/* в 2014 не используется*/	
	
IF ISNULL(@IPERCENT,0) > 0
BEGIN
	--Вычисление погрешности для страховой части	
	SELECT 
		@C3S = CONVERT(NUMERIC(18,2),
			(
				CONVERT(NUMERIC(18,6), SUM( --Стр 2040 = 
					(CASE WHEN CODE_STR = '2000' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2010' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2020' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2030' THEN C3 ELSE 0 END)
				)) * @IPERCENT/100
				- CONVERT(NUMERIC(18,6), (SELECT SUM(C3) FROM #RES2 WHERE CODE_STR = '2050'))
			) / (@IPERCENT/100)	
		),
		@C3SS = CONVERT(NUMERIC(18,2),
			(
				CONVERT(NUMERIC(18,6), SUM( --Стр 2040 = 
					(CASE WHEN CODE_STR = '2000' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2010' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2020' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2030' THEN C3 ELSE 0 END)
				)) * @IPERCENT/100
			)
		),
		@C4S = CONVERT(NUMERIC(18,2),
			(
				CONVERT(NUMERIC(18,6), SUM( --Стр 2040 = 
					(CASE WHEN CODE_STR = '2000' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2010' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2020' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2030' THEN C4 ELSE 0 END)
				)) * @IPERCENT/100
				- CONVERT(NUMERIC(18,6),(SELECT SUM(C4) FROM #RES2 WHERE CODE_STR = '2050'))
			) / (@IPERCENT/100)	
		),
		@C4SS = CONVERT(NUMERIC(18,2),
			(
				CONVERT(NUMERIC(18,6), SUM( --Стр 2040 = 
					(CASE WHEN CODE_STR = '2000' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2010' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2020' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2030' THEN C4 ELSE 0 END)
				)) * @IPERCENT/100
			)
		),			
		@C5S = CONVERT(NUMERIC(18,2),
			(
				CONVERT(NUMERIC(18,6), SUM( --Стр 2040 = 
					(CASE WHEN CODE_STR = '2000' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2010' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2020' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2030' THEN C5 ELSE 0 END)
				)) * @IPERCENT/100
				- CONVERT(NUMERIC(18,6),(SELECT SUM(C5) FROM #RES2 WHERE CODE_STR = '2050'))
			) / (@IPERCENT/100)	
		),		
		@C5SS = CONVERT(NUMERIC(18,2),
			(
				CONVERT(NUMERIC(18,6), SUM( --Стр 2040 = 
					(CASE WHEN CODE_STR = '2000' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2010' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2020' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2030' THEN C5 ELSE 0 END)
				)) * @IPERCENT/100
			)
		),
		@C6S = CONVERT(NUMERIC(18,2),
			(
				CONVERT(NUMERIC(18,6), SUM( --Стр 2040 = 
					(CASE WHEN CODE_STR = '2000' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2010' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2020' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2030' THEN C6 ELSE 0 END)
				)) * @IPERCENT/100
				- CONVERT(NUMERIC(18,6), (SELECT SUM(C6) FROM #RES2 WHERE CODE_STR = '2050'))
			) / (@IPERCENT/100)						
		),
		@C6SS = CONVERT(NUMERIC(18,2),
			(
				CONVERT(NUMERIC(18,6), SUM( --Стр 2040 = 
					(CASE WHEN CODE_STR = '2000' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2010' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2020' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2030' THEN C6 ELSE 0 END)
				)) * @IPERCENT/100
			)
		)			
	FROM #RES2
	WHERE
		CODE_STR IN ('2000', '2010', '2020', '2030')

	IF @SALARY_OPTIONS_OPT6_1 = 1
	BEGIN
		UPDATE #RES2
		SET
			C3 = CASE WHEN @nMONTH3 = 3 THEN ISNULL(@C4SS,0) + ISNULL(@C5SS,0) + ISNULL(@C6SS,0) ELSE ISNULL(@C3SS,0) END,
			C4 = ISNULL(@C4SS,0),
			C5 = ISNULL(@C5SS,0),
			C6 = ISNULL(@C6SS,0)
		WHERE 
			CODE_STR = '2050'
		
	END
	
	---Корректируем необлагаемые суммы на копейки округления

	IF @SALARY_OPTIONS_OPT6_1 = 3
	BEGIN		
		UPDATE #RES2
		SET
			C3 = C3 + ISNULL(@C3S,0),
			C4 = C4 + ISNULL(@C4S,0),
			C5 = C5 + ISNULL(@C5S,0),
			C6 = C6 + ISNULL(@C6S,0)			 
		WHERE 
			CODE_STR = '2010'
			
		--UPDATE #RES2
		--SET
		--	C3 = C4 + C5 + C6
		--WHERE 
		--	CODE_STR = '2110'

	END	
	
END	

	-- Накопительную часть в 2014 не считаем 
	--IF @SALARY_OPTIONS_OPT6_1 = 1
	--BEGIN
	--		UPDATE #RES2
	--		SET
	--			C3 = CASE WHEN @nMONTH3 = 3 THEN ISNULL(@C4NS,0) + ISNULL(@C5NS,0) + ISNULL(@C6NS,0) ELSE ISNULL(@C3NS,0) END,
	--			C4 = ISNULL(@C4NS,0),
	--			C5 = ISNULL(@C5NS,0),
	--			C6 = ISNULL(@C6NS,0)
	--		WHERE 
	--			CODE_STR = '2510'
	--END

	--IF @SALARY_OPTIONS_OPT6_1 = 3
	--BEGIN	
	--	UPDATE #RES2
	--	SET
	--		C3 = C3 + ISNULL(@C3N,0),
	--		C4 = C4 + ISNULL(@C4N,0),
	--		C5 = C5 + ISNULL(@C5N,0),
	--		C6 = C6 + ISNULL(@C6N,0)			 
	--	WHERE 
	--		CODE_STR = '2120'
			
		--UPDATE #RES2
		--SET
		--	C3 = C4 + C5 + C6		 
		--WHERE 
		--	CODE_STR = '2120'	
	-- END	
	


IF ISNULL(@IPERCENT_OMS,0) > 0
BEGIN
	--Вычисление погрешности для ОМС	
	SELECT 
		@C3N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2150 = 
					(CASE WHEN CODE_STR = '2100' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2110' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2130' THEN C3 ELSE 0 END)
				) * @IPERCENT_OMS/100
				- (SELECT SUM(C3) FROM #RES2 WHERE CODE_STR = '2150')
			) / (@IPERCENT_OMS/100)
		),

		@C3NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2150  = 
					(CASE WHEN CODE_STR = '2100' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2110' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2130' THEN C3 ELSE 0 END)
				) * @IPERCENT_OMS/100
			)
		),
		
		@C4N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2150 = 
					(CASE WHEN CODE_STR = '2100' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2110' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2130' THEN C4 ELSE 0 END)
				) * @IPERCENT_OMS/100
				- (SELECT SUM(C4) FROM #RES2 WHERE CODE_STR = '2150')
			) / (@IPERCENT_OMS/100)
		),
		@C4NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2150 = 
					(CASE WHEN CODE_STR = '2100' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2110' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2130' THEN C4 ELSE 0 END)
				) * @IPERCENT_OMS/100
			)
		),
		
		@C5N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2150 = 
					(CASE WHEN CODE_STR = '2100' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2110' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2130' THEN C5 ELSE 0 END)
				) * @IPERCENT_OMS/100
				- (SELECT SUM(C5) FROM #RES2 WHERE CODE_STR = '2150')
			) / (@IPERCENT_OMS/100)
		),

		@C5NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2150 = 
					(CASE WHEN CODE_STR = '2100' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2110' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2130' THEN C5 ELSE 0 END)
				) * @IPERCENT_OMS/100
			)
		),
				
		@C6N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2150 = 
					(CASE WHEN CODE_STR = '2100' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2110' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2130' THEN C6 ELSE 0 END)
				) * @IPERCENT_OMS/100
				- (SELECT SUM(C6) FROM #RES2 WHERE CODE_STR = '2150')
			) / (@IPERCENT_OMS/100)
		),
		@C6NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2150 = 
					(CASE WHEN CODE_STR = '2100' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2110' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2130' THEN C6 ELSE 0 END)
				) * @IPERCENT_OMS/100
			)
		)			
	FROM #RES2
	WHERE
		CODE_STR IN ('2100', '2110', '2120', '2130')


	IF @SALARY_OPTIONS_OPT6_1 = 1
	BEGIN
		UPDATE #RES2
		SET
			C3 = CASE WHEN @nMONTH3 = 3 THEN ISNULL(@C4NS,0) + ISNULL(@C5NS,0) + ISNULL(@C6NS,0) ELSE ISNULL(@C3NS,0) END,
			C4 = ISNULL(@C4NS,0),
			C5 = ISNULL(@C5NS,0),
			C6 = ISNULL(@C6NS,0)
		WHERE 
			CODE_STR = '2150'
		
	END

	--Корректируем необлагаемые суммы на копейки округления
	IF @SALARY_OPTIONS_OPT6_1 = 3
	BEGIN
		UPDATE #RES2
		SET
			C3 = C3 + ISNULL(@C3N,0),
			C4 = C4 + ISNULL(@C4N,0),
			C5 = C5 + ISNULL(@C5N,0),
			C6 = C6 + ISNULL(@C6N,0)			 
		WHERE 
			CODE_STR = '2110'
	END	

END		

---------------
/********Расчет допольнительного тарифа страховых взносов  указаных в части 1 статьи 58.3 Федерального закона от 24 июля 2009 г. № 212-ФЗ**********/
/*******Раздел 2.2*********/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '220', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON <= 3 ),0) )
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)  + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
 			 
FROM #SPR_ESN 
WHERE WAY_CALC = 10	 and SP = ''	 

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '221',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN 
WHERE WAY_CALC = 10	 and SP = ''	


------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '282', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT 
	'224',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN 
WHERE WAY_CALC = 10 and SP = ''	

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '225',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 and SP = ''	 and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 and SP = ''	 and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10  and SP = ''	and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10  and SP = ''	and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10  and SP = ''	and  MONTH_BASE = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10  and SP = ''	and  MONTH_BASE = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10  and SP = ''	and  MONTH_BASE = @nMONTH3) ,0) 


/********Расчет допольнительного тарифа страховых взносов  указаных в части 2 статьи 58.3 Федерального закона от 24 июля 2009 г. № 212-ФЗ**********/
/*******Раздел 2.3*********/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '230', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
 			 
FROM #SPR_ESN 
WHERE WAY_CALC = 11	 and SP = ''		 

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '231',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN 
WHERE WAY_CALC = 11	 and SP = ''	

------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '292', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT 
	'234',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN 
WHERE WAY_CALC = 11 and SP = ''	

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '235',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 and SP = ''	 and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 and SP = ''	and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 and SP = ''	and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 and SP = ''	and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 and SP = ''	and  MONTH_BASE = @nMONTH1) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 and SP = ''	and  MONTH_BASE = @nMONTH2) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 and SP = ''	and  MONTH_BASE = @nMONTH3) ,0)



/********2.4. Расчет страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов по доп тарифу 1***********/
/*******Раздел 2.4*** Класс условий труда - опасный, подкласс условий труда - 4  ******/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '240', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON <= 6),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH3),0))
 			 
FROM #SPR_ESN 
WHERE WAY_CALC = 10	AND SP = 'О4'	 


--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '241',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN 
WHERE WAY_CALC = 10	AND SP = 'О4'



------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '243', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT 
	'244',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN 
WHERE WAY_CALC = 10 AND SP = 'О4'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '245',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'О4' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'О4' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'О4' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'О4' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'О4' and  MONTH_BASE = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'О4' and  MONTH_BASE = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'О4' and  MONTH_BASE = @nMONTH3) ,0) 


/********Расчет допольнительного тарифа страховых взносов  по доп тарифу 1**********/
/*******Раздел 2.4**** Класс условий труда - вредный, подкласс условий труда - 3.4  *****/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '246', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
 			 
FROM #SPR_ESN 
WHERE WAY_CALC = 10	 AND SP = 'В3.4'	 

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '247',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN 
WHERE WAY_CALC = 10	 AND SP = 'В3.4'	 

------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '249', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT 
	'250',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN 
WHERE WAY_CALC = 10	 AND SP = 'В3.4'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '251',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.4' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.4' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.4' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.4' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.4' and  MONTH_BASE = @nMONTH1) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.4' and  MONTH_BASE = @nMONTH2) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.4' and  MONTH_BASE = @nMONTH3) ,0)


/*******Раздел 2.4*** Класс условий труда - вредный, подкласс условий труда - 3.3  ******/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '252', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
 			 
FROM #SPR_ESN 
WHERE WAY_CALC = 10	AND SP = 'В3.3'	 

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '253',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN 
WHERE WAY_CALC = 10	AND SP = 'В3.3'


------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '255', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT 
	'256',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN 
WHERE WAY_CALC = 10 AND SP = 'В3.3'



--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '257',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'В3.3' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'В3.3' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'В3.3' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'В3.3' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'В3.3' and  MONTH_BASE = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'В3.3' and  MONTH_BASE = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'В3.3' and  MONTH_BASE = @nMONTH3) ,0) 


/********Расчет допольнительного тарифа страховых взносов  по доп тарифу 1**********/
/*******Раздел 2.4**** Класс условий труда - вредный, подкласс условий труда - 3.2 *****/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '258', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
 			 
FROM #SPR_ESN 
WHERE WAY_CALC = 10	 AND SP = 'В3.2'	 

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '259',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN 
WHERE WAY_CALC = 10	 AND SP = 'В3.2'	 

------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '261', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT 
	'262',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN 
WHERE WAY_CALC = 10	 AND SP = 'В3.2'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '263',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.2' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.2' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.2' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.2' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.2' and  MONTH_BASE = @nMONTH1) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.2' and  MONTH_BASE = @nMONTH2) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.2' and  MONTH_BASE = @nMONTH3) ,0)

/*******Раздел 2.4**** Класс условий труда - вредный, подкласс условий труда - 3.1 *****/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '264', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
 			 
FROM #SPR_ESN 
WHERE WAY_CALC = 10	 AND SP = 'В3.1'	 

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '265',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN 
WHERE WAY_CALC = 10	 AND SP = 'В3.1'	 

------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '267', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT 
	'268',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN 
WHERE WAY_CALC = 10	 AND SP = 'В3.1'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '269',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.1' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.1' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.1' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.1' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.1' and  MONTH_BASE = @nMONTH1) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.1' and  MONTH_BASE = @nMONTH2) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.1' and  MONTH_BASE = @nMONTH3) ,0)


/********2.4. Расчет страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов по доп тарифу 2***********/
/*******Раздел 2.4*** Класс условий труда - опасный, подкласс условий труда - 4  ******/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2400', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
 			 
FROM #SPR_ESN 
WHERE WAY_CALC = 11	AND SP = 'О4'	 



--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2410',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN 
WHERE WAY_CALC = 11	AND SP = 'О4'


------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '2430', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT 
	'2440',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN 
WHERE WAY_CALC = 11 AND SP = 'О4'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2450',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'О4' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'О4' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'О4' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'О4' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'О4' and  MONTH_BASE = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'О4' and  MONTH_BASE = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'О4' and  MONTH_BASE = @nMONTH3) ,0) 


/********Расчет допольнительного тарифа страховых взносов  по доп тарифу 2**********/
/*******Раздел 2.4**** Класс условий труда - вредный, подкласс условий труда - 3.4  *****/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2460', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
 			 
FROM #SPR_ESN 
WHERE WAY_CALC = 11	 AND SP = 'В3.4'	 

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2470',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN 
WHERE WAY_CALC = 11	 AND SP = 'В3.4'	 

------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '249', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT 
	'2500',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN 
WHERE WAY_CALC = 11	 AND SP = 'В3.4'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2510',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE = @nMONTH1) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE = @nMONTH2) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE = @nMONTH3) ,0)


/*******Раздел 2.4*** Класс условий труда - вредный, подкласс условий труда - 3.3  ******/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2520', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
 			 
FROM #SPR_ESN 
WHERE WAY_CALC = 11	AND SP = 'В3.3'	 

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2530',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN 
WHERE WAY_CALC = 10	AND SP = 'В3.3'


------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '2550', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT 
	'2560',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN 
WHERE WAY_CALC = 11 AND SP = 'В3.3'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2570',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE = @nMONTH3) ,0) 


/********Расчет допольнительного тарифа страховых взносов  по доп тарифу 2**********/
/*******Раздел 2.4**** Класс условий труда - вредный, подкласс условий труда - 3.2 *****/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2580', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
 			 
FROM #SPR_ESN 
WHERE WAY_CALC = 11	 AND SP = 'В3.2'	 

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2590',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN 
WHERE WAY_CALC = 11	 AND SP = 'В3.2'	 

------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '2610', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT 
	'2620',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN 
WHERE WAY_CALC = 11	 AND SP = 'В3.2'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2630',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.2' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.2' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.2' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.2' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.2' and  MONTH_BASE = @nMONTH1) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.2' and  MONTH_BASE = @nMONTH2) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.2' and  MONTH_BASE = @nMONTH3) ,0)

/*******Раздел 2.4**** Класс условий труда - вредный, подкласс условий труда - 3.1 *****/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2640', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH3),0))
 			 
FROM #SPR_ESN 
WHERE WAY_CALC = 11	 AND SP = 'В3.1'	 

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2650',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN 
WHERE WAY_CALC = 11	 AND SP = 'В3.1'	



------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '2670', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT 
	'2680',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN 
WHERE WAY_CALC = 11	 AND SP = 'В3.1'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2690',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE = @nMONTH1) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE = @nMONTH2) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE = @nMONTH3) ,0)

--select * from #RES2 
---------------
/********СРЕДНЕСПИСОЧНАЯ ЧИСЛЕННОСТЬ**********/

DECLARE @Date1M datetime, @Date2M datetime, @Date3M datetime

SELECT @BDate = @START_DATE, @EndDate = @END_DATE
SET @EDate = dateadd(year,1,convert(varchar, YEAR(@BDate))+'0101')

if @nMONTH3 =3
begin
	SET @Date1M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0101')
	SET @Date2M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0201')
	SET @Date3M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0301')
end
if @nMONTH3 =6
begin
	SET @Date1M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0401')
	SET @Date2M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0501')
	SET @Date3M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0601')
end
if @nMONTH3 =9
begin
	SET @Date1M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0701')
	SET @Date2M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0801')
	SET @Date3M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0901')
end
if @nMONTH3 =12
begin
	SET @Date1M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'1001')
	SET @Date2M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'1101')
	SET @Date3M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'1201')
end

/* Считаем что все наши организации не состоят из уставных вкладов инвалидов , поэтому таблицу 3.1 -3.2 не заполняем */
/* Среднесписочная численность всего */
Set @NAvgCount = convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 0, DEFAULT))

/*INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '331',@NAvgCount,
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date1M, @Date2M, @DEP_LINK, 0, 1, 0, DEFAULT)),
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date2M, @Date3M, @DEP_LINK, 0, 1, 0, DEFAULT)),
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date3M, @END_DATE, @DEP_LINK, 0, 1, 0, DEFAULT))	

/* Среднесписочная численность работников инвалидов */
Set @NAvgCount = convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 1, DEFAULT))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '332',@NAvgCount,
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date1M, @Date2M, @DEP_LINK, 0, 1, 1, DEFAULT)),
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date2M, @Date3M, @DEP_LINK, 0, 1, 1, DEFAULT)),
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date3M, @END_DATE, @DEP_LINK, 0, 1, 1, DEFAULT))	

*/

/* Завершаем - списываем значения во временную таблицу */
DECLARE @Table_Razd1 VARCHAR(100)
EXEC dbo.X_GET_TABLE_NAME @Table_Razd1 OUTPUT
EXEC ('select * INTO ' + @Table_Razd1 + ' from #RES2 order by code_str')
EXEC dbo.BufferClear
EXEC dbo.BufferPush -116, @Table_Razd1

DROP TABLE #RES2














GO


GRANT EXECUTE ON dbo.[RSA_RSV_1_14_PFR_PREPARE] TO PUBLIC

GO



GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[X_DOCUMENT_GET_MAX_NUMBER]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[X_DOCUMENT_GET_MAX_NUMBER]

GO





/*
© Кейсистемс (Keysystems), 2005
*/





CREATE         PROCEDURE dbo.X_DOCUMENT_GET_MAX_NUMBER
	@varKSchrDocument 	varchar(30),
	@varKSMaxNum		varchar(30) output,
	@intDepLink		int = NULL
AS
Declare @varKSYear datetime,
	@varKSdbegin datetime,
	@varKSdend datetime,
	@intNastrDocNumZB	TINYINT,	-- 1 - Сквозная нумерация документа
	@intNastrDocNumPeriod	TINYINT,	-- 1 - Нумерация документа с начала года, 2 с начала месяца
	@intF0504501_NUM_NO_RKO	TINYINT

-- Проверка настроек -- 
SET @intNastrDocNumZB = ISNULL (dbo.SA_GET_OPTION_BY_CODE ('XK_NASTR_DOC_NUMBER_ZB'), 0)
IF @intNastrDocNumZB = 1 AND EXISTS (SELECT * FROM dbo.S_OBJECTS SO, dbo.DOC_NASTR NASTR 
					WHERE SO.CODE = @varKSchrDocument
						AND NASTR.LINK = SO.LINK
						AND NASTR.AN_ORG = 0)
	SET @intDepLink = NULL

SET @intNastrDocNumPeriod = ISNULL (dbo.SA_GET_OPTION_BY_CODE ('XK_NASTR_DOC_NUM_PERIOD'), 1)
IF @intNastrDocNumPeriod = 0 
	select @intNastrDocNumPeriod = Isnull(AN_PERIOD,1)
	from dbo.XD_DOC_NASTR 
	where CODE = @varKSchrDocument 

Select @varKSYear = WORKDATE from dbo.USER_INFO
if @intNastrDocNumPeriod = 2
	Select @varKSdbegin = dbo.DateBeginOfMonth(@varKSYear), @varKSdend = dbo.DateEndOfMonth(@varKSYear)
else
	Select @varKSdbegin = dbo.DateBeginOfYear(@varKSYear), @varKSdend = dbo.DateEndOfYear(@varKSYear)

IF @varKSchrDocument = 'DOCUMENTS_RKO' OR @varKSchrDocument = 'DOCUMENTS_F0504501'
BEGIN
	SET @intF0504501_NUM_NO_RKO = ISNULL (dbo.XK_GET_NASTR_INT ('NASTR_F317_NUM_NO_KO'), 0)

	SET @varKSMaxNum = (SELECT right(MAX(REPLACE(SPACE(25-len(RTRIM(number)))+RTRIM(number), ' ','0')), 25)
	FROM dbo.G_PROV G
	INNER JOIN dbo.S_OBJECTS SO ON (G.OBJECT = SO.LINK)
	WHERE (SO.CODE = 'DOCUMENTS_RKO' OR SO.CODE = 'DOCUMENTS_F0504501')
		AND (@intF0504501_NUM_NO_RKO = 1 AND SO.CODE = @varKSchrDocument
			OR @intF0504501_NUM_NO_RKO = 0)
		AND (@intDepLink IS NULL OR G.DEP = @intDepLink)
		AND G.[DATE] BETWEEN @varKSdbegin AND @varKSdend
		AND dbo.CheckIsNumeric (NUMBER) = 1
		AND NUMBER not LIKE '%.%' and NUMBER not LIKE '%-%')
END
ELSE
   SET @varKSMaxNum = (SELECT right(MAX(REPLACE(SPACE(30-len(RTRIM(number)))+RTRIM(number), ' ','0')), 30)
	FROM dbo.G_PROV G INNER JOIN dbo.s_objects so ON G.OBJECT = so.link
	WHERE so.CODE = @varKSchrDocument AND G.DATE BETWEEN @varKSdbegin AND @varKSdend 
		AND (@intDepLink IS NULL OR G.DEP = @intDepLink)
		AND dbo.CheckIsNumeric (NUMBER) = 1
		AND NUMBER not LIKE '%.%' and NUMBER not LIKE '%-%')
		

SET @varKSMaxNum = ISNULL(@varKSMaxNum, REPLICATE('0', 30))



GO


GRANT EXECUTE ON dbo.[X_DOCUMENT_GET_MAX_NUMBER] TO PUBLIC

GO


--Расширенные свойства--


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[X_SAVE_DICTION_PAY_OKTMO]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[X_SAVE_DICTION_PAY_OKTMO]

GO
CREATE 
/*
© Кейсистемс (Keysystems), 2005
*/
         
PROCEDURE dbo.X_SAVE_DICTION_PAY_OKTMO
	@varKSparLINK	int	OUTPUT,
	@varKSparCODE   VARCHAR(11) = null,
	@varKSparKCH	VARCHAR(1) = null,
	@varKSparName   VARCHAR(254) = null,
	@varKSparDOP	VARCHAR(254) = null
AS
DECLARE @varKStrancount int, @varKSSQLError int, @varKSRowCount int, @varKScomment varchar(254), @varKSEventText varchar(254), @varKSObjectLink INT,
		@varKSparPARENT_LINK int
	
	
SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	
	--Проверка обязательных реквизитов
	IF @varKSparCODE IS NULL or @varKSparCODE='' or @varKSparKCH is null OR @varKSparKCH = ''  OR @varKSparNAME is null or @varKSparNAME='' 
	BEGIN
		ROLLBACK
		RETURN 5
	END
	-- проверка уникальности кода
	IF @varKSparCODE = (SELECT CODE FROM  DICTIONARY_OKTMO  where ltrim(RTRIM(code)) = ltrim(rtrim(@varKSparCODE)) and LINK <> @varKSparLINK)
	BEGIN
		RAISERROR('Запись не уникальна!', 11, 1)
		ROLLBACK
		RETURN 5
	END

	IF @varKSparLINK is null OR @varKSparLINK = 0
	BEGIN
		
		INSERT INTO DICTIONARY_OKTMO WITH (ROWLOCK) (CODE, KCH, NAME, DOP)
			VALUES (@varKSparCODE, @varKSparKCH, @varKSparNAME, @varKSparDOP)

		SELECT @varKSSQLError = @@ERROR, @varKSparLINK = @@IDENTITY
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	
	ELSE
	BEGIN
		UPDATE DICTIONARY_OKTMO SET CODE = @varKSparCODE, KCH = @varKSparKCH, NAME = @varKSparNAME , DOP = @varKSparDOP 
		WHERE link=@varKSparLINK
		SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END
	SELECT @varKSObjectLink = link FROM s_objects WHERE code='DICTION_PAY_OKTMO'
	SET @varKSEventText = 'Код ОКТМО ' + @varKSparCODE +' '+ @varKSparKCH +' '+@varKSparNAME +' '+@varKSparDOP
	EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника', @varKSEventText, @varKSObjectLink, 'DICTION_PAY_OKTMO', @varKSparLINK

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0

GO


GRANT EXECUTE ON dbo.[X_SAVE_DICTION_PAY_OKTMO] TO PUBLIC

GO


--Расширенные свойства--
--Свойство:SCRIPT значение: EXECUTE X_FORM_SAVE_DICTIONARY 'DICTION_PAY_OKTMO', 'DICTION_PAY_OKTMO', 1


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BB_EXPORT_ZKR]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BB_EXPORT_ZKR]

GO


/*
© Кейсистемс (Keysystems), 2005
*/

CREATE           
PROCEDURE dbo.BB_EXPORT_ZKR
	@cBuffId	varchar(30) = '',
	@cFormat	varchar(30) = ''

AS
DECLARE @iDepLink	int, 
	@cCodeOpt 	int,
	@iNoteDCL	tinyint,
	@cPrefDCL	varchar(10), 
	@cKorrName	varchar(254), 
	@iLongFio tinyint, 
	@iPostRuk tinyint, 
	@iPostGl tinyint


set @iPostRuk = dbo.sa_get_option_by_code('BB_ZAYAVKA_KR_OPTIONS_POST_RUK')
set @iPostGl = dbo.sa_get_option_by_code('BB_ZAYAVKA_KR_OPTIONS_POST_GL')
set @iLongFio = dbo.sa_get_option_by_code('BB_ZAYAVKA_KR_OPTIONS_FIO')

set @iDepLink = isnull(dbo.BK_GetDepZB(),dbo.GetOwnDepLink())
select @cCodeOpt = KODBP,
	@iNoteDCL = isnull(T_DCL,0),
	@cPrefDCL = isnull(rtrim(PREF_DCL) + ' ',''),
	@cKorrName = isnull(rtrim(KOR_NAME),'<Наим_орг_полн>')
from dbo.BB_ZAYAVKA_KR_OPTIONS

-- Таблица 2 (FROM)
SELECT 	BUDG_LEVEL  = case D.BUH_TYPE WHEN 1 then cast(replace(B.CODE_EL,'0','') as char(1)) else '6' end,
		KOD_UBP = case cast(replace(B.CODE_EL,'0','') as char(1)) when 1 then D.CODE_UBP else BUDG end,
		NAME_UBP	= left(rtrim(D.prefix) + rtrim(D.FULL_NAME) + case when charindex('(',D.prefix,0) > 0 then ')' else '' end,254),
		0 as link,
		0 as link_up
from dbo.DEPARTMENTS D
left join dbo.KL_ADMIN_BS V WITH (NOLOCK) on V.LINK = D.VED_LINK
left join dbo.KL_BUDG_TYPE B WITH (NOLOCK) on V.Link_Budg = B.LINK
where D.LINK = @iDepLink


-- Таблица 3 (TO)
SELECT 	KOD_TOFK  = TOFK.CODE,
		NAME_TOFK = TOFK.FULL_NAME,
		0 as link,
		0 as link_up
from dbo.DEPARTMENTS D
inner join dbo.TREASURY TOFK on D.TOFK_LINK = TOFK.LINK
where D.LINK = @iDepLink



-- Таблица 4 (ZR)


	SELECT  LINK 		 = ZKR.LINK,
			LINK_UP		 = ZKR.LINK,
			GUID_FK		 = '',
			[TYPE]		 = cast(ZKR.SHORT + 1 as char(1)),
			NOM_ZR		 = ZKR.NUMBER,
			DATE_ZR		 = ZKR.DATE,
			KOD_UBP_PAY	 = case @cCodeOpt when 1 then ZKR.DEP_UBP else '' end,
			NAME_UBP_PAY = ZKR.DEP_FNAME, 
			LS_UBP_PAY	 = ZKR.ACC_CODE,
			INN_UBP		 = '',
			KPP_UBP		 = '',
			GLAVA_GRS	 = case ZKR.dep_type WHEN 1 then ZKR.GRBS_CODE else '' end,
			NAME_UBP_GRS = case ZKR.SHORT when 0 then case ZKR.dep_type WHEN 1 then ZKR.GRBS_NAME else ZKR.UCHR_NAME end  else '' end,
			NAME_BUD	 = case ZKR.dep_type WHEN 1 then ZKR.BUDG_NAME else '' end,
			NAME_FO		 = case ZKR.SHORT when 0 then case ZKR.dep_type WHEN 1 then ZKR.FO_NAME else '' end else '' end,
			OKPO_FO		 = case ZKR.SHORT when 0 then case ZKR.dep_type WHEN 1 then ZKR.FO_OKPO else '' end else '' end,
			KOD_TOFK	 = ZKR.TOFK_CODE,
			NAME_TOFK	 = ZKR.TOFK_NAME,
			DATE_ISP	 = ZKR.SROK,
			GUID_SV		 = '',
			NOM_BO		 = ZKR.BO_NUM,
			KOD_ISP		 = '',
			PR_ISP		 = '',
			FAIP_CODE	 = '',
			SUM_V		 = ZKR.SUMMA,
			KOD_V		 = '643',
			SUM_DOC		 = 0,
			TYPE_AP		 = cast(ZKR.AVANSE as char(1)),
			SUM_V_NDS	 = case ZKR.SHORT when 0 then ZKR.SUMMA_NDS else 0 end,
			ORDER_PL	 = ZKR.[ORDER],
			VID_PL		 = CASE	ZKR.KIND WHEN 'почтой'     THEN '1'
										 WHEN 'телеграфом' THEN '2'
										 WHEN 'электронно' THEN '3'
										 WHEN 'срочно' 	   THEN '4'
										 ELSE '0' END,
			PURPOSE		 = replace(replace(ZKR.TARGETTEXT,char(10),''),char(13),''),
			VID_OSN		 = ZKR.OSN_VID,
			NOM_OSN		 = ZKR.OSN_NUM,
			DATE_OSN	 = ZKR.OSN_DATE,
			OSN			 = ZKR.OSN_COM,
			NAME_RCP	 = dbo.BB_DEP_NAME_FOR_SHABLON(@cKorrName, ZKR.KOR_LINK,  ZKR.KOR_ACC_LINK), 
			INN_RCP		 = ZKR.KOR_INN,
			KPP_RCP		 = case when len(rtrim(ZKR.KOR_INN)) > 10 then '0' else ZKR.KOR_KPP end,
			LS_UBP_RCP	 = case ZKR.SHORT when 0 then ZKR.KOR_LACC else '' end,
			BS_RCP		 = replace(ZKR.KOR_RACC,'00000000000000000000',''),
			NAME_BIC_RCP = ZKR.KOR_BANK,
			BIC_RCP		 = ZKR.KOR_BIK,
			KS_BIC_RCP	 = ZKR.KOR_KS,
			PAYSTATUS	 = ZKR.STATUS,
			KDOH		 = replace(ZKR.DOH_CODE_L,'.',''),
			OKATO		 = ZKR.OKATO,
			OSN_PL		 = ZKR.P_REASON,
			NAL_PER		 = ZKR.[PERIOD],
			NOM_DOK		 = ZKR.TREBNUM,
			DATE_DOK	 = case ZKR.ZERODATE when 1 then /*'00.00.0000'*/ '0' else CONVERT(CHAR(10),ZKR.TREBDATE,104) end,
			TYPE_PL		 = ZKR.P_TYPE,
			DOL_RUK_UBP	 = case when ZKR.SHORT = 0 and @iPostRuk = 1 then B.POST_NAME else '' end,
			NAME_RUK_UBP = case @iLongFio when 1 then rtrim(B.FM) + ' ' + rtrim(B.IM) + ' ' + rtrim(B.OT) else B.SHORT_NAME end,
			DOL_BUH_UBP	 = case when ZKR.SHORT = 0 and @iPostGl = 1 then GB.POST_NAME else '' end,
			NAME_BUH_UBP = case @iLongFio when 1 then rtrim(GB.FM) + ' ' + rtrim(GB.IM) + ' ' + rtrim(GB.OT) else GB.SHORT_NAME end,
			DATE_POD_UBP = ZKR.DATE,
			NOM_ZR_FK	 = '',
			DATE_FK		 = cast(null as datetime),
			DOL_ISP_FK	 = '',
			NAME_ISP_FK	 = '',
			TEL_ISP_FK	 = ''
	FROM dbo.BB_ZAYAVKA_KR ZKR
	left join dbo.GetOtvFaceData(null, 'Руководитель') B on ZKR.DEP_LINK = B.LINK_DEP
	left join dbo.GetOtvFaceData(null, 'Главный бухгалтер') GB on ZKR.DEP_LINK = GB.LINK_DEP
	where ZKR.LINK in (select LINK from dbo.BufferGetTableByID(@cBuffId))


if @cFormat > 'TXZR100700' --or @cFormat = ''
/*	SELECT  LINK 		 = case when ZKR.OSNOV_LINK is null then ZKR.LINK else ZKR.DOG_LINK end,
			LINK_UP		 = ZKR.LINK,
			VID_OSN		 = ZKR.DOG_VID,
			NOM_OSN		 = ZKR.DOG_NUM,
			DATE_OSN	 = ZKR.DOG_DATE,
			OSN			 = case ZKR.SHORT when 0 then ZKR.DOG_COM else '' end
	FROM dbo.BB_ZAYAVKA_KR ZKR
	where ZKR.LINK in (select LINK from dbo.BufferGetTableByID(@cBuffId)) and ZKR.DOG_NUM is not null
	union all
	SELECT  LINK 		 = ZKR.LINK,
			LINK_UP		 = ZKR.LINK,
			VID_OSN		 = ZKR.OSN_VID,
			NOM_OSN		 = ZKR.OSN_NUM,
			DATE_OSN	 = ZKR.OSN_DATE,
			OSN			 = case ZKR.SHORT when 0 then ZKR.OSN_COM else '' end
	FROM dbo.BB_ZAYAVKA_KR ZKR
	where ZKR.LINK in (select LINK from dbo.BufferGetTableByID(@cBuffId)) and ZKR.OSN_NUM is not null 
				
*/
	SELECT  ZO.LINK, 
			ZO.LINK_UP,
			VID_OSN		 = ZO.[TYPE],
			NOM_OSN		 = ZO.NUMBER,
			DATE_OSN	 = ZO.[DATE],
			OSN			 = case ZKR.SHORT when 0 then ZO.COMMENT else '' end,
			OSN_PLAT	=	CASE ZKR.SHORT WHEN 0 THEN '' ELSE replace(str(ZO.OSN),'0','2') END
	FROM dbo.BB_ZAYAVKA_KR_OSNOV ZO
	inner join dbo.BB_ZAYAVKA_KR ZKR on ZKR.LINK = ZO.LINK_UP
	where ZKR.LINK in (select LINK from dbo.BufferGetTableByID(@cBuffId))
	union all
	SELECT  ZKR.LINK, 
			ZKR.LINK,
			VID_OSN		 = 'УИН',
			NOM_OSN		 = ZKR.UIN_CODE,
			DATE_OSN	 = NULL,
			OSN			 = '-',
			OSN_PLAT	 = CASE ZKR.SHORT WHEN 0 THEN '' ELSE '2' END
	FROM dbo.BB_ZAYAVKA_KR ZKR
	where ZKR.LINK in (select LINK from dbo.BufferGetTableByID(@cBuffId)) and ZKR.UIN_CODE <>''
 	order by 2,1
	

-- Таблица 4 (ZRST)
	select  ZT.LINK,
			LINK_UP = coalesce((select top 1 LINK from( 
								select LINK from ZAYAVKA_KR_OSNOV where LINK_UP = ZT.LINK_UP 
								union all
								SELECT  FP.LINK FROM dbo.finanse_pays FP where FP.LINK = ZT.LINK_UP and FP.UIN_CODE <>'') A
								order by LINK desc)
					,ZT.LINK_UP),
			KOD_IST_KBK	  = cast(ZT.VID_SR as char(1)),
			TYPE_KBK_PAY  = case ZT.KBK_TYPE when 1 then '10'
											 when 2 then '20'
											 when 4 then '31'
											 when 8 then '32'
											 else '' end,
			KBK_PAY		  = left(replace(replace(ZT.BK_CODE,'.',''),'00000000000000000000',''),20),
			TYPE_KBK_RCP  = case ZKR.SHORT when 0 then case ZT.KBK_TYPE_d when 1 then '10'
																		  when 2 then '20'
																		  when 4 then '31'
																		  when 8 then '32'
																		  else '' end else '' end,
			KBK_RCP		  = case ZKR.SHORT when 0 then left(replace(ZT.BKD_CODE,'.',''),20) else '' end,
			ADD_KLASS_PAY = case when left(DA.CODE,2) = '21' or left(DA.CODE,2) = '31' then isnull(ZT.DCL_CODE, '-') else ZT.DCL_CODE end,
			ADD_KLASS_RCP = ZT.DCL_CODE_D,
			SUM_V_KBK	  = ZT.SUMMA,
			SUM_R_KBK	  = 0,
			PURPOSE_KBK	  = case ZKR.SHORT when 0 then ZT.TARGET else '' end,
			NOTE_KBK	  = case ZKR.SHORT when 0 then ZT.TITLE + case @iNoteDCL when 1 then @cPrefDCL + ZT.DCL_CODE else '' end else '' end 
	from dbo.BB_ZAYAVKA_KR_TABLE ZT
	inner join dbo.FINANSE_PAYS ZKR on ZKR.LINK = ZT.LINK_UP
	inner join dbo.G_PROV G on ZKR.LINK = G.LINK
	inner join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = G.ACC
	where ZT.LINK_UP in (select LINK from dbo.BufferGetTableByID(@cBuffId))





GO


GRANT EXECUTE ON dbo.[BB_EXPORT_ZKR] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BD_JURN_BO_FORM_PROV]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BD_JURN_BO_FORM_PROV]
GO


/*
© Кейсистемс (Keysystems), 2005
*/
CREATE         PROCEDURE dbo.BD_JURN_BO_FORM_PROV
	@varKSparLinkGP int OUTPUT,
	@varKSparLink int, 
	@cProvErr varchar(100) OUTPUT
AS

DECLARE @varKSparAP1 int,
		@varKSparLinkProv int,
		@varKSparDocObj	int,
		@varKSparIstFin tinyint,
		@varKSLinkDt int,
		@varKSLinkKt int,
		@varKSDate datetime,
		@varKSNumber varchar(25),
		@varKSSumma numeric(18,2),
		@varKSComment1 varchar(254), 
		@varKSInfo	varchar(254),
		@varKSDep	varchar(254),
		@varKSKBK	int,
		@varKSKBK_TYPE	int,
		@varKSSGU	int,
		@varKSDOP	int,
		@varKSDEP_ACC int,
		@varKSDateFIN datetime,
		@varKSisFIN bit,
		@bDO bit,
		@cAnalit506 char(2)

set @cProvErr = null
SELECT @varKSparAP1 = AP1,
	   @varKSparLinkProv = PROV_LINK,
	   @varKSparIstFin = IST_FIN /* -1*/,
	   @varKSDate = DATE_AP1,
	   @varKSInfo = NAME_AP1,
	   @varKSSumma = SUMMA,
	   @varKSKBK = KBK_LINK,
	   @varKSKBK_TYPE = KBK_TYPE,
	   @varKSSGU = SGU_LINK,
	   @varKSDOP = DOP_LINK,
	   @varKSDEP_ACC = ACCOUNT_LINK,
	   @varKSDep = DEP,
	   @bDO = DO		  
FROM dbo.BD_JURN_BO WHERE LINK = @varKSparLink


-- Проверяем сформировано ли данное БО на основании Договора 
SET @varKSisFIN = 0 
IF EXISTS(SELECT * FROM dbo.JURN_BO BO
			inner join dbo.OSNOV O on BO.LINK_DOC = O.LINK
			inner join dbo.OSNOV_VID OV on OV.LINK = O.TYPE_LINK and TYPE = 1
			inner join dbo.G_PROV G on O.LINK_G_PROV = G.LINK and ISNULL(year(G.DATE_PROV),0) = ISNULL(year(BO.DATE_DOC),0)
			inner join dbo.S_OBJECTS SO on G.[OBJECT] = SO.LINK and (SO.CODE = 'FINANS_CONTRACT' or SO.CODE = 'FINANS_CONTRACT_CHANGE')
			WHERE BO.LINK_DOC = @varKSparAP1 )
BEGIN
	SET @varKSisFIN = 1 
	-- Получаем дату договора
	SELECT @varKSDateFIN = DATE_PROV FROM dbo.G_PROV WHERE LINK IN (SELECT DOC_LINK FROM dbo.BD_OSNOV WHERE LINK = @varKSparAP1)
END
/*if @varKSDateFIN is null
	set @varKSisFIN = 0*/
	
IF @varKSDep IS NULL OR @varKSDep NOT IN (SELECT LINK FROM dbo.DEPARTMENTS)
	SELECT @varKSDep = LINK_UP FROM dbo.department_accounts DA 
	WHERE DA.LINK = @varKSDEP_ACC
if exists(SELECT * FROM dbo.DEPARTMENTS where LINK = @varKSDep and BUH_TYPE = 1)
	set @cAnalit506 = '00'
else
	set @cAnalit506 = '10'

IF @varKSparLinkProv IS NOT NULL
	RETURN	3001

SELECT @varKSparDocObj = LINK FROM S_OBJECTS WHERE CODE = 'DOCUMENTS_500'

if @bDO = 1
begin
	SELECT @varKSLinkDt = LINK FROM S_ACCOUNTS WHERE cSinth = '502' AND cAnalit = '11' AND cSource = @varKSparIstFin AND ISNULL(cUSER,'') = ''
	if @varKSLinkDt is null 
	begin
		set @cProvErr = 'Не найден счет ' + cast(@varKSparIstFin as char(1)) + '.502.11'
		return 3002
	end
	SELECT @varKSLinkKt = LINK FROM S_ACCOUNTS WHERE cSinth = '502' AND cAnalit = '12' AND cSource = @varKSparIstFin AND ISNULL(cUSER,'') = ''
	if @varKSLinkKt is null 
	begin
		set @cProvErr = 'Не найден счет ' + cast(@varKSparIstFin as char(1)) + '.502.12'
		return 3002
	end
end
else
begin
	SELECT @varKSLinkDt = LINK FROM S_ACCOUNTS WHERE ((@varKSKBK_TYPE = 1 and cSinth = '501' or @varKSKBK_TYPE > 1 and cSinth = '503') AND cAnalit = '13'  AND cSource = '1' and @varKSparIstFin = '1' or 
														cSinth = '506' AND cAnalit = @cAnalit506 AND cSource = @varKSparIstFin and @varKSparIstFin <> '1')
							AND ISNULL(cUSER,'') = ''
	
	if @varKSLinkDt is null and @varKSparIstFin <> '1'
		SELECT @varKSLinkDt = LINK FROM S_ACCOUNTS WHERE cSinth = '504' AND cAnalit = '12' AND cSource = @varKSparIstFin AND ISNULL(cUSER,'') = ''
	
	if @varKSLinkDt is null 
	begin
		set @cProvErr = 'Не найден счет Дт для формирования проводки'
		return 3002
	end
	SELECT @varKSLinkKt = LINK FROM S_ACCOUNTS WHERE cSinth = '502' AND cAnalit = '11' AND cSource = @varKSparIstFin AND ISNULL(cUSER,'') = ''
	if @varKSLinkKt is null 
	begin
		set @cProvErr = 'Не найден счет ' + cast(@varKSparIstFin as char(1)) + '.502.11'
		return 3002
	end
end




SELECT @varKSComment1 = CONVERT(VARCHAR(254),'Принятие обязательств на основании документа:'+ RTRIM(@varKSInfo))
IF @varKSComment1 IS NULL
 SET @varKSComment1 = 'Принятие обязательства на основании записи в журнале регистрации БО'

DECLARE @TabProv1 TABLE
(LINK_GP int,
 LINK_GP1 int,
 LINK_GP2 int,
 LINK_GPA int,
 LINK_OBJECT int)


INSERT INTO @TabProv1 (LINK_GP,LINK_GP1,LINK_GP2)
SELECT GP.LINK,GP1.LINK,GP2.LINK
FROM dbo.G_PROV GP
inner join dbo.G_PROV1 GP1 on GP1.LINK_UP = GP.LINK
inner join G_PROV2 GP2 on GP2.LINK_UP = GP1.LINK
inner join G_PROV_AP GA on GA.LINK_UP  = GP2.LINK and GA.AP1 = @varKSparAP1 
inner join S_ACCOUNTS SA on SA.LINK  = GA.ACCOUNT and cSinth = '502' AND cAnalit = '11'
WHERE GP.OBJECT = @varKSparDocObj

IF @@ROWCOUNT = 0 /* Если для данного документа основания еще нет документа-обязательства, 
                     то создаем новый документ */
BEGIN


	SELECT @varKSNumber = cast(ISNULL(MAX(G.NUMBER),0) as bigint)+1 FROM dbo.G_PROV G WHERE G.OBJECT = @varKSparDocObj AND 
			ISNUMERIC(G.NUMBER) > 0 AND CHARINDEX('.',G.NUMBER,1) = 0 AND CHARINDEX(',',G.NUMBER,1) = 0
			AND YEAR(DATE) = YEAR((SELECT WORKDATE FROM USER_INFO))
	

	IF @varKSisFIN = 1
		BEGIN
			INSERT INTO G_PROV (NUMBER,DATE,OBJECT,DATE_PROV,SUMMA,COMMENT,DEP) 
			VALUES (@varKSNumber,@varKSDateFIN,@varKSparDocObj,@varKSDateFIN,0,@varKSComment1,@varKSDep)
			SELECT @varKSparLinkGP = @@IDENTITY
		END
	ELSE
		BEGIN
			INSERT INTO G_PROV (NUMBER,DATE,OBJECT,DATE_PROV,SUMMA,COMMENT,DEP) 
			VALUES (@varKSNumber,@varKSDate,@varKSparDocObj,@varKSDate,0,@varKSComment1,@varKSDep)
			SELECT @varKSparLinkGP = @@IDENTITY
		END
END
ELSE
	SET @varKSparLinkGP = (SELECT TOP 1 LINK_GP FROM @TabProv1)



/* Теперь вставляем операцию */
DECLARE @varKSOperOrders int,
		@varKSparLinkGP1 int,
		@varKSparLinkGP2 int,
		@varKSparLinkEconOper int

SELECT @varKSparLinkEconOper = LINK FROM dbo.XD_XOZ_OPER WHERE FULLCODE = case @bDO when 1 then  '19.08' else '19.07' end

SELECT @varKSOperOrders = ISNULL(MAX(ORDERS),0)+1 FROM G_PROV1 WHERE LINK_UP = @varKSparLinkGP


INSERT INTO G_PROV1 (LINK_UP,OPER,NAME_OPER,ORDERS)
VALUES(@varKSparLinkGP,NULL,@varKSComment1,@varKSOperOrders)
SELECT @varKSparLinkGP1 = @@IDENTITY
/* Теперь вставляем проводку */
INSERT INTO G_PROV2 (LINK_UP,SUMMA,QUANTITY,STORNO,NAME,ORDERS,ECON_OPER)
VALUES (@varKSparLinkGP1,@varKSSumma,0,0,@varKSComment1,1,@varKSparLinkEconOper)
SELECT @varKSparLinkGP2 = @@IDENTITY
/* Теперь вставляем дебит и кредит */

DECLARE @DebitDate datetime,
		@CreditDate datetime

IF EXISTS(SELECT * FROM dbo.S_ACCOUNTS WHERE LINK = @varKSLinkDt AND ap_INDATE = 1)
BEGIN
	SET @DebitDate = @varKSDate
END
ELSE
BEGIN
	SET @DebitDate = NULL
END

IF EXISTS(SELECT * FROM dbo.S_ACCOUNTS WHERE LINK = @varKSLinkKt AND ap_INDATE = 1)
BEGIN
	SET @CreditDate = @varKSDate
END
ELSE
BEGIN
	SET @CreditDate = NULL
END
-- Тыркаем дебит
INSERT INTO G_PROV_AP (LINK_UP,DB_KR,ACCOUNT,KBK,EKR,DEP,SGU,DEP_ACC,AP1,AP2,INDATE)
VALUES (@varKSparLinkGP2,0,@varKSLinkDt,@varKSKBK,@varKSSGU,@varKSDep,@varKSSGU,@varKSDEP_ACC,@varKSparAP1,@varKSDOP,@DebitDate)
-- Тыркаем кредит
INSERT INTO G_PROV_AP (LINK_UP,DB_KR,ACCOUNT,KBK,EKR,SGU,DEP_ACC,AP1,AP2,INDATE)
VALUES (@varKSparLinkGP2,1,@varKSLinkKt,@varKSKBK,@varKSSGU,@varKSSGU,@varKSDEP_ACC,@varKSparAP1,@varKSDOP,@DebitDate)


/* Теперь прописываем ссылку из журнала на проводку*/
UPDATE dbo.JURN_BO
SET LINK_PO_PROV = @varKSparLinkGP2
WHERE LINK = @varKSparLink

EXEC dbo.X_SALDO_CommitChanges




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on BD_JURN_BO_FORM_PROV to public
GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BK_GET_PREV_DOC_WAYBIL_AUTO]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_GET_PREV_DOC_WAYBIL_AUTO]

GO
CREATE PROCEDURE dbo.BK_GET_PREV_DOC_WAYBIL_AUTO
	@AUTO_LINK	INT,
	@DEP_LINK	INT	=	NULL,
	@DOC_DATE	DATETIME = NULL
AS
BEGIN
	SELECT TOP 1
		*
	FROM dbo.BV_DOC_WAYBILL G
	WHERE
		G.AUTO_LINK = @AUTO_LINK
		AND G.EMP_LINK IS NOT NULL
		AND (@DEP_LINK IS NULL OR G.DEP_LINK = @DEP_LINK)
		AND (@DOC_DATE IS NULL OR G.[DATE] <= @DOC_DATE)
	ORDER BY G.[DATE] DESC 	
END

GO

GRANT EXECUTE ON dbo.[BK_GET_PREV_DOC_WAYBIL_AUTO] TO PUBLIC

GO


--Расширенные свойства--

-- EXEC BK_GET_PREV_DOC_WAYBIL_AUTO 4020
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BB_DOCUMENT_SETDATE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_DOCUMENT_SETDATE]
GO

/*
© Кейсистемс (Keysystems), 2005
*/

CREATE         PROCEDURE dbo.BB_DOCUMENT_SETDATE
	@cBufferId		char(100),
	@varKSDate 		DateTime output,
	@iDateDocProv 	smallint = 0,
	@iNumDoc		tinyint = 0
	
	
AS
if @varKSDate < '19000101'
	SET @varKSDate = NULL 
	
Declare @cObjCode	char(30), 
		@xCount		int,
		@cNumber	varchar(25),
		@iDocLink	int,
		@iDepLink	int,
		@dWorkDate	datetime,

		-- ПЕРИОД РЕДАКТИРОВАНИЯ --
		@dDATE_BEGIN	DATETIME,
		@dDATE_END	DATETIME

IF exists(Select CODE_TASK from dbo.USER_INFO WHERE CODE_TASK IN ('STORAGE', 'OUTPUTS'))
	return 0

SELECT @dDATE_BEGIN = BEGINDATE,
	@dDATE_END = ENDDATE
FROM dbo.ADMIN_INFO

if @varKSDate is not null AND NOT (@varKSDate BETWEEN @dDATE_BEGIN AND @dDATE_END)
		return -1

/*
if @varKSDate is not null 
	IF not exists (select * from dbo.admin_info where @varKSDate BETWEEN BEGINDATE AND ENDDATE)
		return -1
*/
declare @tBuffer table (LINK int)
insert into @tBuffer
select LINK from dbo.BufferGetTableByID(@cBufferId)


set @xCount = 0
if @iNumDoc = 1
begin
	select @dWorkDate = workdate from DBO.USER_INFO
	DECLARE DOC_CUR CURSOR LOCAL STATIC READ_ONLY FOR
	SELECT GP.LINK,SO.CODE,GP.DEP 
	FROM @tBuffer B
	inner join dbo.G_PROV GP on  GP.LINK = B.LINK and (GP.NUMBER = '' or UPPER(left(GP.NUMBER,2)) = 'БН')
	inner join dbo.S_OBJECTS SO on GP.OBJECT = SO.LINK
	OPEN DOC_CUR
	FETCH NEXT FROM DOC_CUR INTO @iDocLink, @cObjCode, @iDepLink
	WHILE @@FETCH_STATUS = 0
	BEGIN
		exec X_DOCUMENT_GET_NEXT_NUMBER @cObjCode, @cNumber output, @iDepLink
		update dbo.G_PROV 
		set NUMBER = @cNumber, DATE = @dWorkDate
		where LINK = @iDocLink
		set @xCount = @xCount + 1
		FETCH NEXT FROM DOC_CUR INTO @iDocLink, @cObjCode, @iDepLink
	end
	close DOC_CUR
end

if @varKSDate is null and @iDateDocProv <> 3
begin
	update dbo.G_PROV 
	set DATE_PROV = @varKSDate
	from dbo.G_PROV GP
	inner join @tBuffer B on GP.LINK = B.LINK
	where GP.DATE_PROV is not null
		AND GP.DATE_PROV BETWEEN @dDATE_BEGIN AND @dDATE_END
	set @xCount = @xCount + @@ROWCOUNT		
end
else
begin
	if @iDateDocProv = 0
	begin
		update dbo.G_PROV 
		set DATE_PROV = @varKSDate
		from dbo.G_PROV GP
		inner join @tBuffer B on GP.LINK = B.LINK
		where (GP.DATE_PROV is null OR GP.DATE_PROV <> @varKSDate)
		set @xCount = @xCount + @@ROWCOUNT		
	end
	if @iDateDocProv = 1
	begin
		update dbo.G_PROV 
		set DATE_PROV = [DATE]
		from dbo.G_PROV GP
		inner join @tBuffer B on GP.LINK = B.LINK
		where (GP.DATE_PROV is null OR GP.DATE_PROV <> GP.[DATE])
			AND GP.[DATE] BETWEEN @dDATE_BEGIN AND @dDATE_END 

		set @xCount = @xCount + @@ROWCOUNT		
	end
end
DECLARE @Curs CURSOR,	
		@CurLink int--,
		--@cNumber varchar(25),
		--@cName varchar(100),
		--@cDate varchar(10),
		--@iDepLink int
--set @iDepLink = dbo.BK_GetDepZB()		

--create table #tProtocol(txt varchar(1000), NEW_ROW tinyint, nSTATUS tinyint, nTAB tinyint, ord int identity(1,1))

SET @Curs = CURSOR FORWARD_ONLY FOR 
SELECT DISTINCT G.LINK  
FROM @tBuffer G
inner join G_PROV1 G1 on G.LINK = G1.LINK_UP 
inner join G_PROV2 G2 on  G1.LINK = G2.LINK_UP AND G2.ECON_OPER IN (SELECT LINK FROM XD_XOZ_OPER WHERE BO = 1 or DO = 1)

OPEN @Curs
FETCH FROM @Curs INTO @CurLink
WHILE @@FETCH_STATUS = 0
BEGIN
	--insert into #tProtocol (txt, NEW_ROW, nSTATUS, nTAB) 
	EXEC XD_FORM_BO @CurLink 
	--print @CurLink
	FETCH FROM @Curs INTO @CurLink
END
CLOSE @Curs
DEALLOCATE @Curs

--select txt, NEW_ROW, nSTATUS, nTAB from #tProtocol
--drop table #tProtocol
exec dbo.X_SALDO_COMMITCHANGES

return @xCount
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_REP_FUR]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_REP_FUR]

GO


CREATE   PROCEDURE [dbo].SA_REP_FUR @LINK_DOC INT
AS

declare @OBJ_CODE varchar(254), @SR_VID INT, @AvgDays NUMERIC(18,2), @PAYMENT INT, @PER INT, @DATE_BEG DATETIME, @LINK_EMPL INT, @LINK_PAYS INT 
Set @OBJ_CODE = (Select top 1 O.CODE from dbo.sdoc D inner join S_OBJECTS O on D.OBJECT = O.LINK and D.LINK = @LINK_DOC)

Select top 1 @SR_VID = [TYPE], @PAYMENT = [PAYMENT], @PER = [TYP_PERIOD], @DATE_BEG = DATE1, @LINK_EMPL = LINK_EMPL, @LINK_PAYS = LINK_PAY
from SDOC_AVAC where LINK_UP = @LINK_DOC
  
--
DECLARE @LINK_DEP INT
select @LINK_DEP = LINK_DEP from SDOC where LINK = @LINK_DOC

SET @AvgDays = COALESCE(dbo.sa_get_option_by_code('FURLOUGH_OPT4'),29,3)
--IF @DATE_BEG <= '20140401'
--	SET @AvgDays = 29.4

Select  NAME_DOC = 'Расчет отпускных №' + RTRIM(C.[NUMBER]) + ' от ' + convert(varchar(10), C.[DATE], 104),
	NAME_DOC2 = 'Основание: приказ ' + RTRIM(LTRIM(t.[NAME])) + ' №' + RTRIM(O.NUMBER) + ' от ' + convert(varchar(10),O.[DATE],104),
	NAME_EMPL,
	TAB_NUMER,
	DATE1, DATE2, ITOGO_DNI,
	SYST_PAY = CASE WHEN SYST_PAY = 2 THEN 'Почасовая система оплаты' else '' END,
	CODE_PAY, NAME_PAY,
	DATE_PER,
	TYP_PERIOD = CASE TYP_PERIOD WHEN 1 THEN '3 месяца' WHEN 2 THEN '12 месяцев' end,
	PAYMENT = CASE PAYMENT WHEN 1 THEN 'в рабочих днях' WHEN 2 THEN 'в календарных днях' end,
	NAME_TYP = NAME_TYP_ARHE
from dbo.DOCUMENTS_ADD_FUR C 
	INNER JOIN dbo.item_vacation iv ON C.REF_ARHE = IV.LINK
	INNER JOIN dbo.orders O ON IV.ORDER_LINK = O.LINK
	INNER JOIN dbo.order_types T on O.TYPE = T.CODE
where C.LINK = @LINK_DOC
UNION
Select  NAME_DOC = 'Расчет командировочных №' + RTRIM(C.[NUMBER]) + ' от ' + convert(varchar(10), C.[DATE], 104),
	NAME_DOC2 = 'Основание: приказ ' + RTRIM(LTRIM(t.[NAME])) + ' №' + RTRIM(O.NUMBER) + ' от ' + convert(varchar(10),O.[DATE],104),
	NAME_EMPL,
	TAB_NUMER,
	DATE1, DATE2, ITOGO_DNI,
	SYST_PAY = CASE WHEN SYST_PAY = 2 THEN 'Почасовая система оплаты' else '' END,
	CODE_PAY, NAME_PAY,
	DATE_PER,
	TYP_PERIOD = CASE TYP_PERIOD WHEN 1 THEN '3 месяца' WHEN 2 THEN '12 месяцев' end,
	PAYMENT = CASE PAYMENT WHEN 1 THEN 'в рабочих днях' WHEN 2 THEN 'в календарных днях' end,
	NAME_TYP = NAME_TYP_ARHE
from dbo.DOCUMENTS_CALC_TRAVEL C 
	INNER JOIN dbo.item_travel iv ON C.REF_ARHE = IV.LINK
	INNER JOIN dbo.orders O ON IV.ORDER_LINK = O.LINK
	INNER JOIN dbo.order_types T on O.TYPE = T.CODE
where C.LINK = @LINK_DOC
UNION
Select  NAME_DOC = CASE WHEN TYPE = 1 THEN 'Расчет компенсации за неиспользованный отпуск №' else 'Расчет по среднему №' end + RTRIM(C.[NUMBER]) + ' от ' + convert(varchar(10), C.[DATE], 104),
	NAME_DOC2 = '',
	NAME_EMPL,
	TAB_NUMER,
	DATE1, DATE2, ITOGO_DNI,
	SYST_PAY = CASE WHEN SYST_PAY = 2 THEN 'Почасовая система оплаты' else '' END,
	CODE_PAY, NAME_PAY,
	DATE_PER,
	TYP_PERIOD = CASE TYP_PERIOD WHEN 1 THEN '3 месяца' WHEN 2 THEN '12 месяцев' end,
	PAYMENT = CASE PAYMENT WHEN 1 THEN 'в рабочих днях' WHEN 2 THEN 'в календарных днях' end,
	NAME_TYP = NAME_TYP_ARHE
from dbo.DOCUMENTS_CALC_AVG C 
where C.LINK = @LINK_DOC


DECLARE @SCRIPT1 VARCHAR(8000), 
	@I INT, 
	@DATE_BEGIN_RP DATETIME,
	@RP_SUMMA_PREM NUMERIC(18,2),
	@RP_SUMMA_MAT NUMERIC(18,2),
	@RP_SUMMA NUMERIC(18,2),
	@SR_PREM NUMERIC(18,2),
	@RP_DAYS INT,
	@RP_HOURS NUMERIC(18,2),
	@RP_DAYS_N INT,
	@RP_HOURS_N NUMERIC(18,2),
	@SUMMA_BASE0 NUMERIC(18,2),
	@ITOGO_DNI NUMERIC(6,2),
	@ITOGO_CH NUMERIC(18,2),
	@INSTR TINYINT,
	@SYST_PAY TINYINT

SELECT  @SCRIPT1 = '', @I = 1, @DATE_BEGIN_RP = DATE_PER,
	@RP_SUMMA_PREM = RP_SUMMA_PREM, @RP_SUMMA_MAT = RP_SUMMA_MAT, @RP_SUMMA = RP_SUMMA, 
	@SR_PREM = SR_PREM, @SYST_PAY = SYST_PAY,
	@RP_DAYS = RP_DAYS,	@RP_HOURS = RP_HOURS,
	@RP_DAYS_N = RP_DAYS_N , @RP_HOURS_N = RP_HOURS_N,
	@SUMMA_BASE0 = SUMMA_BASE, @ITOGO_DNI = ITOGO_DNI, @ITOGO_CH = ITOGO_CH,
	@INSTR = INSTR
FROM 	(
	Select DATE_PER, RP_SUMMA_PREM, RP_SUMMA, RP_SUMMA_MAT, SR_PREM, SYST_PAY, RP_DAYS, RP_HOURS, RP_DAYS_N, RP_HOURS_N, SUMMA_BASE, ITOGO_DNI, ITOGO_CH, INSTR from dbo.DOCUMENTS_ADD_FUR where LINK = @LINK_DOC
	UNION 
	Select DATE_PER, RP_SUMMA_PREM, RP_SUMMA, RP_SUMMA_MAT=0, SR_PREM, SYST_PAY, RP_DAYS, RP_HOURS, RP_DAYS_N, RP_HOURS_N, SUMMA_BASE, ITOGO_DNI, ITOGO_CH, INSTR from dbo.DOCUMENTS_CALC_TRAVEL where LINK = @LINK_DOC
	UNION 
	Select DATE_PER, RP_SUMMA_PREM, RP_SUMMA, RP_SUMMA_MAT=0, SR_PREM, SYST_PAY, RP_DAYS, RP_HOURS, RP_DAYS_N, RP_HOURS_N, SUMMA_BASE, ITOGO_DNI, ITOGO_CH, INSTR from dbo.DOCUMENTS_CALC_AVG where LINK = @LINK_DOC
	) DOC


---начисление по видам оплат
DECLARE @COUNT_M INT
SET @COUNT_M = COALESCE((Select COUNT(DISTINCT PERIOD) from SDOC_AVAC_TABLE2 where LINK_UP = @LINK_DOC),0) - (CASE WHEN @INSTR = 2 THEN 1 ELSE 0 END)
SET @COUNT_M = CASE WHEN @COUNT_M <= 0 THEN 1 ELSE @COUNT_M END
SET @COUNT_M = CASE WHEN @COUNT_M > 12 THEN 12 ELSE @COUNT_M END


IF EXISTS (Select LINK_UP from dbo.SDOC_AVAC_TABLE3 T3 where LINK_UP = @LINK_DOC)
BEGIN

	WHILE @I <= @COUNT_M
	BEGIN
		SET @SCRIPT1 = @SCRIPT1 
			+ ', N_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) + ' = CONVERT(DATETIME,''' + CONVERT(VARCHAR(10),DATEADD(MONTH,@I-1,@DATE_BEGIN_RP),104) + ''',104)'
			+ ', S_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))  + ' = SUMMA' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))
		SET @I = @I + 1
	END

	SET @I = 1
	SET @SCRIPT1 = @SCRIPT1 + ', SUM_N = 0'
	WHILE @I <= @COUNT_M
	BEGIN
		SET @SCRIPT1 = @SCRIPT1 + '+ COALESCE(SUMMA' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) + ',0)'
		SET @I = @I + 1
	END

	SET @SCRIPT1 = 'Select ORDERS, LINK_PAY, NAME_PAY = P.NAME, LINK_KBK, CODE_KBK = KBK.CODE ' + @SCRIPT1 
			+ ' from dbo.SDOC_AVAC_TABLE3 T3 INNER JOIN dbo.PAYS P ON T3.LINK_PAY = P.LINK '
			+ ' LEFT JOIN dbo.SAL_SFIN KBK ON T3.LINK_KBK = KBK.LINK WHERE LINK_UP = ' 
		+ CONVERT(VARCHAR(20),@LINK_DOC) + ' ORDER BY ORDERS'
END
ELSE
BEGIN --Если вручную заполнили суммы по месяцам, а по видам начислений данных нет

	WHILE @I <= @COUNT_M
	BEGIN
		SET @SCRIPT1 = @SCRIPT1 
			+ ', N_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) + ' = CONVERT(DATETIME,''' + CONVERT(VARCHAR(10),DATEADD(MONTH,@I-1,@DATE_BEGIN_RP),104) + ''',104)'
			+ ', S_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))  + ' = 0.00'
		SET @I = @I + 1
	END

	SET @I = 1
	SET @SCRIPT1 = @SCRIPT1 + ', SUM_N = 0'
	SET @SCRIPT1 = 'Select ORDERS=0, LINK_PAY=0, NAME_PAY = '''', LINK_KBK=0, CODE_KBK = '''' ' + @SCRIPT1 

END

exec (@SCRIPT1)

--Коэффициенты индексации
IF (	COALESCE((Select COUNT(distinct koef1) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef1,0) > 0 group by link_up having count(koef1) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef2) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef2,0) > 0 group by link_up having count(koef2) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef3) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef3,0) > 0 group by link_up having count(koef3) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef4) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef4,0) > 0 group by link_up having count(koef4) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef5) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef5,0) > 0 group by link_up having count(koef5) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef6) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef6,0) > 0 group by link_up having count(koef6) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef7) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef7,0) > 0 group by link_up having count(koef7) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef8) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef8,0) > 0 group by link_up having count(koef8) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef9) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef9,0) > 0 group by link_up having count(koef9) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef10) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef10,0) > 0 group by link_up having count(koef10) > 0),1)
	*COALESCE((Select COUNT(distinct koef11) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef11,0) > 0 group by link_up having count(koef11) > 0),1)
	*COALESCE((Select COUNT(distinct koef12) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef12,0) > 0 group by link_up having count(koef12) > 0),1) 
)  = 1 
BEGIN

	SET  @SCRIPT1 = 'Select distinct INSTR = ' + convert(varchar(1),@INSTR) + ', ORDERS = 1, NAME_PAY = ''для всех начислений'', CODE_KBK = ''для всех источников''' 
	SET  @I = 1
	WHILE @I <= @COUNT_M
	BEGIN
		SET @SCRIPT1 = @SCRIPT1 
			+ ', N_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) + ' = CONVERT(DATETIME,''' + CONVERT(VARCHAR(10),DATEADD(MONTH,@I-1,@DATE_BEGIN_RP),104) + ''',104)'
			+ ', S_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))  + ' = MAX(COALESCE(koef' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) + ',1))'
		SET @I = @I + 1
	END
	SET  @SCRIPT1 = @SCRIPT1 + ' from dbo.SDOC_AVAC_TABLE3 where LINK_UP = ' + CONVERT(VARCHAR(20),@LINK_DOC)
	exec (@SCRIPT1)

END
ELSE BEGIN

	SET  @SCRIPT1 = ''
	SET  @I = 1
	WHILE @I <= @COUNT_M
	BEGIN
		SET @SCRIPT1 = @SCRIPT1 
			+ ', N_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) + ' = CONVERT(DATETIME,''' + CONVERT(VARCHAR(10),DATEADD(MONTH,@I-1,@DATE_BEGIN_RP),104) + ''',104)'
			+ ', S_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))  + ' = KOEF' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))
		SET @I = @I + 1
	END
	
	SET @SCRIPT1 = 'Select INSTR = ' + convert(varchar(1),@INSTR) + ', ORDERS, LINK_PAY, NAME_PAY = P.NAME, LINK_KBK, CODE_KBK = KBK.CODE ' + @SCRIPT1 
			+ ' from dbo.SDOC_AVAC_TABLE3 T3 INNER JOIN dbo.PAYS P ON T3.LINK_PAY = P.LINK '
			+ ' LEFT JOIN dbo.SAL_SFIN KBK ON T3.LINK_KBK = KBK.LINK WHERE LINK_UP = ' 
		+ CONVERT(VARCHAR(20),@LINK_DOC) + ' ORDER BY ORDERS'
	
	exec (@SCRIPT1)
END

		

DECLARE @DAYS_SZ NUMERIC(18,2)
--- Время за расчетный период
SELECT  [PERIOD],
	[DAYS_N] = MAX(DAYS_N) ,
	[HOURS_N] = MAX(HOURS_N),
	[DAYS] = MAX(DAYS) ,
	[HOURS] = MAX(HOURS),
	[KDAYS] = MAX(KDAYS),
	[KDAYS_N] = MAX(ISNULL(CONVERT(NUMERIC(4,0),DAY(dbo.DateEndOfMonth(PERIOD))),0))
INTO #TMP
FROM dbo.SDOC_AVAC_TABLE2 WHERE LINK_UP = @LINK_DOC
GROUP BY [PERIOD]

SELECT  
	@DAYS_SZ = SUM(
		CASE WHEN @PAYMENT = 1 THEN--В рабочих днях 
			CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
				CASE WHEN COALESCE(DAYS,0) >= COALESCE(DAYS_N,0) THEN COALESCE(DAYS_N,0) else COALESCE(DAYS,0) * 1.2 END
			ELSE DAYS --Рассчитываются не отпускные, а прочие начисления по среднему
			END
		ELSE --В календарных днях
			CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
					CASE WHEN COALESCE(KDAYS,0.00) <> 0 AND COALESCE(KDAYS,0.00) >= COALESCE(KDAYS_N,0.00) THEN @AvgDays else CONVERT(NUMERIC(18,2),@AvgDays * (CASE WHEN COALESCE(KDAYS_N,0.00) <> 0.00 THEN COALESCE(KDAYS,0.00) / COALESCE(KDAYS_N,0.00) else 0.00 END)) END
			ELSE KDAYS --Рассчитываются не отпускные, а прочие начисления по среднему
			END				
		END)
FROM #TMP

---начисление по месяцам
Select ORDERS, PERIOD, SUMMA, PREM, MATER, 
	DAYS = CASE WHEN @SYST_PAY = 2 THEN 0 ELSE DAYS END, 
	HOURS, 
	DAYS_N = CASE WHEN @SYST_PAY = 2 THEN 0 ELSE DAYS_N END, 
	HOURS_N, CODE_KBK = KBK.CODE, 
	RP_S_PREM = @RP_SUMMA_PREM, RP_SUMMA = @RP_SUMMA, RP_S_MAT = @RP_SUMMA_MAT, 
	RP_DAYS = @RP_DAYS,	RP_HOURS = @RP_HOURS,
	RP_DAYS_N = @RP_DAYS_N,	RP_HOURS_N = @RP_HOURS_N,
	SR_PREM = @SR_PREM, DSUM = @SUMMA_BASE0,
	SUM_DSZ = @DAYS_SZ,
	KOEF = 
	CASE WHEN @PAYMENT = 1 THEN--В рабочих днях 
		CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
			CASE WHEN COALESCE(DAYS,0) >= COALESCE(DAYS_N,0) THEN 1 else 1.2 END
		ELSE 1 --Рассчитываются не отпускные, а прочие начисления по среднему
		END
	ELSE --В календарных днях
	CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
			1
		ELSE 1 --Рассчитываются не отпускные, а прочие начисления по среднему
		END				
	END,
	DAYS_SZ = ROUND(
	CASE WHEN @PAYMENT = 1 THEN--В рабочих днях 
		CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
			CASE WHEN COALESCE(DAYS,0) >= COALESCE(DAYS_N,0) THEN COALESCE(DAYS_N,0) else COALESCE(DAYS,0) * 1.2 END
		ELSE DAYS --Рассчитываются не отпускные, а прочие начисления по среднему
		END
	ELSE --В календарных днях
		CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
					CASE WHEN COALESCE(KDAYS,0.00) <> 0 AND COALESCE(KDAYS,0.00) >= COALESCE(KDAYS_N,0.00) THEN @AvgDays else @AvgDays * (CASE WHEN COALESCE(KDAYS_N,0.00) <> 0.00 THEN COALESCE(KDAYS,0.00) / COALESCE(KDAYS_N,0.00) else 0.00 END) END
		ELSE KDAYS --Рассчитываются не отпускные, а прочие начисления по среднему
		END				
	END,2)
from SDOC_AVAC_TABLE2 T2  LEFT JOIN dbo.SAL_SFIN KBK ON T2.LINK_KBK = KBK.LINK
where link_up = @LINK_DOC
ORDER BY PERIOD

---

DECLARE @FURLOUGH_OPT11 int -- Расчет с учетом районного коэффициента
SET @FURLOUGH_OPT11 = dbo.sa_get_option_by_code('FURLOUGH_OPT11')
---Накручиваем северный коэффициент, если надо
DECLARE @FURLOUGH_GOS_OPT5 int -- Расчет с учетом северного коэффициента
SET @FURLOUGH_GOS_OPT5 = dbo.sa_get_option_by_code('FURLOUGH_GOS_OPT5')

DECLARE @FURLOUGH_GOS_OPT4 varchar(10) --Дата применения районного коэффициента к мат. помощи
SET @FURLOUGH_GOS_OPT4 = COALESCE((SELECT VALUE FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('FURLOUGH_GOS_OPT4'))) AND SID IS NULL),'')
SET @FURLOUGH_GOS_OPT4 = CASE WHEN @FURLOUGH_GOS_OPT4 LIKE '%.  .%' THEN '' ELSE @FURLOUGH_GOS_OPT4 END

SET @FURLOUGH_GOS_OPT4 = CASE WHEN LTRIM(RTRIM(@FURLOUGH_GOS_OPT4)) = '' THEN '01.01.1900' else LTRIM(RTRIM(@FURLOUGH_GOS_OPT4)) END


select INSTR = @INSTR, CODE_PAYS = P.CODE, NAME_PAYS = P.NAME, S.SUMMA,
	RAION_S = S.SUMMA *
	CASE WHEN @FURLOUGH_OPT11 = 1 THEN
		CASE WHEN WAY_CALC = 12
			THEN (CASE WHEN @DATE_BEG >= CONVERT(DATETIME,@FURLOUGH_GOS_OPT4,104) THEN DBO.SA_GET_REGION(@LINK_EMPL,@DATE_BEG,1) / 100  ELSE 1 END) 
			ELSE DBO.SA_GET_REGION(@LINK_EMPL,@DATE_BEG,1) / 100
		END
	ELSE 0
	END,
	NORHT_S = S.SUMMA * CASE WHEN @FURLOUGH_GOS_OPT5 = 1 THEN DBO.SA_GET_REGION(@LINK_EMPL,@DATE_BEG,2) / 100 ELSE 0 END
INTO #TMPA
from 
	dbo.SA_ALL_PAYS_ALL_DATE0(@LINK_EMPL, @DATE_BEG, DEFAULT, @LINK_DEP) S
	inner join dbo.pays P on s.link_pay = p.link
where 
	WAY_CALC not in (6, 7, 12)
	AND
	s.link_pay IN (Select T.PAY_LINK FROM dbo.group_pays(@LINK_PAYS) T)

IF NOT EXISTS (SELECT * FROM #TMPA)
	INSERT INTO #TMPA (INSTR, CODE_PAYS, NAME_PAYS) 
	VALUES (1, '', '')

SELECT * FROM #TMPA

---начисление по расчету
Select ORDERS, DATE1, DATE2, DAYS, HOURS, KOEF_IDX, SR_ZP, SUMMA, 
	CODE_KBK = KBK.CODE, ITOGO_DNI = @ITOGO_DNI, ITOGO_CH = @ITOGO_CH
from SDOC_AVAC_TABLE1 T2  LEFT JOIN dbo.SAL_SFIN KBK ON T2.LINK_KBK = KBK.LINK
where link_up = @LINK_DOC 




GO


GRANT EXECUTE ON dbo.[SA_REP_FUR] TO PUBLIC

GO




GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BB_EXPORT_SPR]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_EXPORT_SPR]
GO


/*
© Кейсистемс (Keysystems), 2005
*/

CREATE PROCEDURE BB_EXPORT_SPR 
		@cBuffId	varchar(30) = '',
		@cObjCode	varchar(30) = ''

AS 
declare @iSum int
set @iSum = 0
-- Таблица 1
-- Код справочника
select  LINK = 0,
	LINK_UP = 0,
	KOD_SPR = case @cObjCode when 'BI_DICTION_INCOME'  	then 'DICTIONARY_INCOME'
				 when 'BI_DICTION_EXP' 	   	then 'DICTIONARY_EXPEND'
				 when 'BI_DICTION_IVF'	   	then 'DICTIONARY_SOURCE'
				 when 'BI_DICTION_KBK2'		then 'DICTIONARY_KBK_INC'
				 when 'BI_DICTION_KBK1'   	then 'DICTIONARY_KBK_EXP'
				 when 'BI_DICTION_KBK4'   	then 'DICTIONARY_KBK_SOURCE'
				 when 'BD_DOP_CLASSIF' 	   	then 'DICTIONARY_ADD_BK'
				 when 'BI_DICTION_DIV' 	   	then 'DICTIONARY_DIVISION'
				 when 'DICTIONARY_TARGET_PROG' 	then 'DICTIONARY_PROGRAM'
				 when 'BI_DICTION_CSR' 	  	then 'DICTIONARY_TARGET_ITEM'
				 when 'DICTIONARY_ITEM'   	then 'DICTIONARY_ITEM'
				 when 'DICTIONARY_KOSGU'   	then 'DICTIONARY_ITEM'
				 when 'DICTIONARY_BANK'   	then 'DICTIONARY_BANK'
				 when 'DICTIONARY_DEPARTMENT'	then 'DICTIONARY_CORR'
				 when 'DICTIONARY_TREASURY'	then 'DICTIONARY_CORR'
				 when 'DICTIONARY_ACCOUNTS'	then 'DICTIONARY_ACCOUNT'
				 when 'DICTIONARY_K_ACCOUNTS'	then 'DICTIONARY_ACCOUNT'
				 when 'BB_DICTION_PROG'	then 'DICTIONARY_PROGRAM'
				 
		 end


-- Таблица 2
-- в зависимости от справочника
IF @cObjCode = 'BI_DICTION_INCOME'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME] = LNAME,
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = ''
	from dbo.KL_KD
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'BI_DICTION_EXP'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME] = [LNAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = ''  
	from dbo.KL_EXPEND
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'BI_DICTION_IVNESHF'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = ''  
	from dbo.BI_DICTION_IVNESHF
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'BI_DICTION_IVF'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = ''  
	from dbo.BI_DICTION_IVF
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'BB_DICTION_PROG'
begin
	select 	LINK,
			LINK_UP = LINK,
			CODE, 
			[SNAME] = cast([NAME] as varchar(45)),
			[NAME] = [LNAME],
			DATE_BEGIN = cast(null as datetime),  
			DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = '' 
	from dbo.KL_PROG
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end IF @cObjCode = 'BD_DOP_CLASSIF'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime) ,
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = '' 
	from dbo.DOP_CLASSIF
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'BI_DICTION_DIV'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME] = [LNAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = ''   
	from dbo.KL_DIVISION
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'DICTIONARY_TARGET_PROG'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = ''   
	from dbo.DICTIONARY_TARGET_PROG
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'BI_DICTION_CSR'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME]  = cast([NAME] as varchar(512)),
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = '' 
	from dbo.BI_DICTION_CSR
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'DICTIONARY_ITEM' or @cObjCode = 'DICTIONARY_KOSGU'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = ''   
	from dbo.DICTIONARY_ITEM               
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 

IF left(@cObjCode,14) = 'BI_DICTION_KBK'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE = cast(replace(CODE,'.','') as varchar(20)), 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME] ,
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = ''  
	from dbo.KL_KBK               
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 

IF @cObjCode = 'DICTIONARY_BANK'
begin
	select 	LINK,
		LINK_UP = LINK,
		BIC = cast(replace(BIK,'.','') as varchar(20)), 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME] = FNAME,
		KS,
		CITY,
		STATE = 1  
	from dbo.DICTIONARY_BANK                
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by BIK
	set @iSum = @@rowcount 
end 

IF @cObjCode = 'DICTIONARY_DEPARTMENT'
begin
	select 	LINK,
		LINK_UP = LINK,
		INN     = cast(INN_LONG as char(12)),
		CODE_BP = cast(BUDG as char(5)),
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME]  = [FULL_NAME],
		CPPU	= KPP,	
		OKATO	= cast(replace(OKATO,' ','') as char(11)),
		ADRESS  = isnull(rtrim(cast(dbo.GetAddressByKladr(REF_LINK_A) + CASE when HOUSE is null or HOUSE = '' then '' else ' ,' + HOUSE end   as varchar(100))),'')
	from dbo.DICTIONARY_DEPARTMENT D                
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by INN
	set @iSum = @@rowcount 
end 

IF @cObjCode = 'DICTIONARY_TREASURY'
begin
	select 	LINK,
		LINK_UP = LINK,
		INN,
		CODE_BP = '',
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME]  = [FULL_NAME],
		CPPU	= KPP,	
		OKATO	= '',
		ADRESS  = isnull(rtrim(cast(dbo.GetAddressByKladr(REF_LINK_A) + CASE when HOUSE is null or HOUSE = '' then '' else ' ,' + HOUSE end   as varchar(100))),'')
	from dbo.DICTIONARY_TREASURY                
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by INN
	set @iSum = @@rowcount 
end 

IF @cObjCode = 'DICTIONARY_ACCOUNTS'
begin
	select 	DA.LINK,
		LINK_UP    = DA.LINK,
		CACCOUNT   = DA.CODE,
		ACC_TYPE   = '',
		ACC_VID    = '',
		STATE      = 1,
		CCORR      = D.INN_LONG,
		CORR_BP    = cast(D.BUDG as char(5)),
		CORR_SNAME = cast(D.[NAME] as varchar(20)),
		BANK_BIC   = isnull(B.BIK,''),
		BANK_KS	   = isnull(B.KS,''),	
		BANK_SNAME = isnull(cast(B.[NAME] as varchar(100)),''),
		TOP_ACC    = isnull(TA.CODE,'')
	from dbo.DEPARTMENT_ACCOUNTS DA
	inner join dbo.DICTIONARY_DEPARTMENT D on DA.LINK_UP = D.LINK and D.LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))               
	left join dbo.BANKS B on B.LINK = DA.BANK_LINK and DA.BANK_LINK is not null
	left join dbo.TREASURY_ACCOUNTS TA on DA.TA_LINK = TA.LINK  and DA.TA_LINK is not null
	order by DA.CODE
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'DICTIONARY_K_ACCOUNTS'
begin
	select 	TA.LINK,
		LINK_UP    = TA.LINK,
		CACCOUNT   = TA.CODE,
		ACC_TYPE   = '',
		ACC_VID    = '',
		STATE      = 1,
		CCORR      = T.INN,
		CORR_BP    = '',
		CORR_SNAME = cast(T.[NAME] as varchar(20)),
		BANK_BIC   = isnull(B.BIK,''),
		BANK_KS	   = isnull(B.KS,''),	
		BANK_SNAME = isnull(cast(B.[NAME] as varchar(100)),''),
		TOP_ACC    = ''
	from dbo.TREASURY_ACCOUNTS TA
	inner join dbo.TREASURY T on TA.LINK_UP = T.LINK and T.LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))               
	left join dbo.BANKS B on B.LINK = TA.BANK_LINK               
	order by TA.CODE
	set @iSum = @@rowcount 
end 


-- Таблица 3
-- Колличество записей
select  LINK = 0,
	LINK_UP = 0,
	[SUM] = @iSum



GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RSA_RSV_1_PERS_UCH]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RSA_RSV_1_PERS_UCH]

GO
-- exec [dbo].RSA_RSV_1_PERS_UCH '20140101', '20140331', 74620 , 0, 17643
CREATE PROCEDURE dbo.RSA_RSV_1_PERS_UCH
	@dDate1 DATETIME,
	@dDate2 DATETIME,
	@LINK_DEP int = NULL,
	@REP TINYINT = 0, 
	@VARILSF INT = null
AS BEGIN

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output

	SET @DEP_LINK = COALESCE(@LINK_DEP,@DEP_LINK)

	DECLARE @ATR_PERS_UCH INT
	SET @ATR_PERS_UCH  = (SELECT DBO.RN_GET_ATR_VALUE(@VARILSF, 'REPORTS_ATR_PERS_UCH'))
	
	SELECT * into #docs FROM  dbo.SA_SZV4_PACHKA P 
	WHERE
	p.link_dep = @DEP_LINK and p.link = @ATR_PERS_UCH
	
	SELECT * into #docs_kor_otm FROM  dbo.SA_SZV4_PACHKA P 
	WHERE
	p.link_dep = @DEP_LINK and p.year_begin = year(@dDate1) and month_end = month(@dDate2) and p.type = 1 and vid_kor <> 1
	/*AND p.[per_edt] < p.[per] */AND p.YEAR_EDT >= 2014  AND P.LINK_ISHOD = @ATR_PERS_UCH


	--Округление каждой строчки таблицы
	DECLARE @ROUND_TYPE tinyint, @ROUND_LEN tinyint
	Set @ROUND_TYPE = dbo.sa_get_option_by_code('SA_SZV4_OPT2')
	Set @ROUND_LEN = (case when @ROUND_TYPE <= 1 then 2 else 0 end)
	Set @ROUND_TYPE = (case when @ROUND_TYPE = 3 then 1 else 0 end)

	--Округление только итогов
	DECLARE @IT_ROUND_TYPE tinyint
	Set @IT_ROUND_TYPE = dbo.sa_get_option_by_code('SA_SZV4_OPT5')


	IF @REP = 0 
	BEGIN 
		Select 	
			[YEAR] = ISNULL(CASE WHEN year_begin >= 2013 THEN year_begin ELSE NULL END ,0),
			[NGROUP] = S.pachka,
			[DOCCOUNT] = COALESCE(MAX(case when S.forma = 2 then CEILING (CAST(S.orders AS FLOAT) /5 ) else 0 end),0)
					+ SUM(case when S.forma = 1 then 1 else 0 end),
			[PERS_CNT] = COUNT(S.orders),
			[cGRP] = REPLACE(str(S.pachka,5),' ','0'),
			[OPT1] = (case when p.type = 1 then 1 else 0 end),
			[OPT2] = (case when p.type = 2 then 1 else 0 end),
			[OPT3] = (case when vid_kor = 2 then 1 else 0 end),
			[OPT4] = (case when vid_kor = 3 then 1 else 0 end),
			INC_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.INCOME_M1)),@ROUND_LEN,@ROUND_TYPE),																																	
			INC_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.INCOME_M2)),@ROUND_LEN,@ROUND_TYPE),																														
			INC_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.INCOME_M3)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M1)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M2)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M3)),@ROUND_LEN,@ROUND_TYPE),
			B_AFT_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_AFTER_M1)),@ROUND_LEN,@ROUND_TYPE),
			B_AFT_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_AFTER_M2)),@ROUND_LEN,@ROUND_TYPE),
			B_AFT_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_AFTER_M3)),@ROUND_LEN,@ROUND_TYPE),
			[INSUR] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_doh)),@ROUND_LEN,@ROUND_TYPE),
			[INSUR1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_str)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_nak)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dop)),@ROUND_LEN,@ROUND_TYPE),
			sd_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_str)),@ROUND_LEN,@ROUND_TYPE),
			sud_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_str)),@ROUND_LEN,@ROUND_TYPE),
			sd_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_nak)),@ROUND_LEN,@ROUND_TYPE),
			sud_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_nak)),@ROUND_LEN,@ROUND_TYPE),
			[PER] = ISNULL(CASE WHEN year_begin >= 2013 THEN PER ELSE NULL END ,0) ,
			[PER10] = ISNULL(CASE WHEN year_begin >= 2013 THEN PER ELSE NULL END ,0) ,
			[TYPE] = p.[vid_kor],
			[PER_EDT] = ISNULL(PER_EDT,0),
			[YEAR_EDT] = ISNULL(YEAR_EDT,0),
			[T_DOG] = s.forma,
			DATE_CRT = '20131201',
			DATE_DOC = [date],
			SZV = MAX(S.forma), 
			FNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),year_begin) + '-ORG-' + LTRIM(RTRIM(d.PFNUMBER)) + '-DCK-' + REPLACE(str(S.pachka,5),' ','0') + '-DPT-000000-DCK-00000.XML',
			LINK_DOC = P.link,
			link_pers = S.link_pers
		into #TMP
		from 
			dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up  AND (s.forma = 1 
															OR s.forma = 2 AND NOt EXISTS(SELECT * from dbo.SZV4_SVEDENIA WHERE  link_up = S.link_up and link_pers = s.link_pers AND forma = 1) )
			
			INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND
			inner join departments d on d.link = p.link_dep 
		where
			P.link in (select link from #DOCS)
			and P.proverka = 1
			and p.link_dep = @DEP_LINK
			--AND S.forma = 1
		group by
			s.pachka, s.Forma, year_begin, p.[vid_kor], p.[TYPE], [date], K.CODE, PER, PER_EDT, YEAR_EDT, d.PFNUMBER, P.[link], S.link_pers
		order by
			S.pachka


		Select 	
			[YEAR] = ISNULL(CASE WHEN year_begin >= 2013 THEN year_begin ELSE NULL END ,0),
			[NGROUP] = S.pachka,
			[DOCCOUNT] = COALESCE(MAX(case when S.forma = 2 then CEILING (CAST(S.orders AS FLOAT) /5 ) else 0 end),0)
					+ SUM(case when S.forma = 1 then 1 else 0 end),
			[PERS_CNT] = COUNT(S.orders),
			[cGRP] = REPLACE(str(S.pachka,5),' ','0'),
			[OPT1] = (case when p.type = 1 then 1 else 0 end),
			[OPT2] = (case when p.type = 2 then 1 else 0 end),
			[OPT3] = (case when vid_kor = 2 then 1 else 0 end),
			[OPT4] = (case when vid_kor = 3 then 1 else 0 end),
			INC_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.INCOME_M1)),@ROUND_LEN,@ROUND_TYPE),																																	
			INC_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.INCOME_M2)),@ROUND_LEN,@ROUND_TYPE),																														
			INC_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.INCOME_M3)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M1)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M2)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M3)),@ROUND_LEN,@ROUND_TYPE),
			B_AFT_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_AFTER_M1)),@ROUND_LEN,@ROUND_TYPE),
			B_AFT_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_AFTER_M2)),@ROUND_LEN,@ROUND_TYPE),
			B_AFT_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_AFTER_M3)),@ROUND_LEN,@ROUND_TYPE),
			[INSUR] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_doh)),@ROUND_LEN,@ROUND_TYPE),
			[INSUR1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_str)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_nak)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dop)),@ROUND_LEN,@ROUND_TYPE),
			sd_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_str)),@ROUND_LEN,@ROUND_TYPE),
			sud_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_str)),@ROUND_LEN,@ROUND_TYPE),
			sd_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_nak)),@ROUND_LEN,@ROUND_TYPE),
			sud_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_nak)),@ROUND_LEN,@ROUND_TYPE),
			[PER] = ISNULL(CASE WHEN year_begin >= 2013 THEN PER ELSE NULL END ,0),
			[PER10] = ISNULL(CASE WHEN year_begin >= 2013 THEN PER ELSE NULL END ,0),
			[TYPE] = p.[vid_kor],
			[PER_EDT] = ISNULL(PER_EDT,0),
			[YEAR_EDT] = ISNULL(YEAR_EDT,0),
			[T_DOG] = s.forma,
			DATE_CRT = '20131201',
			DATE_DOC = [date],
			SZV = MAX(S.forma), 
			FNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),year_begin) + '-ORG-' + LTRIM(RTRIM(d.PFNUMBER)) + '-DCK-' + REPLACE(str(S.pachka,5),' ','0') + '-DPT-000000-DCK-00000.XML',
			LINK_DOC = P.link,
			link_pers = S.link_pers
		into #TMP_1
		from 
			dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up  
																	and s.forma = 2 
																	AND EXISTS(SELECT * from dbo.SZV4_SVEDENIA WHERE  link_up = S.link_up and link_pers = s.link_pers AND forma = 1) 
			
			INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND
			inner join departments d on d.link = p.link_dep 
		where
			P.link in (select link from #DOCS)
			and P.proverka = 1
			and p.link_dep = @DEP_LINK
			--AND S.forma = 1
		group by
			s.pachka, s.Forma, year_begin, p.[vid_kor], p.[TYPE], [date], K.CODE, PER, PER_EDT, YEAR_EDT, d.PFNUMBER, P.[link] , S.link_pers
		order by
			S.pachka

		UPDATE t 
			SEt t.INC_M1 = t.INC_M1+ t1.INC_M1, 
				t.INC_M2 = t.INC_M2+ t1.INC_M2,
				t.INC_M3 = t.INC_M3 + t1.INC_M3 ,
				t.B_BEF_M1 = t.B_BEF_M1 + t1.B_BEF_M1,
				t.B_BEF_M2 = t.B_BEF_M2 + t1.B_BEF_M2, 
				t.B_BEF_M3 = t.B_BEF_M3 + t1.B_BEF_M3,
				t.B_AFT_M1 = t.B_AFT_M1 + t1.B_AFT_M1,
				t.B_AFT_M2 = t.B_AFT_M2 + t1.B_AFT_M2, 
				t.B_AFT_M3 = t.B_AFT_M3 + t1.B_AFT_M3,
				t.[INSUR] =  t.[INSUR] + t1.[INSUR] ,
				t.[INSUR1] = t.[INSUR1] + t1.[INSUR1],
				t.[GAIN] = t.[GAIN] + t1.[GAIN] ,
				t.[GAIN1] = t.[GAIN1] + t1.[GAIN1] ,
				t.sd_str = t.sd_str + t1.sd_str,
				t.sud_str = t.sud_str + t1.sud_str,
				t.sd_nak = t.sd_nak + t1.sd_nak,
				t.sud_nak = t.sud_nak + t1.sud_nak
		FROM #TMP t inner join #TMP_1 t1 ON t.LINK_PERS = t1.link_pers

			SELECT
				CODE = CONVERT(VARCHAR(10), [NGROUP]),
				COL1 = CONVERT(VARCHAR(10),[NGROUP]),
				COL2 = CONVERT(VARCHAR(10),''),
				COL3 = isnull((SUM(isnull(b_bef_m1,0)) + SUM(isnull(b_bef_m2,0)) + SUM(isnull(b_bef_m3,0))),0.00),
				COL4 = SUM(isnull(insur,0.00)),
				COL5 = SUM(ISNULL(pers_cnt,0)),
				COL6 = isnull(fname,''),
				COL7 = CONVERT(VARCHAR(10), date_doc, 104),
				COL8 = [TYPE],
				COL9 = PER,
				COL10 = [YEAR],
				COL11 = [LINK_DOC]
					
			FROM
				#TMP 
			GROUP BY [NGROUP], fname , date_doc	, [TYPE] , PER , [YEAR] , [LINK_DOC]
			ORDER BY
				NGROUP

		drop table #TMP	
		drop table #TMP_1
			
	END
	
	IF @REP = 1 
	BEGIN 	
		Select 	
			[YEAR] = ISNULL(CASE WHEN year_begin >= 2013 THEN year_begin ELSE NULL END ,0),
			[MONTH] = ISNULL(month_end ,0),
			[PER] = PER,
			[NGROUP] = S.pachka,
			[cGRP] = REPLACE(str(S.pachka,5),' ','0'),
			[CODE] = K.CODE,
			[INSUR] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_doh)),@ROUND_LEN,@ROUND_TYPE),
			[INSUR1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_str)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_nak)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dop)),@ROUND_LEN,@ROUND_TYPE),
			sd_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_str)),@ROUND_LEN,@ROUND_TYPE),
			sud_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_str)),@ROUND_LEN,@ROUND_TYPE),
			sd_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_nak)),@ROUND_LEN,@ROUND_TYPE),
			sud_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_nak)),@ROUND_LEN,@ROUND_TYPE),		
			[PERS_CNT] = COUNT(S.orders),
			[PER_EDT] = ISNULL(PER_EDT,0 ),
			[YEAR_EDT] = ISNULL(YEAR_EDT,0),
			FNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),year_begin) + '-ORG-' + LTRIM(RTRIM(d.PFNUMBER)) + '-DCK-' + REPLACE(str(S.pachka,5),' ','0') + '-DPT-000000-DCK-00000.XML',
			IT_ROUND = @IT_ROUND_TYPE,
			DATE_DOC = p.[date],
			[TYPE] = p.[vid_kor],
			B_BEF_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M1)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M2)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M3)),@ROUND_LEN,@ROUND_TYPE),
			[T_DOG] = s.forma,
			LINK_DOC = P.link,
			link_pers = S.link_pers,
			dep_pFNUM = d.PFNUMBER
		into #TMP1
		from 
			dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up AND (s.forma = 1 
															OR s.forma = 2 AND NOt EXISTS(SELECT * from dbo.SZV4_SVEDENIA WHERE  link_up = S.link_up and link_pers = s.link_pers AND forma = 1) )
			INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND
			inner join departments d on d.link = p.link_dep
		where
			P.link in (select link from #docs_kor_otm)
			and P.proverka = 1
			and P.vid_kor > 1
			and p.link_dep = @DEP_LINK
		group by
			s.pachka, s.Forma, year_begin,month_end,per, p.[vid_kor], K.CODE, PER_EDT, YEAR_EDT, d.PFNUMBER, p.[date], P.[link],S.link_pers
	
	
-------- нумерация пачек для корректирующих в зависимости от исходных сведений	
declare @MAX_PACHKA_ISHOD  int,@MIN_PACHKA_ISHOD int,  @MIN_PACHKA_KORR int,  
		@COUNT int , @ID int

select @MAX_PACHKA_ISHOD = max(s.pachka),
		@MIN_PACHKA_ISHOD = min(s.pachka),
		@MIN_PACHKA_KORR = (select max(s.pachka) FROM dbo.SA_SZV4_PACHKA p INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up and P.LINK = @ATR_PERS_UCH)
		FROM dbo.SA_SZV4_PACHKA p INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up and P.LINK_ISHOD = @ATR_PERS_UCH

IF @min_PACHKA_ISHOD = @MIN_PACHKA_KORR
BEGIN 
	declare @Cur cursor , @GR int , @cGR int
	set @ID = 1
	SET @Cur = CURSOR FORWARD_ONLY
	FOR 
		select ngroup,cGRP  from #tmp1 group by ngroup,cGRP
	OPEN @Cur
	FETCH NEXT FROM @Cur INTO @GR, @cGR
	
	WHILE (@@fetch_status <> -1)
	BEGIN
		
		IF (@@fetch_status <> -2)
		BEGIN	

			UPDATE #tmp1
				set NGROUP = @MAX_PACHKA_ISHOD+@ID --, t.[cGRP] =  '00'+ (@MAX_PACHKA_ISHOD+@ID)
			where ngroup = @GR AND cGRP = @cGR
				
			set @ID = @ID+1	
		end
		FETCH NEXT FROM @Cur INTO @GR , @cGR
	end

	CLOSE @Cur
	DEALLOCATE @Cur

END 

UPDATE t
	SET  cGRP=  '00'+ convert(varchar(3),NGROUP) 
	from #tmp1 t 
UPDATE t
	SET  FNAME=  'PFR-700-Y-' + CONVERT(VARCHAR(4),[year]) + '-ORG-' + LTRIM(RTRIM(dep_pFNUM)) + '-DCK-' + REPLACE(str(NGROUP,5),' ','0') + '-DPT-000000-DCK-00000.XML'	
	from #tmp1 t  WHERE TYPE <> 1
	

		Select 	
			[YEAR] = ISNULL(CASE WHEN year_begin >= 2013 THEN year_begin ELSE NULL END ,0),
			[MONTH] = ISNULL(month_end ,0),
			[PER] = case PER when 1 then 3 when 2 then 6 when 3 then 9 when 4 then 0 else null end,
			[NGROUP] = S.pachka,
			[cGRP] = REPLACE(str(S.pachka,5),' ','0'),
			[CODE] = K.CODE,
			[INSUR] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_doh)),@ROUND_LEN,@ROUND_TYPE),
			[INSUR1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_str)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_nak)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dop)),@ROUND_LEN,@ROUND_TYPE),
			sd_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_str)),@ROUND_LEN,@ROUND_TYPE),
			sud_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_str)),@ROUND_LEN,@ROUND_TYPE),
			sd_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_nak)),@ROUND_LEN,@ROUND_TYPE),
			sud_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_nak)),@ROUND_LEN,@ROUND_TYPE),		
			[PERS_CNT] = COUNT(S.orders),
			[PER_EDT] = case ISNULL(PER_EDT,0) when 1 then 3 when 2 then 6 when 3 then 9 when 4 then 0 else null end,
			[YEAR_EDT] = ISNULL(YEAR_EDT,0),
			FNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),year_begin) + '-ORG-' + LTRIM(RTRIM(d.PFNUMBER)) + '-DCK-' + REPLACE(str(S.pachka,5),' ','0') + '-DPT-000000-DCK-00000.XML',
			IT_ROUND = @IT_ROUND_TYPE,
			DATE_DOC = p.[date],
			[TYPE] = p.[vid_kor],
			B_BEF_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M1)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M2)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M3)),@ROUND_LEN,@ROUND_TYPE),
			[T_DOG] = s.forma,
			LINK_DOC = P.link,
			link_pers = S.link_pers
		into #TMP1_1
		from 
			dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up 																	
																	and s.forma = 2 
																	AND EXISTS(SELECT * from dbo.SZV4_SVEDENIA WHERE  link_up = S.link_up and link_pers = s.link_pers AND forma = 1) 
			INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND
			inner join departments d on d.link = p.link_dep
		where
			P.link in (select link from #docs_kor_otm)
			and P.proverka = 1
			and P.vid_kor > 1
			and p.link_dep = @DEP_LINK
		group by
			s.pachka, s.Forma, year_begin,month_end,per, p.[vid_kor], K.CODE, PER_EDT, YEAR_EDT, d.PFNUMBER, p.[date], P.[link],S.link_pers

		UPDATE t 
			SEt t.[INSUR] =  t.[INSUR] + t1.[INSUR] ,
				t.[INSUR1] = t.[INSUR1] + t1.[INSUR1],
				t.[GAIN] = t.[GAIN] + t1.[GAIN] ,
				t.[GAIN1] = t.[GAIN1] + t1.[GAIN1] ,
				t.sd_str = t.sd_str + t1.sd_str,
				t.sud_str = t.sud_str + t1.sud_str,
				t.sd_nak = t.sd_nak + t1.sd_nak,
				t.sud_nak = t.sud_nak + t1.sud_nak
		FROM #TMP1 t inner join #TMP1_1 t1 ON t.LINK_PERS = t1.link_pers


	
	SELECT
			CODE = CONVERT(VARCHAR(10), [NGROUP]),
			COL1 = CONVERT(VARCHAR(10),[NGROUP]),
			COL2 = CONVERT(VARCHAR(10),''),
			COL3 = CONVERT(VARCHAR(10),per_edt),
			COL4 = CONVERT(VARCHAR(10),year_edt),
			COL5 = SUM(ISNULL((case when per_edt >= 2014 then sd_str else 0 end),0)),
			COL6 = SUM(ISNULL((case when per_edt < 2014 then sd_str else 0 end),0)),
			COL7 = SUM(ISNULL((case when per_edt < 2014 then sd_nak else 0 end),0)),
			COL8 = SUM(ISNULL(PERS_CNT, 0)),
			COL9 = isnull(fname,''),
			COL10 = CONVERT(VARCHAR(10), date_doc, 104),
			COL11 = [TYPE],
			COL12 = CONVERT(VARCHAR(1),PER),
			COL13 = CONVERT(VARCHAR(4),[YEAR]),
			COL14 = isnull((SUM(isnull(b_bef_m1,0)) + SUM(isnull(b_bef_m2,0)) + SUM(isnull(b_bef_m3,0))),0.00),
			COL15 = SUM(ISNULL([INSUR],0)),
			COL16 = [LINK_DOC]
		FROM
			#TMP1
		GROUP BY [NGROUP],per_edt,year_edt, fname , date_doc	, [TYPE] , PER , [YEAR] , [LINK_DOC]	
		ORDER BY
			NGROUP
		
		drop table #TMP1
		drop table #TMP1_1

	END 
	
		drop table #docs_kor_otm
		drop table #docs

END










GO


GRANT EXECUTE ON dbo.[RSA_RSV_1_PERS_UCH] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BV_GET_DOC_WAYBILL_MAX_NUM]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BV_GET_DOC_WAYBILL_MAX_NUM]

GO

CREATE PROCEDURE [dbo].BV_GET_DOC_WAYBILL_MAX_NUM
	@varKSintLinkAuto	INT	
AS

DECLARE @varKSstrMaxNum VARCHAR (40), @varKSnumMaxNum NUMERIC (30)

SELECT @varKSstrMaxNum = '0'

SELECT @varKSstrMaxNum = MAX(REPLACE(SPACE(25-len(RTRIM(DW.NUMBER)))+RTRIM(DW.NUMBER), ' ','0'))
FROM dbo.BV_DOC_WAYBILL DW, USER_INFO UI
WHERE DW.AUTO_LINK = @varKSintLinkAuto AND YEAR(DW.DATE) = YEAR(UI.WORKDATE)


IF ISNUMERIC(@varKSstrMaxNum) = 1
	SET @varKSnumMaxNum = CONVERT(NUMERIC(25), @varKSstrMaxNum)
ELSE
	SET @varKSnumMaxNum = 0

RETURN @varKSnumMaxNum

GO

GRANT EXECUTE ON dbo.[BV_GET_DOC_WAYBILL_MAX_NUM] TO PUBLIC

GO


--Расширенные свойства--


GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FB_CREATE_PROV_FROM_REP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FB_CREATE_PROV_FROM_REP]
GO

-- Формирование проводок в расходном расписании

CREATE	PROCEDURE dbo.FB_CREATE_PROV_FROM_REP @iLinkForm int

as

declare @iTypLink 	int,
		@iLink 		int,
		@iLinkUp 	int,
		@cNameOper 	varchar(250),
		@nSumma 	numeric(28,2),
		@iKBK 		int,
		@iEKR 		int,
		@iDep 		int, 
		@iDepPol 	int,
		--@iDepAcc	int, 
		@iLinkGp1 	int,
		@iOrders 	int,
		@cNameG2 	varchar(254),

 		@xRet		int,
		@cErrTxt 	varchar(60),
		@cRunStr	varchar(1000),
		@iERROR		int,
		@iCountProv	int,
		@iSummaDoc	numeric(28,2),
		@Cur1		CURSOR,
	
		
-- Документ
		@cDocNum	char(25),
		@iDocLink	int,
		@dDocDate	datetime,
		@iDocDep	int,
		@iDocType	int,
		@cComment	varchar(8000),
-- Форма
		@iLT		int
		


-- Берем данные из формы	
select top 1 @iLT 	  = RT.LINK_TABLE, 
			 @iDocDep = RSF.Link_Organization,
			 @cComment = 'Сформирован из формы от ' + convert(char(10),RSF.Begin_Date,104) + ' ' + RSF.Note
from dbo.REPORT_TABLES RT
inner join dbo.REPORT_SAVED_FORMS RSF on RT.LINK_FORM = RSF.LINK_FORM 
					 and RSF.LINK_SAVED_FORM = @iLinkForm

set @cRunStr = 'insert into #Temp exec RI_PROC_T' + ltrim(str(@iLT)) + ' ' + ltrim(str(@iLinkForm))

create table #Temp (CECKED			int,
					UPD				int,
					DEL				int,
					LINK_SAVED_FORM	int,
					LINK_ROW		int,
					ORDERS			int,
					CALC_ORDERS		int,
					PRINT_NULL		int,
					CODE 			varchar(250),
					COL1 			varchar(250), 
					FCOL1 			varchar, 
					COL2 			varchar(250),
					COL3			varchar(17),
					FCOL3			varchar,
					COL4			numeric(20,2 ),
					FCOL4			varchar,
					COL5			numeric(20,2 ),
					FCOL5			varchar,
					COL6			numeric(20,2 ),
					FCOL6			varchar,
					COL7			numeric(20,2 ),
					FCOL7			varchar,
					COL8			numeric(20,2 ),
					FCOL8			varchar,
					COL9			numeric(20,2 ),
					FCOL9			varchar,
					COL10			numeric(20,2 ),
					FCOL10			varchar,
					COL11			numeric(20,2 ),
					FCOL11			varchar)
execute (@cRunStr) 

-- Создаем документ
select @iDocType = LINK from DICTIONARY_DOC_TYPES where CODE = 'KR'
exec X_DOCUMENT_GET_NEXT_NUMBER 'DOCUMENTS_OPER', @cDocNum output, @iDocDep

select @dDocDate = WORKDATE from dbo.USER_INFO

EXEC @iERROR = dbo.X_SAVE_DOCUMENTS_OPER @iDocLink OUTPUT, @cDocNum, @dDocDate, @dDocDate, 0, @cComment, DEFAULT, @iDocType, @iDep
IF @iERROR <> 0
begin
	select 'Документ не сформирован!
Ошибка при создании документа!' as RES
	RETURN -1
end
SET @iCountProv = 0
SET @iSummaDoc = 0
select @iEKR = LINK from dbo.KOSGU where CODE = '251' 
-- Добываем типовую операцию
select @iTypLink = LINK_OPER 
from dbo.DOC_NASTR_T1 N
inner join dbo.S_OBJECTS SO on SO.LINK = N.LINK_UP and SO.CODE = 'BB_UVED_817_69N'

if @iTypLink is null or @iTypLink <= 0
begin
	select 'Документ не сформирован!
Не задана типовая операция!' as RES
	return - 2
end 


select @cNameOper = G1.NAME_OPER,
	 @cNameG2 = XO.NAME
from G_PROV1 G1
left join dbo.XOZ_OPER XO on G1.OPER = XO.LINK   
where G1.LINK = @iTypLink
if @cNameG2 is null
	set @cNameG2 = 'Сформированы из формы 63'


SET @Cur1 = CURSOR FORWARD_ONLY FOR
select D.Link, KBKR.LINK, T.Col10
from #Temp T
inner join dbo.DEPARTMENTS D on replace(D.OKTMO,' ','') = T.Col2
inner join dbo.KL_ADMIN_BS A on D.VED_LINK = A.LINK
inner join dbo.KL_KBK KBKD on replace(KBKD.CODE,'.','') = A.CODE + left(T.Col3,14) or replace(KBKD.CODE,'.','') = '000' + left(T.Col3,8) + '00' + substring(T.Col3,11,4)
inner join (select LINK, LINK_KBK from dbo.KL_KBK_LINKED union
			select LINK_KBK, LINK from dbo.KL_KBK_LINKED)KL on KL.LINK = KBKD.LINK 
inner join dbo.KL_KBK KBKR on KL.LINK_KBK = KBKR.LINK

open @Cur1
fetch next from @Cur1 into @iDepPol, @iKBK, @nSumma
while @@FETCH_STATUS = 0
begin
	set @iOrders = @iOrders + 1
	set @iLinkGP1 = NULL
	exec X_UPDATE_G_PROV1 @iLinkGP1 output, @iDocLink, @iTypLink, @cNameOper, @iOrders

	if @iLinkGP1 is null
		RETURN -3	

	exec @xRet = dbo.FB_SAVE_G_PROV2_AP_LIMIT @iLinkGP1, @iTypLink, @nSumma, /*@dCalcDate*/null, @iKBK, @iEKR, null, null, @iDepPol, null, @cNameG2, '1',@iDepPol
	if @xRet <> 0
	  begin
		select 'Ошибка при записи проводки' as RES 
		PRINT  -4	
	 end
	SET @iCountProv = @iCountProv + 1
	SET @iSummaDoc = @iSummaDoc + @nSumma

	fetch next from @Cur1 into @iDepPol, @iKBK, @nSumma
END


exec dbo.X_SALDO_COMMITCHANGES	
drop table #Temp

select 'Сформирован документ № ' + rtrim(@cDocNum) + ' от ' + convert(char(10),@dDocDate,104) + ' (' + ltrim(str(@iCountProv)) + ' операций на сумму ' + ltrim(str(@iSummaDoc,20,2)) + ' руб.)'  as RES
return 0

GO

grant execute on dbo.FB_CREATE_PROV_FROM_REP to public
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[X_SAVE_DOCUMENTS_PAY_ADD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[X_SAVE_DOCUMENTS_PAY_ADD]
GO






/*
© Кейсистемс (Keysystems), 2005
*/

CREATE    


PROCEDURE dbo.X_SAVE_DOCUMENTS_PAY_ADD
	@varKSpLINK		int	OUTPUT,
	@varKSpDOH_LINK       INT = null,
	@varKSpSGU_LINK       INT = null,
	@varKSpOKATO          VARCHAR(11) = null,
	@varKSpP_REASON       VARCHAR(2) = null,
	@varKSpPERIOD         VARCHAR(10) = null,
	@varKSpTREBNUM        VARCHAR(30) = null,
	@varKSpTREBDATE       DATETIME = null,
	@varKSpZERODATE       BIT = null,
	@varKSpP_TYPE         VARCHAR(2) = null,
	@varKSpSTATUS         VARCHAR(2) = null,
	@cUinCode			  varchar(20) = ''
AS
SET LOCK_TIMEOUT 30000
SET IMPLICIT_TRANSACTIONS ON
DECLARE 	@varKSstrVALUE	varchar(7000),
		@varKSEventText	varchar(254),
		@varKSERROR		int,
		@varKSRowCount	int,
		@varKStrancount	int
SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	
	IF exists (select * from FINANSE_PAYS where link = @varKSpLINK)
		UPDATE FINANSE_PAYS
			SET Link_Dohod = @varKSpDOH_LINK,
			Link_SGU = @varKSpSGU_LINK,
			OKATO = @varKSpOKATO,
			P_REASON = @varKSpP_REASON,
			Nal_PERIOD = @varKSpPERIOD,
			TREBNUM = @varKSpTREBNUM,
			TREBDATE = @varKSpTREBDATE,
			ZERODATE = @varKSpZERODATE,
			P_TYPE = @varKSpP_TYPE,
			STATUS = @varKSpSTATUS,
			UIN_CODE = @cUinCode
		WHERE Link = @varKSpLINK
	ELSE 
	BEGIN
		ROLLBACK
		RETURN 2
	END
	SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
	IF @varKSERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
	IF @varKSRowCount = 0
	BEGIN
		ROLLBACK
		RETURN 2
	END

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[KU_PERSON_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KU_PERSON_SAVE]

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE [dbo].KU_PERSON_SAVE
	@parLINK		int	OUTPUT,
	@parFM			varchar(100) = null,--
	@parIM			varchar(100) = null,--
	@parOT			varchar(100) = null,--
	@parSEX			tinyint = null,
	@parBIRTHDATE  		 datetime = null,
	@parBIRTHPLACE		varchar(254) = null,
	@parDOC_LINK		int = null,
	@parDOC_NUM		varchar(20) = null,
	@parDOC_WHOM		varchar(254) = null,
	@parDOC_DATE		datetime = null,
	@parINSUR_NUM		varchar(14) = null,
	@parINN			varchar(12) = null,
	@parCITIZ_LINK		int = null,
	@parNATION_LINK		int = null,
	@parMAR_LINK		int = null,
	@parMED_POL_LINK	int = null,
	@parMED_POL_SER		varchar(15) = '',
	@parMED_POL_NUM		varchar(25) = '',
	@parDRIVER_DOC_NUM	varchar(12) = '',
	@parDRIVER_KLASS	tinyint = 0,
	@parDATE_PENS		datetime = null
AS



SET	@parFM = LEFT(LTRIM(RTRIM(@parFM)),100)
SET	@parIM = LEFT(LTRIM(RTRIM(@parIM)),100)
SET	@parOT = LEFT(LTRIM(RTRIM(@parOT)),100)
SET	@parDOC_NUM = LEFT(LTRIM(RTRIM(@parDOC_NUM)),20)
SET	@parDOC_WHOM = LEFT(LTRIM(RTRIM(@parDOC_WHOM)),254)
SET	@parINSUR_NUM = LEFT(LTRIM(RTRIM(@parINSUR_NUM)),14)
SET	@parINN = LEFT(LTRIM(RTRIM(@parINN)),12)
SET	@parMED_POL_SER = LEFT(LTRIM(RTRIM(@parMED_POL_SER)),10)
SET	@parMED_POL_NUM = LEFT(LTRIM(RTRIM(@parMED_POL_NUM)),25)
SET @parBIRTHPLACE = LEFT(LTRIM(RTRIM(@parBIRTHPLACE)),254)
SET @parDRIVER_DOC_NUM = LEFT(LTRIM(RTRIM(@parDRIVER_DOC_NUM)),12)


DECLARE @trancount int, @SQLError int, @RowCount int, @EventText varchar(254), @ObjectLink int

SET @trancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	
	IF @parFM IS NULL or @parFM='' OR @parIM is null or @parIM='' or @parSEX is null
		or @parDOC_LINK is null or @parDOC_NUM is null  or @parDOC_NUM='' or @parDOC_DATE is null or @parDOC_WHOM is null
		or @parDOC_WHOM='' or @parCITIZ_LINK is null or @parBIRTHDATE is null
	BEGIN
		ROLLBACK
		RETURN 5
	END

	IF @parLINK is null OR @parLINK = 0
	BEGIN
		INSERT INTO person WITH (ROWLOCK) (FM, IM, OT, SEX, BIRTHDATE, BIRTHPLACE, DOC_LINK, DOC_NUM, DOC_WHOM,
				DOC_DATE, INSUR_NUM, INN, CITIZ_LINK, NATION_LINK, MAR_LINK, MED_POL_SER, MED_POL_NUM,DRIVER_DOC_NUM,DRIVER_KLASS,DATE_PENS)
			VALUES (@parFM,	@parIM, @parOT, @parSEX, @parBIRTHDATE, @parBIRTHPLACE,	@parDOC_LINK,
				@parDOC_NUM, @parDOC_WHOM, @parDOC_DATE, @parINSUR_NUM,	@parINN, @parCITIZ_LINK,
				@parNATION_LINK, @parMAR_LINK, @parMED_POL_SER, @parMED_POL_NUM,
				@parDRIVER_DOC_NUM,@parDRIVER_KLASS,@parDATE_PENS)
		SELECT @SQLError = @@ERROR, @parLINK = @@IDENTITY
		IF @SQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		INSERT INTO MED_POL WITH (ROWLOCK) (LINK_PERS,SER, [NUMBER])
			VALUES (@parLINK,@parMED_POL_SER,	@parMED_POL_NUM)
		SELECT @SQLError = @@ERROR, @parMED_POL_LINK = @@IDENTITY
		IF @SQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END		
		UPDATE person set MED_POL_LINK = @parMED_POL_LINK 
		where link = @parLINK
		SELECT @SQLError = @@ERROR
		IF @SQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END		
		--
		DECLARE @DEP_LINK INT
		SET @DEP_LINK = (SELECT DEP_LINK FROM USER_DEP)
		INSERT INTO PERSON_TO_DEP(PERS_LINK, DEP_LINK)
		VALUES (@parLINK, @DEP_LINK)
		--
	END
	
	ELSE
	BEGIN
		UPDATE person SET 
			FM = @parFM, IM = @parIM, OT = @parOT, SEX = @parSEX, BIRTHDATE = @parBIRTHDATE, 
				BIRTHPLACE = @parBIRTHPLACE, DOC_LINK = @parDOC_LINK, DOC_NUM = @parDOC_NUM, 
				DOC_WHOM = @parDOC_WHOM, DOC_DATE = @parDOC_DATE, INSUR_NUM = @parINSUR_NUM,
				INN = @parINN, CITIZ_LINK = @parCITIZ_LINK, NATION_LINK = @parNATION_LINK, MAR_LINK = @parMAR_LINK,
				MED_POL_LINK = @parMED_POL_LINK, MED_POL_SER = @parMED_POL_SER, MED_POL_NUM = @parMED_POL_NUM, DRIVER_DOC_NUM = @parDRIVER_DOC_NUM, DRIVER_KLASS = @parDRIVER_KLASS,DATE_PENS = @parDATE_PENS
		WHERE link=@parLINK
		SELECT @SQLError = @@ERROR, @RowCount = @@ROWCOUNT
		IF @SQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @RowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
		
	
	END

	SELECT @ObjectLink = link FROM s_objects WHERE code='KU_PERSON'
	SET @EventText = 'Физические лица ' +  right(RTRIM(@parFM) + ' ' + RTRIM(@parIM) + ' ' + RTRIM(@parOT), 200)
	EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника', @EventText, @ObjectLink, 'KU_PERSON', @parLINK

IF @@TRANCOUNT > @trancount
	COMMIT TRAN
RETURN 0




GO


GRANT EXECUTE ON dbo.[KU_PERSON_SAVE] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[DP_SPRAV_ISP]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[DP_SPRAV_ISP]

GO
CREATE PROCEDURE dbo.DP_SPRAV_ISP 
  @varKSBeginPeriod  DATETIME, 
  @varKSEndPeriod    DATETIME,
  @varKSDocType      INT,
  @varKSDocVid	     INT = 0,
  @varKSRegNum	     VARCHAR(10) = '',
  @varKSEmpl	     INT = 0,
  @p_iNpa			 SMALLINT = 0
AS 

DECLARE @varKSDocCount INT


SELECT @varKSDocCount = COUNT(*)
FROM DOCUMENTS D INNER JOIN EVENT_REG ER ON D.LINK = ER.LINK_DOC
WHERE D.DOC_TIP = @varKSDocType AND
      ER.REG_DATE BETWEEN CONVERT(DATETIME,@varKSBeginPeriod,120) AND CONVERT(DATETIME,@varKSEndPeriod,120)

CREATE TABLE #Documents (LINK INT,NAME VARCHAR(100),REG_NUM VARCHAR(50), SODER VARCHAR(5000), ISHNISP varchar(50), ISHDISP datetime, DOC_VID varchar(100))
CREATE TABLE #Tasks (DOC_LINK INT,NAME VARCHAR(100),REG_NUM VARCHAR(20),TASK_LINK INT, NLEVEL INT, DOC_STATUS INT) 
CREATE TABLE #Executors (DOC_LINK INT,TASK_LINK INT,NLEVEL INT, EXEC_LINK INT,SROK DATETIME,OTV BIT,OK BIT,DAT DATETIME,ISP VARCHAR(40),OTDEL VARCHAR(90)) 

INSERT INTO #Documents (LINK,NAME,REG_NUM,SODER, ISHNISP,ISHDISP,DOC_VID)
SELECT 
	D.LINK,left(D.NAME,100),ER.REG_NUM, D.[SODER], --D.ISHNISP, D.ISHDISP, DV.NAME
		 ISNULL(D.ISHNISP,NN.ISH_NUM), ISNULL(D.ISHDISP,NN.ISH_DATE), DV.NAME
FROM 
	dbo.DOCUMENTS D 
	INNER JOIN dbo.EVENT_REG ER ON D.LINK = ER.LINK_DOC
	INNER JOIN dbo.WF_DOCVID DV ON D.DOC_VID = DV.LINK
	LEFT JOIN (
				SELECT EG.LINK_DOC,WCI.ISH_NUM, WCI.ISH_DATE
				FROM
					dbo.EVENT_GETDOC EG
					INNER JOIN (SELECT LINK_DOC, MAX(LINK) AS LINK FROM dbo.EVENT_GETDOC GROUP BY LINK_DOC) EG2 
						ON EG2.LINK_DOC = EG.LINK_DOC AND EG2.LINK = EG.LINK
					INNER JOIN dbo.WF_CORR_IN WCI ON WCI.LINK_UP = EG.LINK
					INNER JOIN (SELECT LINK_UP, MAX(LINK) AS LINK FROM dbo.WF_CORR_IN GROUP BY LINK_UP) WCI2 ON WCI2.LINK_UP = WCI.LINK_UP AND WCI2.LINK = WCI.LINK
	   ) NN ON NN.LINK_DOC = D.LINK
WHERE 
	D.DOC_TIP = @varKSDocType
	AND ER.REG_DATE BETWEEN @varKSBeginPeriod AND @varKSEndPeriod
	AND (@varKSDocVid = 0 OR D.DOC_VID = @varKSDocVid)
	AND (@varKSRegNum = '' OR er.reg_num = @varKSRegNum)
	AND (@p_iNpa = 0 OR @p_iNpa = (@p_iNpa|DV.NORM))
--	AND ( (@varKSDocVid  is not null AND @varKSRegNum is not null AND D.DOC_VID = @varKSDocVid AND @varKSRegNum is not null AND er.reg_num = @varKSRegNum) 
--	OR (@varKSDocVid is null AND  @varKSRegNum is not null and ER.REG_NUM = @varKSRegNum) 
--	OR (@varKSDocVid is not null AND  @varKSRegNum is null and D.DOC_VID = @varKSDocVid)
--	OR (@varKSDocVid is  null AND @varKSRegNum is  null))

SELECT @varKSDocCount = COUNT(*) FROM #Documents

-- удаляются из выборки документы c контрольной отметкой не идущее в статистику
DELETE D FROM #Documents D
INNER JOIN EVENT_CONTROL EC ON D.LINK = EC.LINK_DOC
INNER JOIN WF_DOCCONTROL DC ON EC.CONTROL_LINK = DC.LINK AND DC.NO_STAT = 1

CREATE TABLE #WF_EVENT_EXECUTOR(
	LINK		INT,
	LINK_TASK	INT,
	LINK_DOC	INT,
	EXECUTOR	INT,
	SROK_DATE	DATETIME,
	CHECKED		BIT,
	ISP			BIT,
	ISP_DATE	DATETIME,
	EXECUTOR_NAME	VARCHAR(30)
)

INSERT INTO #WF_EVENT_EXECUTOR (LINK, LINK_TASK, LINK_DOC, EXECUTOR, SROK_DATE, CHECKED, ISP, ISP_DATE, EXECUTOR_NAME)
SELECT LINK, LINK_TASK, LINK_DOC, EXECUTOR, SROK_DATE, CHECKED, ISP, ISP_DATE, EXECUTOR_NAME FROM dbo.WF_EVENT_EXECUTOR_FN(@varKSBeginPeriod,@varKSEndPeriod) 

CREATE INDEX #IDX_WF_EVENT_EXECUTOR ON #WF_EVENT_EXECUTOR (LINK_TASK)

INSERT INTO #Tasks (DOC_LINK,NAME,REG_NUM,TASK_LINK, NLEVEL)
SELECT D.LINK,D.NAME,D.REG_NUM,ET.LINK,ET.LINK_EXECUTOR
FROM WF_EVENT_TASK ET INNER JOIN #Documents D ON ET.LINK_DOC = D.LINK AND
     EXISTS(SELECT * FROM #WF_EVENT_EXECUTOR WHERE LINK_TASK = ET.LINK)
ORDER BY 1,3 



CREATE TABLE #EMPL_STAFF(
	EMPL_LINK	INT,
	SUBDIV_LINK	INT
)
CREATE INDEX #IDX_EMPL_STAFF ON #EMPL_STAFF (EMPL_LINK)

INSERT INTO #EMPL_STAFF (EMPL_LINK, SUBDIV_LINK)
SELECT EMPL_LINK, SUBDIV_LINK FROM DBO.EMPL_STAFF(DEFAULT)


INSERT INTO #Executors (DOC_LINK,TASK_LINK,NLEVEL, EXEC_LINK,SROK,OTV,OK,DAT,ISP,OTDEL) 
SELECT EE.LINK_DOC,T.TASK_LINK,T.NLEVEL,EE.LINK,SROK_DATE,CHECKED,ISP,ISP_DATE,EXECUTOR_NAME,
       ISNULL((SELECT left(NAME,90) FROM dbo.SUBDIV S WHERE S.LINK = ES.SUBDIV_LINK),'Нет отдела') 
FROM #WF_EVENT_EXECUTOR EE 
		     INNER JOIN #Tasks T ON EE.LINK_TASK = T.TASK_LINK
					AND (@varKSEmpl = 0 or EE.EXECUTOR = @varKSEmpl)
--					AND (@varKSEmpl is not null and EE.EXECUTOR = @varKSEmpl
--						or @varKSEmpl is null)
             LEFT OUTER JOIN #EMPL_STAFF ES ON EE.EXECUTOR = ES.EMPL_LINK 
ORDER BY 1,2

CREATE TABLE #Rez2 (DOC_LINK INT,DOC_NAME VARCHAR(100),ISP VARCHAR(40),OTDEL VARCHAR(90),DOC_STATUS INT) 

-- просроченные
INSERT INTO #rez2 (DOC_LINK,DOC_NAME,ISP,OTDEL,DOC_STATUS)
SELECT DISTINCT E.DOC_LINK,T.NAME,E.ISP,E.OTDEL,3  
FROM #Executors E,#Tasks T,event_task_ref tr
WHERE T.DOC_LINK = E.DOC_LINK AND tr.link_task = t.task_link and tr.link_executors = e.exec_link and e.ok = 0 and e.OTV = 1 and
--       E.DOC_LINK IN (SELECT DOC_LINK
--                      FROM #Executors
--                      WHERE OK = 0 AND OTV = 1 AND ISP = E.ISP) AND
      DATEDIFF(DAY,E.SROK,GETDATE()) > 0

-- в работе
INSERT INTO #rez2 (DOC_LINK,DOC_NAME,ISP,OTDEL,DOC_STATUS)
SELECT DISTINCT E.DOC_LINK,T.NAME,E.ISP,E.OTDEL,4  
FROM  #Executors E,#Tasks T,event_task_ref tr
WHERE T.DOC_LINK = E.DOC_LINK AND tr.link_task = t.task_link and tr.link_executors = e.exec_link and e.ok = 0 and e.OTV = 1 and
      E.DOC_LINK NOT IN (SELECT DOC_LINK FROM #rez2 WHERE DOC_STATUS = 3 and DOC_LINK = E.DOC_LINK and ISP = E.ISP ) AND
 DATEDIFF(DAY,E.SROK,GETDATE()) <= 0
--	  E.DOC_LINK NOT IN (SELECT R2.DOC_LINK FROM #rez2 R2,  #Executors E2 WHERE R2.DOC_LINK = E2.DOC_LINK AND E2.OK = 0 AND E2.OTV = 1 AND R2.ISP = E.ISP)

-- исполненно с нарушением
INSERT INTO #rez2 (DOC_LINK,DOC_NAME,ISP,OTDEL,DOC_STATUS)
SELECT DISTINCT E.DOC_LINK,T.NAME,E.ISP,E.OTDEL,1  
FROM  #Executors E,#Tasks T,event_task_ref tr
WHERE T.DOC_LINK = E.DOC_LINK AND tr.link_task = t.task_link and tr.link_executors = e.exec_link and e.ok = 1 and e.OTV = 1 and
      E.DOC_LINK NOT IN (SELECT DOC_LINK FROM #rez2 WHERE DOC_STATUS IN (3,4) and DOC_LINK = E.DOC_LINK and ISP = E.ISP ) AND
      E.OTV = 1 AND ISNULL(DATEDIFF(DAY,E.SROK,E.DAT),-1) > 0

-- исполненно в срок
INSERT INTO #rez2 (DOC_LINK,DOC_NAME,ISP,OTDEL,DOC_STATUS)
SELECT DISTINCT E.DOC_LINK,T.NAME,E.ISP,E.OTDEL,2  
FROM  #Executors E,#Tasks T,event_task_ref tr
WHERE T.DOC_LINK = E.DOC_LINK AND tr.link_task = t.task_link and tr.link_executors = e.exec_link and e.ok = 1 and e.OTV = 1 and
      E.DOC_LINK NOT IN (SELECT DOC_LINK FROM #rez2 WHERE DOC_STATUS IN (3,4,1) and DOC_LINK = E.DOC_LINK and ISP = E.ISP ) AND
      E.OTV = 1 AND ISNULL(DATEDIFF(DAY,E.SROK,E.DAT),-1) <= 0
--      E.DOC_LINK NOT IN (SELECT R2.DOC_LINK FROM #rez2 R2,  #Executors E2 WHERE R2.DOC_LINK = E2.DOC_LINK AND E2.OK = 0 AND E2.OTV = 1 AND R2.ISP = E.ISP)
	
UPDATE #Rez2
SET DOC_STATUS = 2
WHERE DOC_LINK IN (SELECT LINK FROM dbo.DOCUMENTS WHERE ISP = 1) AND
      DOC_STATUS IN (3,4)

SELECT DISTINCT R.OTDEL,R.ISP,R.DOC_LINK,T.REG_NUM,R.DOC_NAME,R.DOC_STATUS, D.SODER, D.ISHNISP, ISHDISP = RIGHT('00' + CONVERT(VARCHAR(10),DAY(D.ISHDISP)),2)
																											+ '.' + RIGHT('00' + CONVERT(VARCHAR(10),MONTH(D.ISHDISP)),2)
																											+ '.' + CONVERT(VARCHAR(10),YEAR(D.ISHDISP)), D.DOC_VID
FROM #Rez2 R INNER JOIN #Tasks T ON R.DOC_LINK = T.DOC_LINK
	INNER JOIN #Documents D ON D.LINK = R.DOC_LINK
ORDER BY R.OTDEL,R.ISP,R.DOC_STATUS

SELECT * FROM #Executors
SELECT @varKSDocCount

-----------------------------------------------------------------------------------------------------------------------------------------------------
-- формирование итоговой строки в справке по исполнителям
-----------------------------------------------------------------------------------------------------------------------------------------------------
-- исполнено в срок
UPDATE #Tasks 
SET DOC_STATUS = 2
FROM #Tasks T,#Executors E --,event_task_ref tr	
WHERE T.DOC_LINK = E.DOC_LINK AND -- tr.link_task = t.task_link and tr.link_executors = e.exec_link and e.ok = 1 and e.OTV = 1 and
      T.DOC_LINK NOT IN (SELECT DOC_LINK
                         FROM #Executors
                         WHERE OK = 0 AND OTV = 1) AND
      E.OTV = 1 AND
      ISNULL(DATEDIFF(DAY,SROK,DAT),-1) <= 0

-- исполнено с нарушением
UPDATE #Tasks SET DOC_STATUS = 1
FROM #Tasks T,#Executors E --,event_task_ref tr		
WHERE T.DOC_LINK = E.DOC_LINK AND --tr.link_task = t.task_link and tr.link_executors = e.exec_link and e.ok = 1 and e.OTV = 1 and
      T.DOC_LINK NOT IN (SELECT DOC_LINK
                         FROM #Executors
                         WHERE OK = 0 AND OTV = 1) AND
      E.OTV = 1 AND
      ISNULL(DATEDIFF(DAY,SROK,DAT),-1) > 0

-- в работе
UPDATE #Tasks
SET DOC_STATUS = 4
FROM #Tasks T,#Executors E --,event_task_ref tr	
WHERE T.DOC_LINK = E.DOC_LINK AND --tr.link_task = t.task_link and tr.link_executors = e.exec_link and e.ok = 0 and e.OTV = 1 and
      T.DOC_LINK IN (SELECT DOC_LINK
                     FROM #Executors
                     WHERE OK = 0 AND OTV = 1) AND
      DATEDIFF(DAY,SROK,GETDATE()) <= 0 

-- просрочен
UPDATE #Tasks 
SET DOC_STATUS = 3
FROM #Tasks T,#Executors E --,event_task_ref tr	
WHERE T.DOC_LINK = E.DOC_LINK AND --tr.link_task = t.task_link and tr.link_executors = e.exec_link and e.ok = 0 and e.OTV = 1 and
      T.DOC_LINK IN (SELECT DOC_LINK
                     FROM #Executors
                     WHERE OK = 0 AND OTV = 1) AND
      DATEDIFF(DAY,SROK,GETDATE()) > 0  AND OK = 0 AND OTV = 1

UPDATE #Tasks
SET DOC_STATUS = 2
WHERE DOC_LINK IN (SELECT LINK FROM dbo.DOCUMENTS WHERE ISP = 1) AND DOC_STATUS IN (3,4)

SELECT DISTINCT DOC_LINK,NAME,REG_NUM,DOC_STATUS
FROM #Tasks
ORDER BY DOC_STATUS


--DROP TABLE #Documents
--DROP TABLE #Tasks
--DROP TABLE #Executors
--DROP TABLE #Rez2



GO


GRANT EXECUTE ON dbo.[DP_SPRAV_ISP] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_U_VEDOM_DGH_TABLE1_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_U_VEDOM_DGH_TABLE1_SAVE]

GO

/*
© Кейсистемс (Keysystems), 2005
*/

CREATE  PROCEDURE [dbo].SD_U_VEDOM_DGH_TABLE1_SAVE

	@varKSintLINK			int,
	@varKSintORDERS			int,
	@varKSintPERS_LINK		int,
	@varKSnumSUMMA			numeric(18,2)	=0.0,
	@varKSnumDISBURS			numeric(18,2)  =0.0, 
	@varKSchrNOTE			varchar(254),
	@varLinkEkr				INT = null
AS
DECLARE @varKSSQLError			tinyint,
	  @varKStrancount	int,		
	  @varKSstrVALUE		varchar(7000),
	  @varKStintSTATUS	int,
	  @varKSRowCount		int

SET @varKStrancount = @@TRANCOUNT

SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN


INSERT INTO SDOC_VEDOM_DGH_TABLE1 WITH (ROWLOCK) (LINK_UP,ORDERS,PERS_LINK,SUMMA,DISBURS,NOTE , LINK_EKR)
VALUES (@varKSintLINK,@varKSintORDERS,@varKSintPERS_LINK,@varKSnumSUMMA,@varKSnumDISBURS,@varKSchrNOTE, @varLinkEkr)	
SELECT @varKSSQLError = @@ERROR, @varKSintLINK = @@IDENTITY
IF @varKSSQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END

WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0


GO


GRANT EXECUTE ON dbo.[SD_U_VEDOM_DGH_TABLE1_SAVE] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_SHOW_PAYS_EMPL_TABLE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SHOW_PAYS_EMPL_TABLE]

GO

CREATE PROCEDURE dbo.SA_SHOW_PAYS_EMPL_TABLE @LINK INT
AS

--ДЛЯ КОГО СЧИТАТЬ
DECLARE @BUF_ID VARCHAR(20), @LINK_EMPL INT, @LINK_DEP INT
EXEC DBO.GETRANDSTR 20, @BUF_ID OUT

DECLARE @SQL VARCHAR(1000)

SET @SQL = '
INSERT INTO DBO.BUFFER (ID, LINK)
SELECT DISTINCT ''' + @BUF_ID + ''', T.LINK_EMPL
FROM
	DBO.TABELS T WITH (NOLOCK) 
WHERE
	T.LINK_DOC = ' + CONVERT(VARCHAR(20),@LINK)

EXEC (@SQL)
	
SET @LINK_DEP = (SELECT TOP 1 LINK_DEP FROM DBO.SDOC WITH (NOLOCK) WHERE LINK = @LINK)
	
IF ISNULL((SELECT COUNT(LINK) FROM DBO.BUFFER WITH (NOLOCK) WHERE ID = @BUF_ID),0) = 1
BEGIN	
	SET @LINK_EMPL = (SELECT TOP 1 LINK FROM DBO.BUFFER WITH (NOLOCK) WHERE ID = @BUF_ID)
	SELECT 0 as CHECKED, 0 as DEL, 0 UPD, convert(bit,0) as LOCKED,	* 
	FROM dbo.DICTIONARY_PAYS_EMPL_FN(DEFAULT,@LINK_EMPL,DEFAULT,DEFAULT,@LINK_DEP, 1)
	
END	
ELSE

--select CHECKED=null, DEL=null, UPD=null, LOCKED=null, LINK=null, LINK_EMPL=null, LINK_SOVM=null, LINK_PAYS=null, CODE_PAYS=null, NAME_PAYS=null, DATE_BEGIN=null, DATE_END=null, WAY_CALC=null, BASE=null, VALUE=null, SUMMA=null, ACTUAL=null, ISPERCENT=null, ISPERCENT_NAME=null, OMP_LINK=null, ORDER_LINK=null, ORDER_NUM=null, ORDER_DATE=null, ORDER_TYPE=null, ORDER_NAME=null, ORDER_INFO=null, LINK_KBK=null, CODE_KBK=null, NAME_KBK=null, LINK_ETS=null, LINK_PKG=null, OBJ_CODE=null, NOSUM=null, PROPORC = null
	SELECT 0 as CHECKED, 0 as DEL, 0 UPD, convert(bit,0) as LOCKED,	*
	FROM dbo.DICTIONARY_PAYS_EMPL_FN(DEFAULT,DEFAULT,DEFAULT,@BUF_ID,@LINK_DEP, 1)


SET @SQL = '
	DELETE FROM DBO.BUFFER WHERE ID = ''' + @BUF_ID + ''''
EXEC (@SQL)

RETURN 0




GO


GRANT EXECUTE ON dbo.[SA_SHOW_PAYS_EMPL_TABLE] TO PUBLIC

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RN_PRINT_RSV1]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RN_PRINT_RSV1]

GO

/*
© Кейсистемс (Keysystems), 2014
*/

CREATE PROCEDURE dbo.[RN_PRINT_RSV1]
	@namesTables varchar(8000),        -- имена глобальных временных таблиц через запятую, где хранятся таблицы
									-- нужно самим сделать select, первый select отностится к c_data2
									-- после работы, нужно удалить!
	@LSF int
AS
/*
*/

	create table #all (COL1 varchar(8000), COL2 varchar(8000), COL3 float, COL4 float, COL5 float, COL6 varchar(8000),  CODE varchar(50), DEL bit, ITOG int, orders int IDENTITY(1,1))
	declare @table varchar(100), @RunStr varchar(8000),@table1 varchar(100),@table2 varchar(100),@table3 varchar(100) ,@table4 varchar(100),@table5 varchar(100),@table6 varchar(100), 
	@table7 varchar(100),@table8 varchar(100),@table9 varchar(100) ,@table10 varchar(100),@table11 varchar(100),@table12 varchar(100), 
	@table13 varchar(100),@table14 varchar(100),@table15 varchar(100) ,@table16 varchar(100),@table17 varchar(100),@table18 varchar(100), 
	@table19 varchar(100),@table20 varchar(100),@table21 varchar(100) 

	
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table1 output, ','



	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table2 output, ','


	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table3 output, ','
	--set @RunStr = 'DELETE A 
	--               FROM  ' + @table3 +' A 
	--               WHERE EXISTS(SELECT * FROM '+@table3 +' B WHERE SUBSTRING(A.CODE,18,9) = SUBSTRING(B.CODE,18,9) AND SUBSTRING(B.CODE,1,17) <> ''00000000000000000'')  
	--               AND SUBSTRING(A.CODE,1,17) = ''00000000000000000'''  
 --  PRINT @RunStr
	--execute(@RunStr)

--	set @RunStr = 'SELECT * FROM ' + @table3 
--	execute(@RunStr)

--	set @RunStr = 'drop table ' + @table3
--	execute(@RunStr)

	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table4 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table5 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table6 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table7 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table8 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table9 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table10 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table11 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table12 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table13 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table14 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table15 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table16 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table17 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table18 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table19 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table20 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table21 output, ','

set @RunStr = 'SELECT * FROM ' + @table1 +' ' 
execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table2 +' ' 
execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table3 +' ' 
execute(@RunStr)
set @RunStr = 'SELECT * FROM ' + @table4 +' ' 
execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table5 +' ' 
execute(@RunStr)
set @RunStr = 'SELECT * FROM ' + @table6 +' ' 
execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table7 +' ' 
execute(@RunStr)
set @RunStr = 'SELECT * FROM ' + @table8 +' ' 
execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table9 +' ' 
execute(@RunStr)
set @RunStr = 'SELECT * FROM ' + @table10 +' ' 
execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table11 +' ' 
execute(@RunStr)


set @RunStr = 'SELECT * FROM ' + @table12 +' ' 
execute(@RunStr)
set @RunStr = 'SELECT * FROM ' + @table13 +' ' 
execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table14 +' ' 
execute(@RunStr)
set @RunStr = 'SELECT * FROM ' + @table15 +' ' 
execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table16 +' ' 
execute(@RunStr)
set @RunStr = 'SELECT * FROM ' + @table17 +' ' 
execute(@RunStr)
set @RunStr = 'SELECT * FROM ' + @table18 +' ' 
execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table19 +' ' 
execute(@RunStr)
set @RunStr = 'SELECT UPD,del,link_saved_form,link_row,orders,Calc_orders,Print_Null,
				code,col1,col2,col3,col4,col5,col6,col7,col8,col9,
				col10 = (SELECT TOP 1 CASE WHEN LEN(''''+ col10 + '','' + col11+ '','' +col12+ '','' +col13+ '','' +col14+ '','' +col15+ '','' +col16+ '',''+col17+'','') >10 
													THEN ''''+ col10 + '','' + col11+ '','' +col12+ '','' +col13+ '','' +col14+ '','' +col15+ '','' +col16+ '',''+col17+'',''
													ELSE '' '' END FROM ' + @table20 +'  where COL7 = a.COL7 and COL3=''700'')  ,
				col18 = (SELECT TOP 1 CASE WHEN LEN( ''''+ col18+ '','' +col19+ '','' +col20+ '','' +col21+ '','' +col22+ '','' +col23+ '','' +col24+ '','' +col25+'','' ) >10 
													THEN ''''+ col18+ '','' +col19+ '','' +col20+ '','' +col21+ '','' +col22+ '','' +col23+ '','' +col24+ '','' +col25+'','' 
													ELSE '' '' END FROM ' + @table20 +'  where COL7 = a.COL7 and COL3=''700''),
				col26 = (SELECT TOP 1 CASE WHEN LEN(''''+col26+ '','' +col27+ '','' +col28+ '','' +col29+ '','' +col30+ '','' +col31+ '','' +col32+ '','' +col33+'','') >10 
													THEN ''''+col26+ '','' +col27+ '','' +col28+ '','' +col29+ '','' +col30+ '','' +col31+ '','' +col32+ '','' +col33+'',''					
													ELSE '' '' END  FROM ' + @table20 +'  where COL7 = a.COL7 and COL3=''700''),
				col34 = (SELECT TOP 1 CASE WHEN LEN(''''+col34+ '','' +col35+ '','' +col36+ '','' +col37+ '','' +col38+ '','' +col39+ '','' +col40+ '','' +col41+'','') >10 
													THEN ''''+col34+ '','' +col35+ '','' +col36+ '','' +col37+ '','' +col38+ '','' +col39+ '','' +col40+ '','' +col41+'',''
													ELSE '' '' END FROM ' + @table20 +'  where COL7 = a.COL7 and COL3=''700''),
				col42,col43,col44 FROM ' + @table20 +' a ' 

execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table21 +' ' 
execute(@RunStr)


/*exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
set @RunStr = 'SELECT * FROM ' + @table 
PRINT @RunStr
execute(@RunStr)

set @RunStr = 'drop table ' + @table
execute(@RunStr)
*/

GO


GRANT EXECUTE ON dbo.[RN_PRINT_RSV1] TO PUBLIC

GO




GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_RSV1_EXPORT_TEST]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_RSV1_EXPORT_TEST]

GO
CREATE PROCEDURE dbo.SA_RSV1_EXPORT_TEST (@Res tinyint output, @link int, @m int) 
AS
BEGIN

/* declare @Res tinyint
 set @Res = 0
 exec SA_RSV1_EXPORT_TEST @Res output, 2501, 3
 */
	DECLARE @LINK_DEP INT
	SELECT @LINK_DEP = LINK_ORGANIZATION FROM dbo.REPORT_SAVED_FORMS WHERE LINK_SAVED_FORM = @link

	SELECT 				
		D.PFNUMBER,
		D.TFOMS_REG_NUM,
		D.OKATO AS OKATO,
		D.OKTMO,
		D.INN,
		D.OKVED,
		D.KPP,
		D.OKPO,
		D.OGRN,
		D.OKOPF,
		D.OKFS,
		GB_PHONE = GLBUH.PHONE,
		D.KLADR_LINK,
		D.TFOMS_KT,
		GLBUH_FIO = GLBUH.FM
	INTO #TMP	
	FROM 
		dbo.DEPARTMENTS D
		LEFT JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Главный бухгалтер') GLBUH ON GLBUH.link_dep = d.link
	WHERE 
		D.LINK = @LINK_DEP
	
	
	DECLARE @ATR_PERS_UCH INT
	SET @ATR_PERS_UCH  = (SELECT DBO.RN_GET_ATR_VALUE(@link, 'REPORTS_ATR_PERS_UCH'))
	
	
	DECLARE @PERS_DATE varchar(10) ,  @RSV_DATE varchar(10)
	SET  @RSV_DATE  =  convert(varchar(10),(select modify_date from dbo.REPORT_SAVED_FORMS WHERE LINK_SAVED_FORM = @link),104)
	
	IF @RSV_DATE >= '20140101'
		SET  @PERS_DATE =  convert(varchar(10),(select date  FROM   dbo.SA_SZV4_PACHKA P WHERE p.link_dep = @LINK_DEP and p.link = @ATR_PERS_UCH ))

	-- Проставлять ОКАТО или ОКТМО по настройке
	DECLARE @OKATO_OR_OKTMO int
	SET @OKATO_OR_OKTMO = dbo.SA_GET_OPTION_BY_CODE('NASTR_USE_OKATO_OKTMO') 
	
	
	SET @Res = 1		
	CREATE TABLE #ERR_MSG (MSG_BEFORE VARCHAR(254),Msg VARCHAR(254),msg_after VARCHAR(254))

	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(PFNUMBER,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Регистрационный номер в ПФР.',
			msg_after  = 'Необходимо указать Регистрационный номер в ПФР в настройках организации на вкладке РЕКВИЗИТЫ.'
	END

	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(INN,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ИНН',
			msg_after  = 'Необходимо указать ИНН в настройках организации на вкладке РЕКВИЗИТЫ.'
	END		
	
	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(KPP,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'КПП',
			msg_after  = 'Необходимо указать КПП в настройках организации на вкладке РЕКВИЗИТЫ.'
	END	

	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(OKPO,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОКПО',
			msg_after  = 'Необходимо указать ОКПО в настройках организации на вкладке РЕКВИЗИТЫ.'
	END	

	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(OKPO,'')))) > 10) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Неверно указаны следующие реквизиты:',
			Msg = 'ОКПО не должен быть больше 10 знаков',
			msg_after  = 'Необходимо исправить ОКПО в настройках организации на вкладке РЕКВИЗИТЫ.'
	END		
	
	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(OGRN,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОГРН',
			msg_after  = 'Необходимо указать ОГРН в настройках организации на вкладке РЕКВИЗИТЫ.'
	END	
	
	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(GLBUH_FIO,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Ф.И.О. главного бухгалтера',
			msg_after  = 'Необходимо указать "Ф.И.О. главного бухгалтера" в настройках организации на вкладке ОТВЕТСТВЕННЫЕ ЛИЦА.'
	END

	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(GB_PHONE,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Телефон главного бухгалтера',
			msg_after  = 'Необходимо указать "Телефон главного бухгалтера" в настройках организации на вкладке ОТВЕТСТВЕННЫЕ ЛИЦА.'
	END
	
	
	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(OKATO,'')))) = 0) AND @OKATO_OR_OKTMO = 1 BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОКАТО',
			msg_after  = 'Необходимо указать ОКАТО в настройках организации на вкладке АДРЕС.'
	END


	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(OKTMO,'')))) = 0) AND @OKATO_OR_OKTMO = 2 BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОКТМО',
			msg_after  = 'Необходимо указать ОКТМО в настройках организации на вкладке АДРЕС.'
	END

	IF EXISTS (SELECT * FROM #TMP WHERE KLADR_LINK IS NULL) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Адрес организации',
			msg_after  = 'Необходимо указать "Адрес организации" в настройках организации на вкладке АДРЕС.'
	END				
	
	/*IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(TFOMS_REG_NUM,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Регистрационный номер в ТФОМС.',
			msg_after  = 'Необходимо указать Регистрационный номер в ТФОМС в настройках организации на вкладке ПРОЧИЕ.'
	END	*/

	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(OKVED,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОКВЭД',
			msg_after  = 'Необходимо указать ОКВЭД в настройках организации на вкладке ПРОЧИЕ.'
	END	


	
	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(OKOPF,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОКОПФ',
			msg_after  = 'Необходимо указать ОКОПФ в настройках организации на вкладке ПРОЧИЕ.'
	END			

	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(OKFS,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОКФС',
			msg_after  = 'Необходимо указать ОКФС в настройках организации на вкладке ПРОЧИЕ.'
	END

	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(TFOMS_KT,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Код тарифа',
			msg_after  = 'Необходимо указать "Код тарифа" в настройках организации на вкладке ПРОЧИЕ.'
	END	
	
	IF EXISTS (SELECT * FROM #TMP WHERE LTRIM(RTRIM(ISNULL(TFOMS_KT,''))) NOT IN ('01','02','03','04','05','09'))  BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Неверно указаны следующие реквизиты:',
			Msg = 'Код тарифа может принимать одно из возможных значений: 01, 02, 03, 04, 05, 09',
			msg_after  = 'Необходимо исправить "Код тарифа" в настройках организации на вкладке ПРОЧИЕ.'
	END		


	IF @RSV_DATE >= '20140101'
	BEGIN
		IF @PERS_DATE < @RSV_DATE BEGIN
			SET @Res = 0
			INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
			SELECT
				MSG_BEFORE = 'Неверно указаны следующие реквизиты:',
				Msg = 'Дата составления расчета по Персонифицированному учету не должна быть меньше даты Заполения РВС-1',
				msg_after  = 'Необходимо исправить Дату составления в расчете по персонифицированному учету в режиме Персонифицированный учет.'
		END	
	END
	
	SELECT * FROM #ERR_MSG	
	
END






GO


GRANT EXECUTE ON dbo.[SA_RSV1_EXPORT_TEST] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_RSV1_EXPORT_0700_2014]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_RSV1_EXPORT_0700_2014]

GO
---- exec [dbo].SA_RSV1_EXPORT_0700_2014 2525

CREATE   PROCEDURE [dbo].SA_RSV1_EXPORT_0700_2014 ( @Link int /*Ссылка на расчет*/ ) 
AS

CREATE TABLE #OUTPUT (ID int identity(1,1), F_NAME VARCHAR(254), OUT_TEXT TEXT)

SET NOCOUNT ON

--Строка заголовка
CREATE TABLE #TASK_PROP (ID int identity(1,1), VAL VARCHAR (254))

INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MAJOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MINOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_FIX',1

declare @NAME_PROG varchar(254), @VERS_PROG VARCHAR(254), @WORK_END varchar(1)
Select @NAME_PROG = UPPER(RTRIM(LTRIM([NAME]))), 
	@VERS_PROG = (SELECT RTRIM(LTRIM(VAL)) FROM #TASK_PROP WHERE [ID] = 1)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 2)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 3)
from dbo.DICTIONARY_TASK where CODE = 'SALARY'
--------------------------------------------
-- Проставлять ОКАТО или ОКТМО по настройке
DECLARE @OKATO_OR_OKTMO int
SET @OKATO_OR_OKTMO = dbo.SA_GET_OPTION_BY_CODE('NASTR_USE_OKATO_OKTMO') 

DECLARE @ATR_TYPE_KOR INT
SET @ATR_TYPE_KOR  = (SELECT DBO.RN_GET_ATR_VALUE(@Link, 'REPORTS_ATR_TYPE_KOR'))	

	
DECLARE @LINK_DEP INT, @YEAR INT, @Version TINYINT, @Period_Number TINYINT, @LINK_FORM INT, @Begin_Date DATETIME, @End_Date DATETIME, @modify_date DATETIME
SELECT 
	@LINK_DEP = LINK_ORGANIZATION, 
	@YEAR = YEAR(Begin_Date),
	@Version = [Version],
	@Period_Number = Period_Number,
	@LINK_FORM = LINK_FORM,
	@Begin_Date = dbo.DateBeginOfYear(Begin_Date),
	@End_Date = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,Period_Number*3,YEAR(Begin_Date))),
	@modify_date = modify_date
FROM dbo.REPORT_SAVED_FORMS WHERE LINK_SAVED_FORM = @link

SELECT top 1
	DD1.OKPO AS OKPO1, 
	RIGHT(REPLICATE('0',12) + LTRIM(RTRIM(DD1.INN)), 12) AS INN1, 
	DD1.KPP AS KPP1, 
	FULL_NAME = CONVERT(VARCHAR(160),UPPER(DD1.FULL_NAME)),
	UPPER(DD1.NAME) AS ORGNAME,
	DD2.NALOG AS IMNS_SONO, DD2.NAME AS IMNS_NAME, 
	DD2.NALOG AS SONO, 
	RIGHT(REPLICATE('0',15) + LTRIM(RTRIM(DD1.OGRN)), 15) AS OGRN1,
	LTRIM(RTRIM(dbo.GetAddressBykladr(DD1.REF_LINK_A))) 
		+ CASE WHEN ISNULL(DD1.HOUSE, '') = '' THEN '' ELSE ' ' + LTRIM(RTRIM(DD1.HOUSE)) END
		+ CASE WHEN ISNULL(DD1.FLAT, '') = '' THEN '' ELSE ' - ' + LTRIM(RTRIM(DD1.FLAT)) END
	AS ADDR_STR,
	CAST(NULL AS DATETIME) AS DATE_END,
	UPPER(RTRIM(CHIEF.FM) + ' ' + LEFT(CHIEF.IM, 1) + '. ' + LEFT(CHIEF.OT,1) + '.') AS CHIEF_FIO,
	RTRIM(CHIEF.PHONE) AS CH_PHONE,
	UPPER(RTRIM(GLBUH.FM) + ' ' + LEFT(GLBUH.IM, 1) + '. ' + LEFT(GLBUH.OT,1) + '.') AS GLBUH_FIO,
	RTRIM(GLBUH.PHONE) AS GL_PHONE,
	OGRN = RIGHT(REPLICATE('0',15) + LTRIM(RTRIM(DD1.OGRN)), 15),
	DD1.OKATO,
	DD1.OKTMO,
	OKVED = (CASE WHEN LEN(ltrim(rtrim(DD1.OKVED)))<8 AND RIGHT(DD1.OKVED,1) = '.' THEN STUFF(DD1.OKVED,LEN(ltrim(rtrim(DD1.OKVED))),1,'') ELSE DD1.OKVED end) ,
 	DD1.OKPO,
	DD1.FSS_REG_NUM, --Регистрационный номер (код) страхователя ТФОМС
	DD1.FSS_KOD_P, --Код подчиненности - код, состоящий из пяти цифр, указывающий на территориальный орган Фонда, в котором страхователь зарегистрирован в текущий момент;	
	DD1.FSS_KOD_DOP, --Дополнительный код предусмотрен для обособленных подразделений организаций
	DD1.OKOPF, --- код Общероссийского классификатора организационно-правовых форм;
	DD1.OKFS, --- код Общероссийского классификатора форм собственности;
	DD1.PFNUMBER,
	DA.PINDEX, REGION = UPPER(DA.REGION), DA.REGCODE, RAION = UPPER(DA.RAION), GOROD = UPPER(DA.GOROD), 
	NASEL = UPPER(DA.NASEL), STREET = UPPER(DA.STREET), DA.HOUSE, DA.KORP, DA.FLAT,
	TFOMS_RNUM = DD1.TFOMS_REG_NUM,
	TFOMS_KT = DD1.TFOMS_KT,
	TFOMS_KTI = '03',
	WORK_END = '1'
INTO #DEP_DATA	
FROM DICTIONARY_DEPARTMENT DD1 
	LEFT OUTER JOIN DICTIONARY_DEPARTMENT DD2 ON DD1.IMNS_LINK = DD2.LINK
	LEFT OUTER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Руководитель') chief on chief.link_dep = dd1.link
	LEFT OUTER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Главный бухгалтер') GLBUH ON GLBUH.link_dep = dd1.link
	LEFT JOIN DBO.DEP_ADRESS(@LINK_DEP) DA ON 1=1
WHERE DD1.LINK = @LINK_DEP

DECLARE @Cur0 CURSOR, @CurD0 CURSOR, @Cur00 CURSOR,@Cur000 CURSOR, @TAB_NUM TINYINT, @TAB_NAME VARCHAR(254), @TABD_NUM TINYINT, @TABD_NAME VARCHAR(254), @TAB1_NAME VARCHAR(254), @TAB1_NUM TINYINT, @Cur CURSOR, @Cur1 CURSOR , @Cur2 CURSOR , @NUM INT, @BLOK_NAME VARCHAR(254), @RAZDEL_NUM TINYINT, @RAZDEL_NAME VARCHAR(254),
		@CurI0 CURSOR,@CurI00 CURSOR,@CurI000 CURSOR,@CurI CURSOR, @CurI1 CURSOR, @CurI2 CURSOR

DECLARE @lcFNAME varchar(254)
SELECT @lcFNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),@YEAR) + '-ORG-' + RTRIM(LTRIM(COALESCE(PFNUMBER,''))) + '-DCK-00001-DPT-000000-DCK-00000.XML' FROM #DEP_DATA

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
 SELECT @lcFNAME, 'OEM' --Имя файла
 UNION ALL SELECT @lcFNAME, SPACE(0) + '<?xml version="1.0" encoding="Windows-1251" ?>'
 UNION ALL SELECT @lcFNAME, SPACE(0) + '<ФайлПФР>'
	UNION ALL SELECT @lcFNAME, SPACE(1) + '<ИмяФайла>' + RTRIM(LTRIM(@lcFNAME)) + '</ИмяФайла>'
	UNION ALL SELECT @lcFNAME, SPACE(1) + '<ЗаголовокФайла>'
	 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ВерсияФормата>07.00</ВерсияФормата>'
	 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ТипФайла>ВНЕШНИЙ</ТипФайла>'
	 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ПрограммаПодготовкиДанных>'
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<НазваниеПрограммы>' + @NAME_PROG + '</НазваниеПрограммы>'
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<Версия>' + @VERS_PROG + '</Версия>'
	 UNION ALL SELECT @lcFNAME, SPACE(2) + '</ПрограммаПодготовкиДанных>'
	 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ИсточникДанных>СТРАХОВАТЕЛЬ</ИсточникДанных> '
	UNION ALL SELECT @lcFNAME, SPACE(1) + '</ЗаголовокФайла>'
	UNION ALL SELECT @lcFNAME, SPACE(1) + '<ПачкаВходящихДокументов Окружение="Единичный запрос">'
	 UNION ALL SELECT @lcFNAME, SPACE(2) + '<РАСЧЕТ_ПО_СТРАХОВЫМ_ВЗНОСАМ_НА_ОПС_И_ОМС_ПЛАТЕЛЬЩИКАМИ_ПРОИЗВОДЯЩИМИ_ВЫПЛАТЫ_ФЛ_2014>'
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<НомерВпачке>1</НомерВпачке>'
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<РегистрационныйНомерПФР>' + LTRIM(RTRIM(ISNULL(PFNUMBER,''))) + '</РегистрационныйНомерПФР>' + CHAR(10) +
								 SPACE(3) + '<НомерКорректировки>' + CASE @Version WHEN 0 THEN '000' ELSE (REPLICATE('0',2) + ltrim(rtrim(CONVERT(varchar(3),@Version)))) END + '</НомерКорректировки>' + CHAR(10) +
								 SPACE(3) + '<КодОтчетногоПериода>' + CASE @Period_Number WHEN 1 THEN '3' WHEN 2 THEN '6' WHEN 3 THEN '9' ELSE '0' END +'</КодОтчетногоПериода>' + CHAR(10) +
								 SPACE(3) + '<КалендарныйГод>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),@YEAR),''))) + '</КалендарныйГод> ' + CHAR(10) +
							   CASE WHEN LTRIM(RTRIM(ISNULL(@WORK_END,''))) = 'Л' THEN
										SPACE(3) + '<ПрекращениеДеятельности>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(1),WORK_END),''))) + '</ПрекращениеДеятельности> ' + CHAR(10)
								 ELSE '' END
		FROM #DEP_DATA	
		UNION ALL SELECT @lcFNAME, (	CASE  WHEN isnull(@ATR_TYPE_KOR,0) = 0 THEN ''
								ELSE  
								SPACE(3) + '<ТипКорректировки>' + CONVERT(varchar(1),@ATR_TYPE_KOR) + '</ТипКорректировки>' + CHAR(10) 
								END)

	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<НаименованиеОрганизации>' + LTRIM(RTRIM(ISNULL(FULL_NAME,''))) + '</НаименованиеОрганизации>' FROM #DEP_DATA
	  --UNION ALL SELECT @lcFNAME, SPACE(3) + '<РегистрационныйНомерТФОМС>' + LTRIM(RTRIM(ISNULL(TFOMS_RNUM,''))) + '</РегистрационныйНомерТФОМС>' FROM #DEP_DATA
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<ИННсимвольный>' + LTRIM(RTRIM(ISNULL(INN1,''))) + '</ИННсимвольный>' FROM #DEP_DATA
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<КПП>' + LTRIM(RTRIM(ISNULL(KPP1,''))) + '</КПП>' FROM #DEP_DATA
	  --UNION ALL SELECT @lcFNAME, SPACE(3) + '<ОГРН>' + LTRIM(RTRIM(ISNULL(OGRN1,''))) + '</ОГРН>' FROM #DEP_DATA 
	  --UNION ALL SELECT @lcFNAME, SPACE(3) + case when @OKATO_OR_OKTMO = 1 
				--							 then ('<КодПоОКАТО>' + REPLACE(LTRIM(RTRIM(ISNULL(OKATO,''))),SPACE(1),'') + '</КодПоОКАТО>' )
				--							 ELSE ('<КодПоОКТМО>' + REPLACE(LTRIM(RTRIM(ISNULL(OKTMO,''))),SPACE(1),'') + '</КодПоОКТМО>' ) END 
				--							 FROM #DEP_DATA
	  											
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<КодПоОКВЭД>' + LTRIM(RTRIM(ISNULL(OKVED,''))) + '</КодПоОКВЭД>' FROM #DEP_DATA 
	  --UNION ALL SELECT @lcFNAME, SPACE(3) + '<КодПоОКПО>' + LTRIM(RTRIM(ISNULL(OKPO,''))) + '</КодПоОКПО>' FROM #DEP_DATA 
	  --UNION ALL SELECT @lcFNAME, SPACE(3) + '<КодПоОКОПФ>' + LTRIM(RTRIM(ISNULL(OKOPF,''))) + '</КодПоОКОПФ>' FROM #DEP_DATA 
	  --UNION ALL SELECT @lcFNAME, SPACE(3) + '<КодПоОКФС>' + LTRIM(RTRIM(ISNULL(OKFS,''))) + '</КодПоОКФС>' FROM #DEP_DATA 
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<Телефон>' + LTRIM(RTRIM(ISNULL(GL_PHONE,''))) + '</Телефон>' FROM #DEP_DATA 
		
	 -- UNION ALL SELECT @lcFNAME, SPACE(3) + '<АдресРегистрации>'
		 -- UNION ALL SELECT @lcFNAME, SPACE(4) + '<ТипАдреса>РОССИЙСКИЙ</ТипАдреса>' 
		 -- UNION ALL SELECT @lcFNAME, SPACE(4) + '<Индекс>'+ LTRIM(RTRIM(ISNULL(PINDEX,''))) + '</Индекс>' FROM #DEP_DATA  
		 -- UNION ALL SELECT @lcFNAME, SPACE(4) + '<РоссийскийАдрес>' + CHAR(10) +

			--								CASE WHEN LTRIM(RTRIM(ISNULL(REGION,''))) <> '' THEN
			--								 SPACE(5) + '<Регион>' + CHAR(10) + 
			--									SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(REGION,len(REGION)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(REGION),1,' '))) ) )) + '</ГеографическоеНазвание>' + CHAR(10) + 
			--									SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(REGION),1,' ')) )) + '</Сокращение>' + CHAR(10) +
			--								SPACE(5) + '</Регион>' + CHAR(10) 
			--								ELSE '' END +
											
			--								CASE WHEN LTRIM(RTRIM(ISNULL(RAION,''))) <> '' THEN
			--								 SPACE(5) + '<Район>' + CHAR(10) + 
			--									SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(RAION,len(RAION)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(RAION),1,' '))) ) )) + '</ГеографическоеНазвание>' + CHAR(10) + 
			--									SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(RAION),1,' ')) )) + '</Сокращение>' + CHAR(10) +
			--								SPACE(5) + '</Район>' + CHAR(10) 
			--								ELSE '' END +

			--								CASE WHEN LTRIM(RTRIM(ISNULL(GOROD,''))) <> '' THEN
			--								 SPACE(5) + '<Город>' + CHAR(10) + 
			--									SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(GOROD,len(GOROD)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(GOROD),1,' '))) ) )) + '</ГеографическоеНазвание>' + CHAR(10) + 
			--									SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(GOROD),1,' ')) )) + '</Сокращение>' + CHAR(10) +
			--								SPACE(5) + '</Город>' + CHAR(10) 
			--								ELSE '' END +

			--								CASE WHEN LTRIM(RTRIM(ISNULL(NASEL,''))) <> '' THEN
			--								 SPACE(5) + '<НаселенныйПункт>' + CHAR(10) + 
			--									SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(NASEL,len(NASEL)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(NASEL),1,' '))) ) )) + '</ГеографическоеНазвание>' + CHAR(10) + 
			--									SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(NASEL),1,' ')) )) + '</Сокращение>' + CHAR(10) +
			--								SPACE(5) + '</НаселенныйПункт>' + CHAR(10) 
			--								ELSE '' END +	

			--								CASE WHEN LTRIM(RTRIM(ISNULL(STREET,''))) <> '' THEN
			--								SPACE(5) + '<Улица>' + CHAR(10)
			--									+ SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(STREET,len(STREET)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(STREET),1,' '))) ) ))+'</ГеографическоеНазвание>' + CHAR(10) 
			--									+ SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(STREET),1,' ')) ))+'</Сокращение>' + CHAR(10) 
			--									+ SPACE(5) + '</Улица>' + CHAR(10)
			--								ELSE '' END	+			

			--								CASE WHEN LTRIM(RTRIM(ISNULL(HOUSE,''))) <> '' THEN
			--								 SPACE(5) + '<Дом>' + CHAR(10) + 
			--									SPACE(6) + '<Сокращение>ДОМ</Сокращение>' + CHAR(10) +
			--									SPACE(6) + '<Номер>'+ UPPER(LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),HOUSE),'')))) + '</Номер>' + CHAR(10) + 
			--								SPACE(5) + '</Дом>' + CHAR(10) 
			--								ELSE '' END +												

			--								CASE WHEN LTRIM(RTRIM(ISNULL(KORP,''))) <> '' THEN
			--								 SPACE(5) + '<Корпус>' + CHAR(10) + 
			--									SPACE(6) + '<Сокращение>КОРП.</Сокращение>' + CHAR(10) +
			--									SPACE(6) + '<Номер>'+ UPPER(LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),KORP),'')))) + '</Номер>' + CHAR(10) + 
			--								SPACE(5) + '</Корпус>' + CHAR(10) 
			--								ELSE '' END +																

			--								CASE WHEN LTRIM(RTRIM(ISNULL(FLAT,''))) <> '' THEN
			--								 SPACE(5) + '<Квартира>' + CHAR(10) + 
			--									SPACE(6) + '<Сокращение>КВ.</Сокращение>' + CHAR(10) +
			--									SPACE(6) + '<Номер>'+ UPPER(LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),FLAT),'')))) + '</Номер>' + CHAR(10) + 
			--								SPACE(5) + '</Квартира>' + CHAR(10) 
			--								ELSE '' END +				
											
			--						SPACE(4) + '</РоссийскийАдрес>' + CHAR(10) +
			--					SPACE(3) + '</АдресРегистрации>'
			--FROM #DEP_DATA  

------ стр.1_2
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
select @lcFNAME, 
		CASE WHEN T.COL = 3 THEN
			SPACE(3) + '<КоличествоЗЛ>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ>'
		ELSE
			SPACE(3) + '<СреднесписочнаяЧисленность>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СреднесписочнаяЧисленность>'		
		END	
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 1, 1, DEFAULT) T WHERE T.COL IN (3,4) ORDER BY T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)	
		 --SELECT @lcFNAME, SPACE(3) + '<КодУстановленногоТарифа>' + LTRIM(RTRIM(ISNULL(TFOMS_KT,''))) + '</КодУстановленногоТарифа>' FROM #DEP_DATA
/*UNION ALL*/ SELECT @lcFNAME, SPACE(3) + '<КоличествоСтраниц>14</КоличествоСтраниц>'
UNION ALL SELECT @lcFNAME, SPACE(3) + '<КоличествоЛистовПриложения>0</КоличествоЛистовПриложения>'

----- стр.2
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<Раздел1РасчетПоНачисленнымУплаченным2014>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ОстатокЗадолженностиНаНачалоРасчетногоПериода2014>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, CASE T.COL 
	WHEN 3 THEN SPACE(5) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
				SPACE(5) + '<СтраховыеВзносыОПС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОПС>' 
	WHEN 4 THEN	SPACE(5) + '<ОПСстраховаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧасть>'
	WHEN 5 THEN SPACE(5) + '<ОПСнакопительнаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСнакопительнаяЧасть>'
	WHEN 6 THEN SPACE(6) + '<ВзносыПоДопТарифу1>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу1>'	
	WHEN 7 THEN SPACE(6) + '<ВзносыПоДопТарифу2_18>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу2_18>'
	WHEN 8 THEN SPACE(5) + '<СтраховыеВзносыОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОМС>'		
	--WHEN 6 THEN SPACE(5) + '<СтраховыеВзносыТФОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СтраховыеВзносыТФОМС>'
	END						
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 1, DEFAULT) T WHERE T.COL IN (3,4,5,6,7,8) ORDER BY T.COL

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</ОстатокЗадолженностиНаНачалоРасчетногоПериода2014>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<НачисленоСначалаРасчетногоПериода2014>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME,
	CASE T.COL 
	WHEN 3 THEN 
		 CASE T.ROW WHEN 2 THEN SPACE(5) + '<ВсегоСначалаРасчетногоПериода2014>' WHEN 6 THEN SPACE(5) + '<ПоследниеТриМесяцаИтого2014>' ELSE SPACE(5) + '<ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.ROW - 2))) + 'с2014>' END + CHAR(10) +
				SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
				SPACE(6) + '<СтраховыеВзносыОПС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОПС>' 
	--WHEN 4 THEN SPACE(6) + '<ОПСнакопительнаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСнакопительнаяЧасть>' 
	WHEN 6 THEN SPACE(6) + '<ВзносыПоДопТарифу1>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу1>'	
	WHEN 7 THEN SPACE(6) + '<ВзносыПоДопТарифу2_18>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу2_18>'		
	WHEN 8 THEN SPACE(6) + '<СтраховыеВзносыОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОМС>'	+ CHAR(10) +		
	--WHEN 6 THEN SPACE(6) + '<СтраховыеВзносыТФОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СтраховыеВзносыТФОМС>' + CHAR(10) +	
		 CASE T.ROW WHEN 2 THEN SPACE(5) + '</ВсегоСначалаРасчетногоПериода2014>' WHEN 6 THEN SPACE(5) + '</ПоследниеТриМесяцаИтого2014>' ELSE SPACE(5) + '</ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.ROW - 2))) + 'с2014>' END	
	END						
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 0, DEFAULT) T WHERE ROW IN (2,3,4,5,6) AND T.COL IN (3,6,7,8) ORDER BY T.ROW, T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</НачисленоСначалаРасчетногоПериода2014>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ДоначисленоСначалаРасчетногоПериода2014всего>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, CASE T.COL 
	WHEN 3 THEN --SPACE(5) + '<ВсегоСначалаРасчетногоПериода2013>' + CHAR(10) +
					SPACE(5) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
					SPACE(5) + '<СтраховыеВзносыОПС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОПС>'
	WHEN 4 THEN		SPACE(5) + '<ОПСстраховаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧасть>'
	WHEN 5 THEN		SPACE(5) + '<ОПСнакопительнаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСнакопительнаяЧасть>'
	WHEN 6 THEN		SPACE(5) + '<ВзносыПоДопТарифу1>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу1>'	
	WHEN 7 THEN		SPACE(5) + '<ВзносыПоДопТарифу2_18>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу2_18>'		
	WHEN 8 THEN		SPACE(5) + '<СтраховыеВзносыОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОМС>'	
				--SPACE(5) + '</ВсегоСначалаРасчетногоПериода2013>'
	--WHEN 6 THEN sPACE(5) + '<СтраховыеВзносыТФОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СтраховыеВзносыТФОМС>'
	END						
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 7, DEFAULT) T WHERE T.COL IN (3,4,5,6,7,8) ORDER BY T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</ДоначисленоСначалаРасчетногоПериода2014всего>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ДоначисленоСначалаРасчетногоПериода2014превышающие>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, CASE T.COL 
	WHEN 3 THEN	--SPACE(5) + '<СсуммПревышающихПредельнуюВеличинуБазы>' + CHAR(10) +	
					SPACE(5) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
					SPACE(5) + '<СтраховыеВзносыОПС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОПС>' 
	WHEN 4 THEN		SPACE(5) + '<ОПСстраховаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧасть>'
	--WHEN 5 THEN		SPACE(5) + '<ОПСнакопительнаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСнакопительнаяЧасть>'
	--WHEN 6 THEN		SPACE(5) + '<ВзносыПоДопТарифу1>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу1>'	
	--WHEN 7 THEN		SPACE(5) + '<ВзносыПоДопТарифу2_18>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу2_18>'	
	--WHEN 8 THEN		SPACE(5) + '<СтраховыеВзносыОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОМС>'	 
				--SPACE(5) + '</СсуммПревышающихПредельнуюВеличинуБазы>'	
	--WHEN 6 THEN sPACE(5) + '<СтраховыеВзносыТФОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СтраховыеВзносыТФОМС>'
	END						
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 8, DEFAULT) T WHERE T.COL IN (3,4) ORDER BY T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</ДоначисленоСначалаРасчетногоПериода2014превышающие>'


INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ВсегоКуплате2014>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, CASE T.COL 
	WHEN 3 THEN --SPACE(5) + '<ВсегоСначалаРасчетногоПериода2013>' + CHAR(10) +
					SPACE(5) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
					SPACE(5) + '<СтраховыеВзносыОПС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОПС>'
	WHEN 4 THEN		SPACE(5) + '<ОПСстраховаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧасть>'
	WHEN 5 THEN		SPACE(5) + '<ОПСнакопительнаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСнакопительнаяЧасть>'
	WHEN 6 THEN		SPACE(5) + '<ВзносыПоДопТарифу1>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу1>'	
	WHEN 7 THEN		SPACE(5) + '<ВзносыПоДопТарифу2_18>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу2_18>'		
	WHEN 8 THEN		SPACE(5) + '<СтраховыеВзносыОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОМС>'	
	END						
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 10, DEFAULT) T WHERE T.COL IN (3,4,5,6,7,8) ORDER BY T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</ВсегоКуплате2014>'


INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<УплаченоСначалаРасчетногоПериода2014>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME,
	CASE T.COL 
	WHEN 3 THEN 
	CASE T.ROW WHEN 11 THEN SPACE(5) + '<ВсегоСначалаРасчетногоПериода2014>' WHEN 15 THEN SPACE(5) + '<ПоследниеТриМесяцаИтого2014>' ELSE SPACE(5) + '<ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.ROW - 11))) + 'с2014>' END + CHAR(10) +
				SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
				SPACE(6) + '<СтраховыеВзносыОПС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОПС>' 
	
	WHEN 4 THEN SPACE(6) + '<ОПСстраховаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧасть>' 
	WHEN 5 THEN SPACE(6) + '<ОПСнакопительнаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСнакопительнаяЧасть>' 
	WHEN 6 THEN SPACE(6) + '<ВзносыПоДопТарифу1>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу1>'	
	WHEN 7 THEN SPACE(6) + '<ВзносыПоДопТарифу2_18>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу2_18>'		
	WHEN 8 THEN SPACE(6) + '<СтраховыеВзносыОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОМС>'	+ CHAR(10) +		
	--WHEN 6 THEN SPACE(6) + '<СтраховыеВзносыТФОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СтраховыеВзносыТФОМС>' + CHAR(10) +	
	CASE T.ROW WHEN 11 THEN SPACE(5) + '</ВсегоСначалаРасчетногоПериода2014>' WHEN 15 THEN SPACE(5) + '</ПоследниеТриМесяцаИтого2014>' ELSE SPACE(5) + '</ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.ROW - 11))) + 'с2014>' END	
	END						
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 0, DEFAULT) T WHERE ROW IN (11,12,13,14,15) AND T.COL IN (3,4,5,6,7,8) ORDER BY T.ROW, T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</УплаченоСначалаРасчетногоПериода2014>'

--INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ВтомЧислеЗаПредыдущиеРасчетныеПериоды2013>'
--INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
--SELECT @lcFNAME, CASE T.COL 
--	WHEN 3 THEN SPACE(5) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
--		 SPACE(5) + '<ОПСстраховаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧасть>'
--	WHEN 4 THEN SPACE(5) + '<ОПСнакопительнаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСнакопительнаяЧасть>'
--	WHEN 5 THEN	SPACE(6) + '<ОПСстраховаяЧастьПоДопТар1>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧастьПоДопТар1>'		
--	WHEN 6 THEN	SPACE(6) + '<ОПСстраховаяЧастьПоДопТар2>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧастьПоДопТар2>'
--	WHEN 7 THEN SPACE(5) + '<СтраховыеВзносыОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОМС>'		
--	--WHEN 6 THEN SPACE(5) + '<СтраховыеВзносыТФОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СтраховыеВзносыТФОМС>'
--	END						
--FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 16, DEFAULT) T WHERE T.COL IN (3,4,5,6,7) ORDER BY T.COL
--INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</ВтомЧислеЗаПредыдущиеРасчетныеПериоды2013>'


INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ОстатокЗадолженностиНаКонецРасчетногоПериода2014>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, CASE T.COL 
	WHEN 3 THEN	SPACE(5) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
				SPACE(5) + '<СтраховыеВзносыОПС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОПС>'
	WHEN 4 THEN	SPACE(5) + '<ОПСстраховаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧасть>'
	WHEN 5 THEN	SPACE(5) + '<ОПСнакопительнаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСнакопительнаяЧасть>'
	WHEN 6 THEN	SPACE(5) + '<ВзносыПоДопТарифу1>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу1>'	
	WHEN 7 THEN	SPACE(5) + '<ВзносыПоДопТарифу2_18>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу2_18>'		
	WHEN 8 THEN	SPACE(5) + '<СтраховыеВзносыОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОМС>'	
	END							
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 16, DEFAULT) T WHERE T.COL IN (3,4,5,6,7,8) ORDER BY T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</ОстатокЗадолженностиНаКонецРасчетногоПериода2014>'


INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '</Раздел1РасчетПоНачисленнымУплаченным2014>'	


-----Разделы 2
CREATE TABLE #TABLES (NUM TINYINT, TAB_NAME VARCHAR(254))
INSERT INTO #TABLES 
		SELECT 3,'Раздел2РасчетПоТарифуИдопТарифу'
		
CREATE TABLE #TABLES_1 (NUM1 TINYINT, TAB_NUM TINYINT, TAB1_NAME varchar(254))
INSERT INTO #TABLES_1 
		SELECT 4,3, 'Раздел_2_1'

CREATE TABLE #STR_2_1R (NUM TINYINT, TAB_NUM TINYINT, RAZDEL_NAME VARCHAR(254))
INSERT INTO #STR_2_1R 
		SELECT 1,4,'НаОбязательноеПенсионноеСтрахование2014'
UNION	SELECT 2,4,'НаОбязательноеМедицинскоеСтрахование'

--UNION	SELECT 2,4,'НачисленоСтраховыхВзносовВпользуРаботниковИнвалидов'
--UNION	SELECT 3,4,'РасчетПоВыплатамРаботникамЕНВД' WHERE @YEAR <= 2010
--UNION	SELECT 4,4,'НачисленоСтраховыхВзносовВпользуРаботниковЕНВД' WHERE @YEAR <= 2010

CREATE TABLE #STR_2_1B (NUM TINYINT, RAZDEL_NUM TINYINT, BLOK_NAME VARCHAR(254))
INSERT INTO #STR_2_1B 
		SELECT 1,1,'СуммаВыплатИвознагражденийОПС'
UNION	SELECT 2,1,'НеПодлежащиеОбложениюОПС'
UNION	SELECT 3,1,'СуммаРасходовПринимаемыхКвычетуОПС'
UNION	SELECT 4,1,'ПревышающиеПредельнуюВеличинуБазыОПС'
UNION	SELECT 5,1,'БазаДляНачисленияСтраховыхВзносовНаОПС'
UNION	SELECT 6,1,'НачисленоНаОПСсСуммНеПревышающих'
UNION	SELECT 7,1,'НачисленоНаОПСсСуммПревышающих'
UNION	SELECT 8,1,'КоличествоФЛвсего'
UNION	SELECT 9,1,'КоличествоФЛпоКоторымБазаПревысилаПредел'
UNION	SELECT 10,2,'СуммаВыплатИвознаграждений'
UNION	SELECT 11,2,'НеПодлежащиеОбложению'
UNION	SELECT 12,2,'СуммаРасходовПринимаемыхКвычету'
UNION	SELECT 13,2,'ПревышающиеПредельнуюВеличинуБазы'
UNION	SELECT 14,2,'БазаДляНачисленияСтраховыхВзносовНаОМС'
UNION	SELECT 15,2,'НачисленоНаОМС'

--- ДОП ТАРИФЫ раздел 2_2 2_3
CREATE TABLE #TABLES1 (NUM TINYINT, TAB_NAME VARCHAR(254))
INSERT INTO #TABLES1 
		SELECT 5,'Раздел_2_2'
 union SELECT 6,'Раздел_2_3'

 

CREATE TABLE #STR_2_2C (NUM TINYINT, TAB_NUM TINYINT, BLOK_NAME VARCHAR(254))
INSERT INTO #STR_2_2C
		SELECT 1,5,'СуммаВыплатИвознагражденийПоДопТарифу'
UNION	SELECT 2,5,'НеПодлежащиеОбложениюПоДопТарифу'
UNION	SELECT 3,5,'БазаДляНачисленияСтраховыхВзносовПоДопТарифу'
UNION	SELECT 4,5,'НачисленоПоДопТарифу'
UNION	SELECT 5,5,'КоличествоФЛпоДопТарифу'

UNION	SELECT 6,6,'СуммаВыплатИвознагражденийПоДопТарифу'
UNION	SELECT 7,6,'НеПодлежащиеОбложениюПоДопТарифу'
UNION	SELECT 8,6,'БазаДляНачисленияСтраховыхВзносовПоДопТарифу'
UNION	SELECT 9,6,'НачисленоПоДопТарифу'
UNION	SELECT 10,6,'КоличествоФЛпоДопТарифу'


CREATE TABLE #TABLES_2 (NUM2 TINYINT, TAB2_NAME varchar(254))
INSERT INTO #TABLES_2 
		SELECT 7, 'Раздел_2_4'

CREATE TABLE #STR_2_4R (NUM TINYINT, TAB_NUM TINYINT, RAZDEL_NAME VARCHAR(254))
INSERT INTO #STR_2_4R 
		SELECT 1,7,'РасчетНачисленныхПоКодуСпецОценкиУТ'
CREATE TABLE #STR_2_4r1 (NUM TINYINT, RAZDEL_NUM TINYINT, BLOK_NAME VARCHAR(254))
INSERT INTO #STR_2_4r1 
		SELECT 1,1,'РасчетНачисленныхПоДопТарифу'
UNION	SELECT 2,1,'РасчетНачисленныхПоДопТарифу'
UNION	SELECT 3,1,'РасчетНачисленныхПоДопТарифу'
UNION	SELECT 4,1,'РасчетНачисленныхПоДопТарифу'
UNION	SELECT 5,1,'РасчетНачисленныхПоДопТарифу'
CREATE TABLE #STR_2_4B (NUM TINYINT, RAZDEL_NUM TINYINT, BLOK_NAME VARCHAR(254))
INSERT INTO #STR_2_4B 
		SELECT 1,1,'СуммаВыплатИвознагражденийПоДопТарифу'		
UNION	SELECT 2,1,'НеПодлежащиеОбложениюПоДопТарифу'
UNION	SELECT 3,1,'БазаДляНачисленияСтраховыхВзносовПоДопТарифу'
UNION	SELECT 4,1,'НачисленоПоДопТарифу'
UNION	SELECT 5,1,'КоличествоФЛпоДопТарифу'
UNION	SELECT 6,2,'СуммаВыплатИвознагражденийПоДопТарифу'		
UNION	SELECT 7,2,'НеПодлежащиеОбложениюПоДопТарифу'
UNION	SELECT 8,2,'БазаДляНачисленияСтраховыхВзносовПоДопТарифу'
UNION	SELECT 9,2,'НачисленоПоДопТарифу'
UNION	SELECT 10,2,'КоличествоФЛпоДопТарифу'
UNION	SELECT 11,3,'СуммаВыплатИвознагражденийПоДопТарифу'		
UNION	SELECT 12,3,'НеПодлежащиеОбложениюПоДопТарифу'
UNION	SELECT 13,3,'БазаДляНачисленияСтраховыхВзносовПоДопТарифу'
UNION	SELECT 14,3,'НачисленоПоДопТарифу'
UNION	SELECT 15,3,'КоличествоФЛпоДопТарифу'
UNION	SELECT 16,4,'СуммаВыплатИвознагражденийПоДопТарифу'		
UNION	SELECT 17,4,'НеПодлежащиеОбложениюПоДопТарифу'
UNION	SELECT 18,4,'БазаДляНачисленияСтраховыхВзносовПоДопТарифу'
UNION	SELECT 19,4,'НачисленоПоДопТарифу'
UNION	SELECT 20,4,'КоличествоФЛпоДопТарифу'
UNION	SELECT 21,5,'СуммаВыплатИвознагражденийПоДопТарифу'		
UNION	SELECT 22,5,'НеПодлежащиеОбложениюПоДопТарифу'
UNION	SELECT 23,5,'БазаДляНачисленияСтраховыхВзносовПоДопТарифу'
UNION	SELECT 24,5,'НачисленоПоДопТарифу'
UNION	SELECT 25,5,'КоличествоФЛпоДопТарифу'


--INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<' + @TAB_NAME + '>'
--select * from DBO.SA_SAVED_REPORT_VIEW (37368, 3, 0, DEFAULT) T WHERE T.COL IN (3) ORDER BY T.COL


SET @Cur0 = CURSOR FORWARD_ONLY
FOR select NUM, TAB_NAME from #TABLES order by NUM
OPEN @Cur0
FETCH NEXT FROM @Cur0 INTO @TAB_NUM, @TAB_NAME
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN	
	
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<' + @TAB_NAME + '>'
		

		SET @Cur = CURSOR FORWARD_ONLY
		FOR select NUM1, TAB1_NAME from #TABLES_1 WHERE TAB_NUM = @TAB_NUM order by NUM1
		OPEN @Cur
		FETCH NEXT FROM @Cur INTO @TAB1_NUM, @TAB1_NAME
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN	
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<' + @TAB1_NAME + '>'
					
			--- Рабочие тариф 01
			IF @TAB1_NUM = 4
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<КодТарифа>' + LTRIM(RTRIM(ISNULL(TFOMS_KT,''))) + '</КодТарифа>' FROM #DEP_DATA

				SET @Cur1 = CURSOR FORWARD_ONLY
				FOR select NUM, RAZDEL_NAME from #STR_2_1R WHERE TAB_NUM = @TAB1_NUM order by NUM
				OPEN @Cur1
				FETCH NEXT FROM @Cur1 INTO @RAZDEL_NUM, @RAZDEL_NAME
				WHILE (@@fetch_status <> -1)
				BEGIN
					IF (@@fetch_status <> -2)
					BEGIN		

						INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<' + @RAZDEL_NAME + '>'
						
						SET @Cur2 = CURSOR FORWARD_ONLY
						FOR select NUM, BLOK_NAME from #STR_2_1B WHERE RAZDEL_NUM = @RAZDEL_NUM OR RAZDEL_NUM = @RAZDEL_NUM order by NUM
						OPEN @Cur2
						FETCH NEXT FROM @Cur2 INTO @NUM, @BLOK_NAME
						WHILE (@@fetch_status <> -1)
						BEGIN
							IF (@@fetch_status <> -2)
							BEGIN
								if @num = 8 or @num = 9
								begin
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @BLOK_NAME + '>'
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
										SELECT @lcFNAME, 
											CASE WHEN T.COL = 3 THEN SPACE(7) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
												 SPACE(7) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
											ELSE SPACE(7) + '<КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + + '</КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
											END				
										FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @BLOK_NAME + '>'

								end
								else begin
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @BLOK_NAME + '>'
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
										SELECT @lcFNAME, 
											CASE WHEN T.COL = 3 THEN SPACE(7) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
												 SPACE(7) + '<РасчетСумм>' + CHAR(10) +
												 SPACE(8) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
											ELSE SPACE(8) + '<СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + + '</СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
											END				
										FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</РасчетСумм>'
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @BLOK_NAME + '>'
								end
							END
							FETCH NEXT FROM @Cur2 INTO @NUM, @BLOK_NAME
						END
						CLOSE @Cur2
						DEALLOCATE @Cur2

						INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</' + @RAZDEL_NAME + '>'
					END
					FETCH NEXT FROM @Cur1 INTO @RAZDEL_NUM, @RAZDEL_NAME
				END
				CLOSE @Cur1
				DEALLOCATE @Cur1
			
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @TAB1_NAME + '>'
			end	
			FETCH NEXT FROM @Cur INTO @TAB1_NUM, @TAB1_NAME
			END
		CLOSE @Cur
		DEALLOCATE @Cur

		--- Инвалиды тариф 03
		if (select count(*) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, DEFAULT, DEFAULT) T WHERE T.COL = 3 AND SUMMA <> 0 ) > 0
		begin
			SET @CurI0 = CURSOR FORWARD_ONLY
			FOR select NUM1, TAB1_NAME from #TABLES_1 order by NUM1
			OPEN @CurI0
			FETCH NEXT FROM @CurI0 INTO @TAB1_NUM, @TAB1_NAME
			WHILE (@@fetch_status <> -1)
			BEGIN
				IF (@@fetch_status <> -2)
				BEGIN	
				
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<' + @TAB1_NAME + '>'


					--- Инвалиды тариф 03
					IF @TAB1_NUM = 4
						INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<КодТарифа>' + LTRIM(RTRIM(ISNULL(TFOMS_KTI,''))) + '</КодТарифа>' FROM #DEP_DATA

					SET @CurI = CURSOR FORWARD_ONLY
					FOR select NUM, RAZDEL_NAME from #STR_2_1R WHERE TAB_NUM = @TAB1_NUM order by NUM
					OPEN @CurI
					FETCH NEXT FROM @CurI INTO @RAZDEL_NUM, @RAZDEL_NAME
					WHILE (@@fetch_status <> -1)
					BEGIN
						IF (@@fetch_status <> -2)
						BEGIN		

							INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<' + @RAZDEL_NAME + '>'
					
							SET @CurI1 = CURSOR FORWARD_ONLY
							FOR select NUM, BLOK_NAME from #STR_2_1B WHERE RAZDEL_NUM = @RAZDEL_NUM OR RAZDEL_NUM = @RAZDEL_NUM order by NUM
							OPEN @CurI1
							FETCH NEXT FROM @CurI1 INTO @NUM, @BLOK_NAME
							WHILE (@@fetch_status <> -1)
							BEGIN
								IF (@@fetch_status <> -2)
								BEGIN
									if @num = 8 or @num = 9
									begin
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @BLOK_NAME + '>'
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
											SELECT @lcFNAME,
												CASE WHEN T.COL = 3 THEN SPACE(7) + '<КодСтроки>' + substring(LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))),1,3) + '</КодСтроки>' + CHAR(10) +
													 SPACE(7) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
												ELSE SPACE(7) + '<КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + + '</КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
												END				
											FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @BLOK_NAME + '>'
									end
									else begin
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @BLOK_NAME + '>'
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
											SELECT @lcFNAME, 
												CASE WHEN T.COL = 3 THEN SPACE(7) + '<КодСтроки>' + substring(LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))),1,3) + '</КодСтроки>' + CHAR(10) +
													 SPACE(7) + '<РасчетСумм>' + CHAR(10) +
													 SPACE(8) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
												ELSE SPACE(8) + '<СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + + '</СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
												END				
											FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</РасчетСумм>'
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @BLOK_NAME + '>'

									end
								END
								FETCH NEXT FROM @CurI1 INTO @NUM, @BLOK_NAME
							END
							CLOSE @CurI1
							DEALLOCATE @CurI1

							INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</' + @RAZDEL_NAME + '>'
						END
						FETCH NEXT FROM @CurI INTO @RAZDEL_NUM, @RAZDEL_NAME
					END
					CLOSE @CurI
					DEALLOCATE @CurI
						
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @TAB1_NAME + '>'
				END
				FETCH NEXT FROM @CurI0 INTO @TAB1_NUM, @TAB1_NAME
			END
			CLOSE @CurI0
			DEALLOCATE @CurI0	
		end



		------------------------------------------------
		------------------------------------------------

		--- ДОП ТАРИФЫ
		---Раздел 2.2 и 2.3
		SET @CurD0 = CURSOR FORWARD_ONLY
		FOR select NUM, TAB_NAME from #TABLES1 order by NUM
		OPEN @CurD0
		FETCH NEXT FROM @CurD0 INTO @TABD_NUM, @TABD_NAME
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN	
			
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<' + @TABD_NAME + '>'
				--- ДОП ТАРИФЫ 01
				--IF @TAB_NUM = 5
				--	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<КодТарифа>' + LTRIM(RTRIM(ISNULL(TFOMS_KT,''))) + '</КодТарифа>' FROM #DEP_DATA

				--SET @Cur = CURSOR FORWARD_ONLY
				--FOR select NUM, RAZDEL_NAME from #STR_2_1R WHERE TAB_NUM = @TAB_NUM order by NUM
				--OPEN @Cur
				--FETCH NEXT FROM @Cur INTO @RAZDEL_NUM, @RAZDEL_NAME
				--WHILE (@@fetch_status <> -1)
				--BEGIN
				--	IF (@@fetch_status <> -2)
				--	BEGIN		

				--		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<' + @RAZDEL_NAME + '>'
						
						SET @Cur = CURSOR FORWARD_ONLY
						FOR select NUM, BLOK_NAME from #STR_2_2C WHERE TAB_NUM = @TABD_NUM OR TAB_NUM = @TABD_NUM order by NUM
						OPEN @Cur
						FETCH NEXT FROM @Cur INTO @NUM, @BLOK_NAME
						WHILE (@@fetch_status <> -1)
						BEGIN
							IF (@@fetch_status <> -2)
							BEGIN
								if @num = 5 or @num = 10
								begin
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @BLOK_NAME + '>'
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
										SELECT @lcFNAME, 
											CASE WHEN T.COL = 3 THEN SPACE(7) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
												 SPACE(7) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
											ELSE SPACE(7) + '<КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + + '</КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
											END				
										FROM DBO.SA_SAVED_REPORT_VIEW (@link, 5, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @BLOK_NAME + '>'

								end
								else begin
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @BLOK_NAME + '>'
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
										SELECT @lcFNAME, 
											CASE WHEN T.COL = 3 THEN SPACE(7) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
												 SPACE(7) + '<РасчетСумм>' + CHAR(10) +
												 SPACE(8) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
											ELSE SPACE(8) + '<СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + + '</СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
											END				
										FROM DBO.SA_SAVED_REPORT_VIEW (@link, 5, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</РасчетСумм>'
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @BLOK_NAME + '>'
								end
							END
							FETCH NEXT FROM @Cur INTO @NUM, @BLOK_NAME
						END
						CLOSE @Cur
						DEALLOCATE @Cur

				--		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @RAZDEL_NAME + '>'
				--	END
				--	FETCH NEXT FROM @Cur INTO @RAZDEL_NUM, @RAZDEL_NAME
				--END
				--CLOSE @Cur
				--DEALLOCATE @Cur
			
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @TABD_NAME + '>'
			END
			FETCH NEXT FROM @CurD0 INTO @TABD_NUM, @TABD_NAME

		END
		CLOSE @CurD0
		DEALLOCATE @CurD0

		------------------------------------------------
		------------------------------------------------

		--- ДОП ТАРИФЫ
		---Раздел 2.4_1 и 2.4_2
		SET @Cur00 = CURSOR FORWARD_ONLY
		FOR select NUM2, TAB2_NAME from #TABLES_2 
		OPEN @Cur00
		FETCH NEXT FROM @Cur00 INTO @TAB1_NUM, @TAB1_NAME
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN	
			
				if (select count(*) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, DEFAULT, DEFAULT) T WHERE T.COL = 3 AND SUMMA <> 0 ) > 0
				BEGIN	
			--- --- доп тариф 01
				IF @TAB1_NUM = 7
				BEGIN
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<' + @TAB1_NAME + '>'
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<КодОснованияРасчетаПоДопТарифу>' + LTRIM(RTRIM('1')) + '</КодОснованияРасчетаПоДопТарифу>'
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ОснованиеЗаполненияРаздела2_4>' + LTRIM(RTRIM('РЕЗУЛЬТАТЫ СПЕЦОЦЕНКИ')) + '</ОснованиеЗаполненияРаздела2_4>'
				end
				SET @Cur000 = CURSOR FORWARD_ONLY
				FOR select NUM, RAZDEL_NAME from #STR_2_4R WHERE TAB_NUM = @TAB1_NUM order by NUM
				OPEN @Cur000
				FETCH NEXT FROM @Cur000 INTO @RAZDEL_NUM, @RAZDEL_NAME
				WHILE (@@fetch_status <> -1)
				BEGIN
					IF (@@fetch_status <> -2)
					BEGIN		

						
						
						
						--NUM TINYINT, RAZDEL_NUM TINYINT, BLOK_NAME 
						SET @Cur1 = CURSOR FORWARD_ONLY
						FOR select NUM, BLOK_NAME from #STR_2_4R1 WHERE RAZDEL_NUM = @RAZDEL_NUM order by NUM
						OPEN @Cur1
						FETCH NEXT FROM @Cur1 INTO @TABD_NUM, @TABD_NAME
						WHILE (@@fetch_status <> -1)
						BEGIN
							IF (@@fetch_status <> -2)
							BEGIN		
								
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<' + @RAZDEL_NAME + '>'
								
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) 
											SELECT @lcFNAME, 
													SPACE(6) + '<КодСпециальнойОценкиУсловийТруда>' + 
													(CASE WHEN @TABD_NUM = 1 THEN LTRIM(RTRIM('О4'))
														 WHEN @TABD_NUM = 2 THEN LTRIM(RTRIM('В3.4'))
														 WHEN @TABD_NUM = 3 THEN LTRIM(RTRIM('В3.3'))
														 WHEN @TABD_NUM = 4 THEN LTRIM(RTRIM('В3.2'))
														 ELSE LTRIM(RTRIM('В3.1')) END ) + '</КодСпециальнойОценкиУсловийТруда>'
								
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @TABD_NAME + '>'	
									
									
									SET @Cur2 = CURSOR FORWARD_ONLY
									FOR select NUM, BLOK_NAME from #STR_2_4B WHERE RAZDEL_NUM = @TABD_NUM OR RAZDEL_NUM = @TABD_NUM order by NUM
									OPEN @Cur2
									FETCH NEXT FROM @Cur2 INTO @NUM, @BLOK_NAME
									WHILE (@@fetch_status <> -1)
									BEGIN
										IF (@@fetch_status <> -2)
										BEGIN
												
																						
											if @num = 5 or @num = 10 or @num = 15 or @num = 20 or @num = 25 
											begin
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '<' + @BLOK_NAME + '>'
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT @lcFNAME, 
														CASE WHEN T.COL = 3 THEN SPACE(8) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
															 SPACE(8) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
														ELSE SPACE(8) + '<КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + + '</КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
														END				
													FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</' + @BLOK_NAME + '>'

											end
											else begin
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '<' + @BLOK_NAME + '>'
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT @lcFNAME, 
														CASE WHEN T.COL = 3 THEN SPACE(8) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
															 SPACE(8) + '<РасчетСумм>' + CHAR(10) +
															 SPACE(9) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
														ELSE SPACE(9) + '<СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + + '</СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
														END				
													FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(8) + '</РасчетСумм>'
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</' + @BLOK_NAME + '>'
											end
										END
										FETCH NEXT FROM @Cur2 INTO @NUM, @BLOK_NAME
									END
									CLOSE @Cur2
									DEALLOCATE @Cur2
								
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @TABD_NAME + '>'	
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</' + @RAZDEL_NAME + '>'
							END
							FETCH NEXT FROM @Cur1 INTO @TABD_NUM, @TABD_NAME
					
						END
						CLOSE @Cur1
						DEALLOCATE @Cur1						
						
						
						
					END
					FETCH NEXT FROM @Cur000 INTO @RAZDEL_NUM, @RAZDEL_NAME	
				END 	
				CLOSE @Cur000
				DEALLOCATE @Cur000
				
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @TAB1_NAME + '>'
				END 
				/***************************/	
			--- доп тариф 2
				/***************************/
				if (select count(*) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, DEFAULT, DEFAULT) T WHERE T.COL = 3 AND SUMMA <> 0 ) > 0
				begin
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<' + @TAB1_NAME + '>'
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<КодОснованияРасчетаПоДопТарифу>' + LTRIM(RTRIM('2')) + '</КодОснованияРасчетаПоДопТарифу>'
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ОснованиеЗаполненияРаздела2_4>' + LTRIM(RTRIM('РЕЗУЛЬТАТЫ СПЕЦОЦЕНКИ')) + '</ОснованиеЗаполненияРаздела2_4>'

					SET @CurI0 = CURSOR FORWARD_ONLY
					FOR select NUM, RAZDEL_NAME from #STR_2_4R WHERE TAB_NUM = @TAB1_NUM order by NUM
					OPEN @CurI0
					FETCH NEXT FROM @CurI0 INTO @RAZDEL_NUM, @RAZDEL_NAME
					WHILE (@@fetch_status <> -1)
					BEGIN
						IF (@@fetch_status <> -2)
						BEGIN		

							
														
							--NUM TINYINT, RAZDEL_NUM TINYINT, BLOK_NAME 
							SET @CurI00 = CURSOR FORWARD_ONLY
							FOR select NUM, BLOK_NAME from #STR_2_4R1 WHERE RAZDEL_NUM = @RAZDEL_NUM order by NUM
							OPEN @CurI00
							FETCH NEXT FROM @CurI00 INTO @TABD_NUM, @TABD_NAME
							WHILE (@@fetch_status <> -1)
							BEGIN
								IF (@@fetch_status <> -2)
								BEGIN	
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<' + @RAZDEL_NAME + '>'	
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) 
											SELECT @lcFNAME, 
													SPACE(6) + '<КодСпециальнойОценкиУсловийТруда>' + 
													(CASE WHEN @TABD_NUM = 1 THEN LTRIM(RTRIM('О4'))
														 WHEN @TABD_NUM = 2 THEN LTRIM(RTRIM('В3.4'))
														 WHEN @TABD_NUM = 3 THEN LTRIM(RTRIM('В3.3'))
														 WHEN @TABD_NUM = 4 THEN LTRIM(RTRIM('В3.2'))
														 ELSE LTRIM(RTRIM('В3.1')) END ) + '</КодСпециальнойОценкиУсловийТруда>'
									
									
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @TABD_NAME + '>'	
										
										
										SET @CurI000 = CURSOR FORWARD_ONLY
										FOR select NUM, BLOK_NAME from #STR_2_4B WHERE RAZDEL_NUM = @TABD_NUM OR RAZDEL_NUM = @TABD_NUM order by NUM
										OPEN @CurI000
										FETCH NEXT FROM @CurI000 INTO @NUM, @BLOK_NAME
										WHILE (@@fetch_status <> -1)
										BEGIN
											IF (@@fetch_status <> -2)
											BEGIN
												if @num = 5 or @num = 10 or @num = 15 or @num = 20 or @num = 25 
												begin
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '<' + @BLOK_NAME + '>'
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														SELECT @lcFNAME, 
															CASE WHEN T.COL = 3 THEN SPACE(8) + '<КодСтроки>' + substring(LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))),1,3) + '</КодСтроки>' + CHAR(10) +
																 SPACE(8) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
															ELSE SPACE(8) + '<КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + + '</КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
															END				
														FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</' + @BLOK_NAME + '>'

												end
												else begin
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '<' + @BLOK_NAME + '>'
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														SELECT @lcFNAME, 
															CASE WHEN T.COL = 3 THEN SPACE(8) + '<КодСтроки>' + substring(LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))),1,3) + '</КодСтроки>' + CHAR(10) +
																 SPACE(8) + '<РасчетСумм>' + CHAR(10) +
																 SPACE(9) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
															ELSE SPACE(9) + '<СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + + '</СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
															END				
														FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(8) + '</РасчетСумм>'
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</' + @BLOK_NAME + '>'
												end
											END
											FETCH NEXT FROM @CurI000 INTO @NUM, @BLOK_NAME
										END
										CLOSE @CurI000
										DEALLOCATE @CurI000
									
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @TABD_NAME + '>'	
									
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</' + @RAZDEL_NAME + '>'
								END
								FETCH NEXT FROM @CurI00 INTO @TABD_NUM, @TABD_NAME
						
							END
							CLOSE @CurI00
							DEALLOCATE @CurI00						
							
							
							
						END
						FETCH NEXT FROM @CurI0 INTO @RAZDEL_NUM, @RAZDEL_NAME	
					END 	
					CLOSE @CurI0
					DEALLOCATE @CurI0
				
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @TAB1_NAME + '>'
				/*****************/
				END
			
				--INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @TAB1_NAME + '>'
			end	
			FETCH NEXT FROM @Cur00 INTO @TAB1_NUM, @TAB1_NAME
		END
		CLOSE @Cur00
		DEALLOCATE @Cur00

		-----Разделы 2.5.1 и 2.5.2
		CREATE TABLE #PACHKA_ISH (
			LINK INT, NOM_PACH VARCHAR(10), SUM_BASE NUMERIC(18,2), SUM_NACH NUMERIC(18,2), KOL_ZL NUMERIC(5), 
			NAME_FILE VARCHAR(254))

		CREATE TABLE #TAB3 (ROW_CODE VARCHAR(10), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
		INSERT INTO #TAB3 (ROW_CODE, COL, SUMMA, STR_VAL)
		SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

		INSERT INTO #PACHKA_ISH (NOM_PACH, SUM_BASE, SUM_NACH, KOL_ZL, NAME_FILE)
		SELECT DISTINCT 
			NOM_PACH = (SELECT TOP 1 ROW_CODE FROM #TAB3 T WHERE T.COL = 2 AND T.ROW_CODE = T3.ROW_CODE),
			SUM_BASE = (SELECT TOP 1 SUMMA FROM #TAB3 T WHERE T.COL = 3 AND T.ROW_CODE = T3.ROW_CODE),
			SUM_NACH = (SELECT TOP 1 SUMMA FROM #TAB3 T WHERE T.COL = 4 AND T.ROW_CODE = T3.ROW_CODE),
			KOL_ZL = (SELECT TOP 1 SUMMA FROM #TAB3 T WHERE T.COL = 5 AND T.ROW_CODE = T3.ROW_CODE),
			NAME_FILE = (SELECT TOP 1 STR_VAL FROM #TAB3 T WHERE T.COL = 6 AND T.ROW_CODE = T3.ROW_CODE)
		FROM
			#TAB3 T3

		DROP TABLE #TAB3

		DECLARE @NUM_pp INT
		SET @NUM_pp = 0
		UPDATE #PACHKA_ISH SET @NUM_pp = @NUM_pp + 1, LINK = @NUM_pp

		
		CREATE TABLE #PACHKA_KOR (
			LINK INT, NOM_PACH VARCHAR(4), PERIOD_CODE VARCHAR(1), PERIOD_YEAR VARCHAR(4),SUM_D NUMERIC(18,2), SUM_D_STR NUMERIC(18,2) , SUM_D_NAK NUMERIC(18,2), KOL_ZL NUMERIC(5), 
			NAME_FILE VARCHAR(254))

		CREATE TABLE #TAB4 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
		INSERT INTO #TAB4 (ROW_CODE, COL, SUMMA, STR_VAL)
		SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

		INSERT INTO #PACHKA_KOR (NOM_PACH, PERIOD_CODE, PERIOD_YEAR,SUM_D, SUM_D_STR, SUM_D_NAK, KOL_ZL, NAME_FILE)
		SELECT DISTINCT 
			NOM_PACH = (SELECT TOP 1 ROW_CODE FROM #TAB4 T WHERE T.COL = 2 AND T.ROW_CODE = T4.ROW_CODE),
			PERIOD_CODE = (SELECT TOP 1 STR_VAL FROM #TAB4 T WHERE T.COL = 3 AND T.ROW_CODE = T4.ROW_CODE),
			PERIOD_YEAR = (SELECT TOP 1 STR_VAL FROM #TAB4 T WHERE T.COL = 4 AND T.ROW_CODE = T4.ROW_CODE),
			SUM_D = (SELECT TOP 1 SUMMA FROM #TAB4 T WHERE T.COL = 5 AND T.ROW_CODE = T4.ROW_CODE),
			SUM_D_STR = (SELECT TOP 1 SUMMA FROM #TAB4 T WHERE T.COL = 6 AND T.ROW_CODE = T4.ROW_CODE),
			SUM_D_NAK = (SELECT TOP 1 SUMMA FROM #TAB4 T WHERE T.COL = 7 AND T.ROW_CODE = T4.ROW_CODE),
			KOL_ZL = (SELECT TOP 1 SUMMA FROM #TAB4 T WHERE T.COL = 8 AND T.ROW_CODE = T4.ROW_CODE),
			NAME_FILE = (SELECT TOP 1 STR_VAL FROM #TAB4 T WHERE T.COL = 9 AND T.ROW_CODE = T4.ROW_CODE)
		FROM
			#TAB4 T4

		DROP TABLE #TAB4
		
		SET @NUM_pp = 0
		UPDATE #PACHKA_KOR SET @NUM_pp = @NUM_pp + 1, LINK = @NUM_pp


		IF (SELECT COUNT(*) FROM #PACHKA_ISH) > 0 -- исходные сведения
			OR (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 8, DEFAULT, DEFAULT) WHERE COL = 5 AND SUMMA2 <> 0) > 0 
		BEGIN
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел_2_5>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ПереченьПачекИсходныхСведенийПУ>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<КоличествоПачек>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),(SELECT COUNT(*) FROM #PACHKA_ISH)),''))) + '</КоличествоПачек>'

			UNION ALL SELECT @lcFNAME, 
				SPACE(6) + '<СведенияОпачкеИсходных>' + CHAR(10) +
					SPACE(7) + '<НомерПП>' + LTRIM(RTRIM(CONVERT(VARCHAR(10),ISNULL(LINK,0)))) + '</НомерПП>' + CHAR(10) +			
					SPACE(7) + '<БазаДляНачисленияСтраховыхВзносовНеПревышающаяПредельную>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_BASE,0)))) + '</БазаДляНачисленияСтраховыхВзносовНеПревышающаяПредельную>' + CHAR(10) +	
					SPACE(7) + '<СтраховыхВзносовОПС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_NACH,0)))) + '</СтраховыхВзносовОПС>' + CHAR(10) +	
					SPACE(7) + '<КоличествоЗЛвПачке>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(KOL_ZL,0)))) + '</КоличествоЗЛвПачке>' + CHAR(10) +
					SPACE(7) + '<ИмяФайла>' + LTRIM(RTRIM(ISNULL(NAME_FILE,''))) + '</ИмяФайла>'+ CHAR(10) +					
					SPACE(6) + '</СведенияОпачкеИсходных>'		
			    FROM #PACHKA_ISH
			UNION ALL SELECT @lcFNAME, 
				SPACE(7) + '<ИтогоСведенияПоПачкам>' + CHAR(10) + 
					SPACE(8) + '<БазаДляНачисленияСтраховыхВзносовНеПревышающаяПредельную>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SUM_BASE),0)))) + '</БазаДляНачисленияСтраховыхВзносовНеПревышающаяПредельную>' + CHAR(10) +			
					SPACE(8) + '<СтраховыхВзносовОПС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SUM_NACH),0)))) + '</СтраховыхВзносовОПС>' + CHAR(10) +
					SPACE(8) + '<КоличествоЗЛвПачке>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(KOL_ZL),0)))) + '</КоличествоЗЛвПачке>' + CHAR(10) +
				SPACE(7) + '</ИтогоСведенияПоПачкам>'
			FROM #PACHKA_ISH	
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ПереченьПачекИсходныхСведенийПУ>'

			IF (SELECT COUNT(*) FROM #PACHKA_KOR) > 0 -- исходные сведения
				OR (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 9, DEFAULT, DEFAULT) WHERE COL = 8 AND SUMMA2 <> 0) > 0 
			BEGIN
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ПереченьПачекКорректирующихСведенийПУ>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<КоличествоПачек>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),(SELECT COUNT(*) FROM #PACHKA_KOR)),''))) + '</КоличествоПачек>'

				UNION ALL SELECT @lcFNAME, 
					SPACE(6) + '<СведенияОпачкеКорректирующих>' + CHAR(10) +
						SPACE(7) + '<НомерПП>' + LTRIM(RTRIM(CONVERT(VARCHAR(10),ISNULL(LINK,0)))) + '</НомерПП>' + CHAR(10) +			
						SPACE(7) + '<КорректируемыйОтчетныйПериод>' + CHAR(10) + 
							SPACE(8) + '<Квартал>' + LTRIM(RTRIM(ISNULL((CASE WHEN PERIOD_CODE= '1' THEN '3'
																			 WHEN PERIOD_CODE= '2' THEN '6'
																			 WHEN PERIOD_CODE= '3' THEN '9'
																			 ELSE 0 END
																		 ),''))) + '</Квартал>' + CHAR(10) +	
							SPACE(8) + '<Год>' + LTRIM(RTRIM(ISNULL(PERIOD_YEAR,''))) + '</Год>' + CHAR(10) +
							SPACE(8) + '<Название>' + LTRIM(RTRIM(ISNULL((CASE WHEN PERIOD_CODE= '1' THEN 'С 01.01.'+PERIOD_YEAR+' ПО 31.03.'+PERIOD_YEAR+''
																			 WHEN PERIOD_CODE= '2' THEN 'С 01.01.'+PERIOD_YEAR+' ПО 30.06.'+PERIOD_YEAR+''
																			 WHEN PERIOD_CODE= '3' THEN 'С 01.01.'+PERIOD_YEAR+' ПО 30.09.'+PERIOD_YEAR+''
																			 ELSE 'С 01.01.'+PERIOD_YEAR+' ПО 31.12.'+PERIOD_YEAR+'' END
																		 ),''))) + '</Название>' + CHAR(10) +
						SPACE(7) + '</КорректируемыйОтчетныйПериод>' + CHAR(10) + 
						SPACE(7) + '<ДоначисленоСтраховыхВзносовОПС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_D,0)))) + '</ДоначисленоСтраховыхВзносовОПС>' + CHAR(10) +	
						SPACE(7) + '<ДоначисленоНаСтраховуюЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_D_STR,0)))) + '</ДоначисленоНаСтраховуюЧасть>' + CHAR(10) +	
						SPACE(7) + '<ДоначисленоНаНакопительнуюЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_D_NAK,0)))) + '</ДоначисленоНаНакопительнуюЧасть>' + CHAR(10) +	
						SPACE(7) + '<КоличествоЗЛвПачке>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(KOL_ZL,0)))) + '</КоличествоЗЛвПачке>' + CHAR(10) +
						SPACE(7) + '<ИмяФайла>' + LTRIM(RTRIM(ISNULL(NAME_FILE,''))) + '</ИмяФайла>'+ CHAR(10) +					
					SPACE(6) + '</СведенияОпачкеКорректирующих>' 	
					FROM #PACHKA_KOR
				UNION ALL SELECT @lcFNAME, 
					SPACE(7) + '<ИтогоСведенияПоПачкамКорректирующих>' + CHAR(10) + 
						SPACE(8) + '<ДоначисленоСтраховыхВзносовОПС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SUM_D),0)))) + '</ДоначисленоСтраховыхВзносовОПС>' + CHAR(10) +			
						SPACE(8) + '<ДоначисленоНаСтраховуюЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SUM_D_STR),0)))) + '</ДоначисленоНаСтраховуюЧасть>' + CHAR(10) +
						SPACE(8) + '<ДоначисленоНаНакопительнуюЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SUM_D_NAK),0)))) + '</ДоначисленоНаНакопительнуюЧасть>' + CHAR(10) +
						SPACE(8) + '<КоличествоЗЛвПачке>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(KOL_ZL),0)))) + '</КоличествоЗЛвПачке>' + CHAR(10) +
					SPACE(7) + '</ИтогоСведенияПоПачкамКорректирующих>'
				FROM #PACHKA_KOR	
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ПереченьПачекКорректирующихСведенийПУ>'
			END


			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел_2_5>'	

		END


		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '</' + @TAB_NAME + '>'


	END
	FETCH NEXT FROM @Cur0 INTO @TAB_NUM, @TAB_NAME
END
CLOSE @Cur0
DEALLOCATE @Cur0


-----Разделы 3
/*CREATE TABLE #INVALID (
	LINK INT, FIO VARCHAR(254), FIO2 VARCHAR(254), NUM_SPR VARCHAR(30), DATE_SPR VARCHAR(10), 
	GRP VARCHAR(25), GRP2 VARCHAR(25), PER_BEG VARCHAR(10), PER_END VARCHAR(10), 
	SM_ALL 	NUMERIC(18,2), SM_QWART NUMERIC(18,2), SM1 NUMERIC(18,2), SM2 NUMERIC(18,2), SM3 NUMERIC(18,2) )

CREATE TABLE #TAB5 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
INSERT INTO #TAB5 (ROW_CODE, COL, SUMMA, STR_VAL)
SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

INSERT INTO #INVALID (FIO2, DATE_SPR, PER_END, SM_ALL, SM1, SM2, SM3)
SELECT DISTINCT 
	FIO2 = (SELECT TOP 1 REPLACE(STR_VAL,SPACE(1), ', ') FROM #TAB5 T WHERE T.COL = 2 AND T.ROW_CODE = T5.ROW_CODE),
	DATE_SPR = (SELECT TOP 1 STR_VAL FROM #TAB5 T WHERE T.COL = 3 AND T.ROW_CODE = T5.ROW_CODE),
	PER_END = (SELECT TOP 1 STR_VAL FROM #TAB5 T WHERE T.COL = 4 AND T.ROW_CODE = T5.ROW_CODE),
	SM_ALL = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 5 AND T.ROW_CODE = T5.ROW_CODE),
	SM1 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 6 AND T.ROW_CODE = T5.ROW_CODE),
	SM2 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 7 AND T.ROW_CODE = T5.ROW_CODE),
	SM3 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 8 AND T.ROW_CODE = T5.ROW_CODE)
FROM
	#TAB5 T5

DROP TABLE #TAB5

--Проставить номера попорядку
DECLARE @NEXT_NUM INT
SET @NEXT_NUM = 0
UPDATE #INVALID SET @NEXT_NUM = @NEXT_NUM + 1, LINK = @NEXT_NUM

IF (SELECT COUNT(*) FROM #INVALID) > 0 -- инвалиды
	OR (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 7, DEFAULT, DEFAULT) WHERE COL = 3 AND SUMMA <> 0) > 0 -- информ. технол.
BEGIN
	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<Раздел3РасчетНаПравоПримененияПониженногоТарифа>'
---Раздел3_1	
	IF (SELECT COUNT(*) FROM #INVALID) > 0 -- инвалиды
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_1_СведенияДляПримененияПониженногоТарифа>'

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<КоличествоРаботниковИнвалидов>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),(SELECT COUNT(*) FROM #INVALID)),''))) + '</КоличествоРаботниковИнвалидов>'
		UNION ALL SELECT @lcFNAME, 
			SPACE(5) + '<СведенияОработникеИнвалиде>' + CHAR(10) +
				SPACE(6) + '<НомерПП>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(LINK,0)))) + '</НомерПП>' + CHAR(10) +			
				SPACE(6) + '<ФИО>' + CHAR(10) + 
					SPACE(7) + '<Фамилия>' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,1,','),' ')))) + '</Фамилия>' + CHAR(10) + 		
					SPACE(7) + '<Имя>' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,2,','),' ')))) + '</Имя>' + CHAR(10) + 		
					SPACE(7) + '<Отчество>' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,3,','),' ')))) + '</Отчество>' + CHAR(10) + 										
				SPACE(6) + '</ФИО>' + CHAR(10) + 
				SPACE(6) + '<СведенияИзСправки>' + CHAR(10) + 
					SPACE(7) + '<ДатаВыдачиСправки>' + LTRIM(RTRIM(ISNULL(DATE_SPR,' '))) + '</ДатаВыдачиСправки>' + CHAR(10) +
					SPACE(7) + '<ДатаОкончанияДействия>' + LTRIM(RTRIM(ISNULL(PER_END,''))) + '</ДатаОкончанияДействия>' + CHAR(10) +
				SPACE(6) + '</СведенияИзСправки>' + CHAR(10) + 				
				SPACE(6) + '<СуммыВыплатИвознаграждений>' + CHAR(10) +
					SPACE(7) + '<СуммаВсегоСначалаРасчетногоПериода>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM_ALL,0)))) + '</СуммаВсегоСначалаРасчетногоПериода>' + CHAR(10) +			
					SPACE(7) + '<СуммаПоследние1месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM1,0)))) + '</СуммаПоследние1месяц>' + CHAR(10) +
					SPACE(7) + '<СуммаПоследние2месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM2,0)))) + '</СуммаПоследние2месяц>' + CHAR(10) +
					SPACE(7) + '<СуммаПоследние3месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM3,0)))) + '</СуммаПоследние3месяц>' + CHAR(10) +								
				SPACE(6) + '</СуммыВыплатИвознаграждений>' + CHAR(10) +			
			SPACE(5) + '</СведенияОработникеИнвалиде>'
		FROM #INVALID
		UNION ALL SELECT @lcFNAME, 
			SPACE(5) + '<ИтогоВыплат>' + CHAR(10) + 
				SPACE(6) + '<СуммаВсегоСначалаРасчетногоПериода>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SM_ALL),0)))) + '</СуммаВсегоСначалаРасчетногоПериода>' + CHAR(10) +			
				SPACE(6) + '<СуммаПоследние1месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SM1),0)))) + '</СуммаПоследние1месяц>' + CHAR(10) +
				SPACE(6) + '<СуммаПоследние2месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SM2),0)))) + '</СуммаПоследние2месяц>' + CHAR(10) +
				SPACE(6) + '<СуммаПоследние3месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SM3),0)))) + '</СуммаПоследние3месяц>' + CHAR(10) +								
			SPACE(5) + '</ИтогоВыплат>'
		FROM #INVALID	

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_1_СведенияДляПримененияПониженногоТарифа>'	

*/		

		
		---Раздел3---
IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 10, DEFAULT, 3) WHERE SUMMA <> 0) > 0
BEGIN
			
	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<Раздел3РасчетНаПравоПримененияПониженногоТарифа2014>'
	  
	---Раздел3_1---	
	IF ( SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 10, 1, DEFAULT) WHERE SUMMA <> 0) > 0
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_1_ДляОбщественныхОрганизацийИнвалидов>'
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ЧисленностьЧленовОрганизации>'
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, CASE T.COL 
							WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
										SPACE(6) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
							WHEN 4 THEN SPACE(6) + '<КоличествоЗЛ_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_1месяц>'
							WHEN 5 THEN SPACE(6) + '<КоличествоЗЛ_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_2месяц>'		
							WHEN 6 THEN SPACE(6) + '<КоличествоЗЛ_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_3месяц>'
						END						
		FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 1, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ЧисленностьЧленовОрганизации>'

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ЧисленностьИнвалидов>'
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, CASE T.COL 
			WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
				 SPACE(6) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
			WHEN 4 THEN SPACE(6) + '<КоличествоЗЛ_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_1месяц>'
			WHEN 5 THEN SPACE(6) + '<КоличествоЗЛ_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_2месяц>'		
			WHEN 6 THEN SPACE(6) + '<КоличествоЗЛ_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_3месяц>'
			END						
		FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 2, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ЧисленностьИнвалидов>'

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<УдельныйВесЧисленности>'
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, CASE T.COL 
			WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
				 SPACE(6) + '<УдельныйВес_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_Всего>'
			WHEN 4 THEN SPACE(6) + '<УдельныйВес_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_1месяц>'
			WHEN 5 THEN SPACE(6) + '<УдельныйВес_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_2месяц>'		
			WHEN 6 THEN SPACE(6) + '<УдельныйВес_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_3месяц>'
			END						
		FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 3, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</УдельныйВесЧисленности>'			
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_1_ДляОбщественныхОрганизацийИнвалидов>'
	END	--IF ( SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 10, 1, DEFAULT) WHERE SUMMA <> 0) > 0 	



---Раздел3_2

	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 4, DEFAULT) WHERE SUMMA <> 0) > 0
	BEGIN

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_2_ДляОрганизацийУставныйКапиталСостоитИзВкладовОбщОргИнвалидов>'
					
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СреднесписочнаяЧисленность>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
							SPACE(6) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
				WHEN 4 THEN SPACE(6) + '<КоличествоЗЛ_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_1месяц>'
				WHEN 5 THEN SPACE(6) + '<КоличествоЗЛ_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_2месяц>'		
				WHEN 6 THEN SPACE(6) + '<КоличествоЗЛ_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_3месяц>'
				END						
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 4, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СреднесписочнаяЧисленность>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СреднесписочнаяЧисленностьИнвалидов>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
		  					SPACE(6) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
				WHEN 4 THEN SPACE(6) + '<КоличествоЗЛ_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_1месяц>'
				WHEN 5 THEN SPACE(6) + '<КоличествоЗЛ_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_2месяц>'		
				WHEN 6 THEN SPACE(6) + '<КоличествоЗЛ_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_3месяц>'
				END						
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 5, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СреднесписочнаяЧисленностьИнвалидов>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<УдельныйВесЧисленности>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
							SPACE(6) + '<УдельныйВес_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_Всего>'
				WHEN 4 THEN SPACE(6) + '<УдельныйВес_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_1месяц>'
				WHEN 5 THEN SPACE(6) + '<УдельныйВес_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_2месяц>'		
				WHEN 6 THEN SPACE(6) + '<УдельныйВес_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_3месяц>'
			END						
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 6, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</УдельныйВесЧисленности>'
					
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ФондОплатыТруда>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
							SPACE(6) + '<РасчетСумм>' + CHAR(10) +
								SPACE(7) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
					WHEN 4 THEN SPACE(7) + '<СуммаПоследние1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаПоследние1месяц>'
					WHEN 5 THEN SPACE(7) + '<СуммаПоследние2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаПоследние2месяц>'		
					WHEN 6 THEN SPACE(7) + '<СуммаПоследние3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаПоследние3месяц>'
				END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 7, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</РасчетСумм>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ФондОплатыТруда>'		
		
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ЗарплатаИнвалидов>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
		 					SPACE(6) + '<РасчетСумм>' + CHAR(10) +
								SPACE(7) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
					WHEN 4 THEN SPACE(7) + '<СуммаПоследние1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаПоследние1месяц>'
					WHEN 5 THEN SPACE(7) + '<СуммаПоследние2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаПоследние2месяц>'		
					WHEN 6 THEN SPACE(7) + '<СуммаПоследние3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаПоследние3месяц>'
				END						
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 8, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</РасчетСумм>'			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ЗарплатаИнвалидов>'		
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<УдельныйВесЗарплатыИнвалидов>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
							 SPACE(6) + '<УдельныйВес_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_Всего>'
				WHEN 4 THEN SPACE(6) + '<УдельныйВес_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_1месяц>'
				WHEN 5 THEN SPACE(6) + '<УдельныйВес_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_2месяц>'		
				WHEN 6 THEN SPACE(6) + '<УдельныйВес_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_3месяц>'
				END						
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 9, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</УдельныйВесЗарплатыИнвалидов>'
						
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_2_ДляОрганизацийУставныйКапиталСостоитИзВкладовОбщОргИнвалидов>'
	END --IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 4, DEFAULT) WHERE SUMMA <> 0) > 0

	
	--Раздел3_3
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 11, DEFAULT, DEFAULT) WHERE COL = 3 AND SUMMA <> 0) > 0 -- информ. технол.
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_3_ДляОрганизацийИТ>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СуммаДоходовПоНКвсего>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
							WHEN 2 THEN	SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>'
							WHEN 3 THEN	SPACE(6) + '<СуммаДоходаПоПредшествующему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>' 
							WHEN 4 THEN SPACE(6) + '<СуммаДоходаПоТекущему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'
							END
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, DEFAULT) T where col in (2,3,4) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, + SPACE(5) +'</СуммаДоходовПоНКвсего>'
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СуммаДоходовИТизНих>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
							WHEN 2 THEN	SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' 
							WHEN 3 THEN SPACE(6) + '<СуммаДоходаПоПредшествующему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>' 
							WHEN 4 THEN SPACE(6) + '<СуммаДоходаПоТекущему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'
							END
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, DEFAULT) T where col in (2,3,4) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СуммаДоходовИТизНих>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ДоляДоходовИТ>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
							WHEN 2 THEN	SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' 
							WHEN 3 THEN	SPACE(6) + '<ДоляДоходаПоПредшествующему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</ДоляДоходаПоПредшествующему>' 
							WHEN 4 THEN	SPACE(6) + '<ДоляДоходаПоТекущему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</ДоляДоходаПоТекущему>'
							END
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 3,DEFAULT) T where col in (2,3,4) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ДоляДоходовИТ>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ЧисленностьРаботниковИТ>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME,CASE T.COL 
							WHEN 2 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' 
							WHEN 3 THEN	SPACE(6) + '<КоличествоЗЛпоПредшествующему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛпоПредшествующему>' 
							WHEN 4 THEN SPACE(6) + '<КоличествоЗЛпоТекущему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛпоТекущему>' 
							END
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, DEFAULT) T where col in (2,3,4) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ЧисленностьРаботниковИТ>'


			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СведенияИзРеестраИТ>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>'
				WHEN 5 THEN SPACE(6) + '<ДатаЗаписиВреестре>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,'\ \.\ \.\  '))) + '</ДатаЗаписиВреестре>'
				WHEN 6 THEN SPACE(6) + '<НомерЗаписиВреестре>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</НомерЗаписиВреестре>'		
				END						
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, DEFAULT) T WHERE T.COL IN (3,5,6) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СведенияИзРеестраИТ>'
		
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_3_ДляОрганизацийИТ>'
	END	 --IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 11, DEFAULT, DEFAULT) WHERE COL = 3 AND SUMMA <> 0) > 0 

	----Раздел3_4	
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 12, DEFAULT, DEFAULT) WHERE COL = 5 AND SUMMA <> 0) > 0 -- информ. технол.
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_4_ДляОрганизацийСМИ>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СведенияПоВидуДеятельности>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
					SELECT @lcFNAME, CASE T.COL 
					WHEN 1 THEN SPACE(6) + '<НомерПП>' + LTRIM(RTRIM(T.ROW)) + '</НомерПП>'
					WHEN 2 THEN SPACE(6) + '<НаименованиеВидаЭД>' + LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</НаименованиеВидаЭД>' + CHAR(10) +
								SPACE(6) + '<КодПоОКВЭД>' + LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</КодПоОКВЭД>'
					WHEN 5 THEN SPACE(6) + '<ДоходыПоВидуЭД>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</ДоходыПоВидуЭД>'
					WHEN 6 THEN	SPACE(6) + '<ДоляДоходовПоВидуЭД>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</ДоляДоходовПоВидуЭД>'		
					END
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, DEFAULT, DEFAULT) T where T.ROW IN (1,2,3,4,5,6,7,8,9,10) and T.COL IN (1,2,5,6) ORDER BY T.ROW, t.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СведенияПоВидуДеятельности>'
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ИтогоПоВсемВидамДеятельности>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) +'</ИтогоПоВсемВидамДеятельности>'
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 11, 5) T ORDER BY T.COL
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СведенияИзРеестраСМИ>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 4 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>'
					WHEN 7 THEN SPACE(6) + '<ДатаЗаписиВреестре>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,'\ \.\ \.\  '))) + '</ДатаЗаписиВреестре>'
					WHEN 8 THEN SPACE(6) + '<НомерЗаписиВреестре>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</НомерЗаписиВреестре>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 12, DEFAULT) T WHERE T.COL IN (4,7,8) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СведенияИзРеестраСМИ>'
		
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_4_ДляОрганизацийСМИ>'
	END --IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 12, DEFAULT, DEFAULT) WHERE COL = 5 AND SUMMA <> 0) > 0 
	

----Раздел3_5	
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 13, DEFAULT, DEFAULT) WHERE COL = 3 AND SUMMA <> 0) > 0 -- информ. технол.
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_5_ДляОрганизацийПрименяющихУСН>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, SPACE(5) + 
				'<СуммаДоходаПоСтатье346_15НКвсего>' + CHAR(10) + 
					SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' + CHAR(10) + 
					SPACE(6) + '<СуммаДохода>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДохода>' + CHAR(10) +
				+ SPACE(5) +'</СуммаДоходаПоСтатье346_15НКвсего>'
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 3) T ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, SPACE(5) + 
				'<СуммаДоходаПоСтатье58ИзНих>' + CHAR(10) + 
					SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' + CHAR(10) + 
					SPACE(6) + '<СуммаДохода>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДохода>' + CHAR(10) +
				+ SPACE(5) +'</СуммаДоходаПоСтатье58ИзНих>'
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 2, 3) T ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, SPACE(5) + 
				'<ДоляДоходаПоСтатье58>' + CHAR(10) + 
					SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' + CHAR(10) + 
					SPACE(6) + '<ДоляДохода>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</ДоляДохода>' + CHAR(10) +
				+ SPACE(5) +'</ДоляДоходаПоСтатье58>'
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 3, 3) T ORDER BY T.COL

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_5_ДляОрганизацийПрименяющихУСН>'
	END -- IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 11, DEFAULT, DEFAULT) WHERE COL = 3 AND SUMMA <> 0) > 0
	
	
----Раздел3_6	
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 13, DEFAULT, DEFAULT) WHERE COL in (4,5) AND SUMMA <> 0) > 0 -- информ. технол.
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_6_ДляНекоммерческихОрганизацийПрименяющихУСН>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СуммаДоходовВсего>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' 
					WHEN 4 THEN	SPACE(6) + '<СуммаДоходаПоПредшествующему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>'
					WHEN 5 THEN SPACE(6) + '<СуммаДоходаПоТекущему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 4, DEFAULT) T WHERE T.COL IN (3,4,5) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СуммаДоходовВсего>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СуммаДоходовВвидеЦелевыхПоступлений>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' 
					WHEN 4 THEN	SPACE(6) + '<СуммаДоходаПоПредшествующему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>'
					WHEN 5 THEN SPACE(6) + '<СуммаДоходаПоТекущему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 5, DEFAULT) T WHERE T.COL IN (3,4,5) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СуммаДоходовВвидеЦелевыхПоступлений>'
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СуммаДоходовВвидеГрантов>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' 
					WHEN 4 THEN	SPACE(6) + '<СуммаДоходаПоПредшествующему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>'
					WHEN 5 THEN SPACE(6) + '<СуммаДоходаПоТекущему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 6, DEFAULT) T WHERE T.COL IN (3,4,5) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СуммаДоходовВвидеГрантов>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СуммаДоходовОтОсуществленияОпределенныхВЭД>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' 
					WHEN 4 THEN	SPACE(6) + '<СуммаДоходаПоПредшествующему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>'
					WHEN 5 THEN SPACE(6) + '<СуммаДоходаПоТекущему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 7, DEFAULT) T WHERE T.COL IN (3,4,5) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СуммаДоходовОтОсуществленияОпределенныхВЭД>'
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ДоляДоходов>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' 
					WHEN 4 THEN SPACE(6) + '<СуммаДоходаПоПредшествующему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>'
					WHEN 5 THEN SPACE(6) + '<СуммаДоходаПоТекущему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 8, DEFAULT) T WHERE T.COL IN (3,4,5) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ДоляДоходов>'
	

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_6_ДляНекоммерческихОрганизацийПрименяющихУСН>'
	END


	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '</Раздел3РасчетНаПравоПримененияПониженногоТарифа2014>'

END --	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 10, DEFAULT, 3) WHERE SUMMA <> 0) > 0 -- инвалиды


---РАЗДЕЛ_4 Стр.12
CREATE TABLE #DONACHISL (
	LINK INT,OSN int,CODE_OSN INT, YEAR_D VARCHAR(4), MON int, SUM_STR_14 NUMERIC(18,2), SUM_STR_LIM_14 NUMERIC(18,2), SUM_STR NUMERIC(18,2), SUM_STR_LIM NUMERIC(18,2), SUM_NAK NUMERIC(18,2), SUM_STR_D1 NUMERIC(18,2), SUM_STR_D2 NUMERIC(18,2), SUM_STR_D2_1 NUMERIC(18,2), SUM_MED_STR NUMERIC(18,2))

CREATE TABLE #TAB14 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
INSERT INTO #TAB14 (ROW_CODE, COL, SUMMA, STR_VAL)
SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

INSERT INTO #DONACHISL (OSN,CODE_OSN, YEAR_D, MON,SUM_STR_14, SUM_STR_LIM_14, SUM_STR, SUM_STR_LIM, SUM_NAK ,SUM_STR_D1 , SUM_STR_D2, SUM_STR_D2_1, SUM_MED_STR)
SELECT DISTINCT 
	OSN = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 2 AND T.ROW_CODE = T14.ROW_CODE),
	CODE_OSN = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 3 AND T.ROW_CODE = T14.ROW_CODE),
	YEAR_D = (SELECT TOP 1 STR_VAL FROM #TAB14 T WHERE T.COL = 4 AND T.ROW_CODE = T14.ROW_CODE),
	MON = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 5 AND T.ROW_CODE = T14.ROW_CODE),
	SUM_STR_14 = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 6 AND T.ROW_CODE = T14.ROW_CODE), 
	SUM_STR_LIM_14 = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 7 AND T.ROW_CODE = T14.ROW_CODE),
	SUM_STR = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 8 AND T.ROW_CODE = T14.ROW_CODE),
	SUM_STR_LIM = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 9 AND T.ROW_CODE = T14.ROW_CODE),
	SUM_NAK = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 10 AND T.ROW_CODE = T14.ROW_CODE),
	SUM_STR_D1 = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 11 AND T.ROW_CODE = T14.ROW_CODE),
	SUM_STR_D2 = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 12 AND T.ROW_CODE = T14.ROW_CODE),
	SUM_STR_D2_1 = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 13 AND T.ROW_CODE = T14.ROW_CODE),
	SUM_MED_STR = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 14 AND T.ROW_CODE = T14.ROW_CODE)
FROM
	#TAB14 T14

DROP TABLE #TAB14


--Проставить номера попорядку
DECLARE @NEXT_NUM1 INT
SET @NEXT_NUM1 = 0
UPDATE #DONACHISL SET @NEXT_NUM1 = @NEXT_NUM1 + 1, LINK = @NEXT_NUM1

--IF (SELECT COUNT(*) FROM #DONACHISL) > 0 -- инвалиды
--	OR (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 13, DEFAULT, DEFAULT) WHERE COL = 4 AND SUMMA <> 0) > 0 -- информ. технол.
--BEGIN


	IF (SELECT COUNT(*) FROM #DONACHISL) > 0 -- инвалиды
	BEGIN
	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<Раздел4СуммыДоначисленныхСтраховыхВзносов2014>'

		UNION ALL SELECT @lcFNAME, 
			SPACE(3) + '<СуммаДоначисленныхВзносовЗаПериод>' + CHAR(10) +
				SPACE(4) + '<НомерПП>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(LINK,0)))) + '</НомерПП>' + CHAR(10) +			
				SPACE(4) + '<ОснованиеДляДоначисленияСВ>' + LTRIM(RTRIM(CONVERT(VARCHAR(1),ISNULL(OSN,0)))) + '</ОснованиеДляДоначисленияСВ>' + CHAR(10) +	
				SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(YEAR_D,''))) + '</Год>' + CHAR(10) + 		
				SPACE(4) + '<Месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(2),ISNULL(MON,0)))) + '</Месяц>' + CHAR(10) + 	
				SPACE(4) + '<СуммаДоначисленныхСтраховыхВзносов>' + CHAR(10) +
					SPACE(5) + '<ОПСстраховаяЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR,0)))) + '</ОПСстраховаяЧасть>' + CHAR(10) + 										
					SPACE(5) + '<ОПСстраховаяЧастьСвышеПределаБазы>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_LIM,0)))) + '</ОПСстраховаяЧастьСвышеПределаБазы>' + CHAR(10) + 										
					SPACE(5) + '<ОПСнакопительнаяЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_NAK,0)))) + '</ОПСнакопительнаяЧасть>' + CHAR(10) +
					SPACE(5) + '<ОПСстраховаяЧастьПоДопТар1>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_D1,0)))) + '</ОПСстраховаяЧастьПоДопТар1>' + CHAR(10) +
					SPACE(5) + '<ОПСстраховаяЧастьПоДопТар2>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_D2,0)))) + '</ОПСстраховаяЧастьПоДопТар2>' + CHAR(10) +
					SPACE(5) + '<СтраховыеВзносыОМС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_MED_STR,0)))) + '</СтраховыеВзносыОМС>' + CHAR(10) +	
				SPACE(4) + '</СуммаДоначисленныхСтраховыхВзносов>' + CHAR(10) +
			SPACE(3) + '</СуммаДоначисленныхВзносовЗаПериод>'
		FROM #DONACHISL				


		UNION ALL SELECT @lcFNAME, 
			SPACE(3) + '<ИтогоДоначислено>' + CHAR(10) +
					SPACE(4) + '<ОПСстраховаяЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR,0))))) + '</ОПСстраховаяЧасть>' + CHAR(10) +			
					SPACE(4) + '<ОПСстраховаяЧастьСвышеПределаБазы>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR_LIM,0))))) + '</ОПСстраховаяЧастьСвышеПределаБазы>' + CHAR(10) + 										
					SPACE(4) + '<ОПСнакопительнаяЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_NAK,0))))) + '</ОПСнакопительнаяЧасть>' + CHAR(10) +
					SPACE(4) + '<ОПСстраховаяЧастьПоДопТар1>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR_D1,0))))) + '</ОПСстраховаяЧастьПоДопТар1>' + CHAR(10) +
					SPACE(4) + '<ОПСстраховаяЧастьПоДопТар2>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR_D2,0))))) + '</ОПСстраховаяЧастьПоДопТар2>' + CHAR(10) +
					SPACE(4) + '<СтраховыеВзносыОМС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_MED_STR,0))))) + '</СтраховыеВзносыОМС>' + CHAR(10) +
			SPACE(3) + '</ИтогоДоначислено>' 
		FROM #DONACHISL	

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '</Раздел4СуммыДоначисленныхСтраховыхВзносов2014>'	
	END

--end



---РАЗДЕЛ_5 Стр.13_1
CREATE TABLE #STUD (
	LINK INT, FIO VARCHAR(254), FIO2 VARCHAR(254), NUM_SPR1 VARCHAR(30), DATE_SPR1 VARCHAR(10),NUM_SPR2 VARCHAR(30), DATE_SPR2 VARCHAR(10), 
	SM_ALL 	NUMERIC(18,2), SM1 NUMERIC(18,2), SM2 NUMERIC(18,2), SM3 NUMERIC(18,2) )

CREATE TABLE #TAB15 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
INSERT INTO #TAB15 (ROW_CODE, COL, SUMMA, STR_VAL)
SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

INSERT INTO #STUD (FIO2, NUM_SPR1, DATE_SPR1,NUM_SPR2, DATE_SPR2, 
	SM_ALL, SM1, SM2, SM3 )
SELECT DISTINCT 
	FIO2 = (SELECT TOP 1 REPLACE(STR_VAL,SPACE(1), ', ') FROM #TAB15 T WHERE T.COL = 2 AND T.ROW_CODE = T15.ROW_CODE),
	NUM_SPR1 = (SELECT TOP 1 LEFT(LTRIM(RTRIM(dbo.SA_GET_WORD_NUM(STR_VAL,1,' '))),30) FROM #TAB15 T WHERE T.COL = 3 AND T.ROW_CODE = T15.ROW_CODE),
	DATE_SPR1 = (SELECT TOP 1 LEFT(LTRIM(RTRIM(dbo.SA_GET_WORD_NUM(STR_VAL,2,' '))),10) FROM #TAB15 T WHERE T.COL = 3 AND T.ROW_CODE = T15.ROW_CODE),
	NUM_SPR2 = (SELECT TOP 1 LEFT(LTRIM(RTRIM(dbo.SA_GET_WORD_NUM(STR_VAL,1,' '))),30) FROM #TAB15 T WHERE T.COL = 4 AND T.ROW_CODE = T15.ROW_CODE),
	DATE_SPR2 = (SELECT TOP 1 LEFT(LTRIM(RTRIM(dbo.SA_GET_WORD_NUM(STR_VAL,2,' '))),10) FROM #TAB15 T WHERE T.COL = 4 AND T.ROW_CODE = T15.ROW_CODE),
	SM_ALL = (SELECT TOP 1 SUMMA FROM #TAB15 T WHERE T.COL = 5 AND T.ROW_CODE = T15.ROW_CODE),
	SM1 = (SELECT TOP 1 SUMMA FROM #TAB15 T WHERE T.COL = 6 AND T.ROW_CODE = T15.ROW_CODE),
	SM2 = (SELECT TOP 1 SUMMA FROM #TAB15 T WHERE T.COL = 7 AND T.ROW_CODE = T15.ROW_CODE),
	SM3 = (SELECT TOP 1 SUMMA FROM #TAB15 T WHERE T.COL = 8 AND T.ROW_CODE = T15.ROW_CODE)
FROM
	#TAB15 T15

DROP TABLE #TAB15

--Проставить номера попорядку
DECLARE @NEXT_NUM2 INT
SET @NEXT_NUM2 = 0
UPDATE #STUD SET @NEXT_NUM2 = @NEXT_NUM2 + 1, LINK = @NEXT_NUM2

--количество обучающихся
DECLARE @COUNT_STUD INT
set @COUNT_STUD = (select count(*) from #STUD ) 


--IF (SELECT COUNT(*) FROM #STUD) > 0 -- студенты
--	OR (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 15, DEFAULT, DEFAULT) WHERE COL = 5 AND SUMMA <> 0) > 0 -- оплата студентам
--BEGIN

IF (SELECT COUNT(*) FROM #STUD) > 0 -- студенты
BEGIN
	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<Раздел5СведенияОВыплатахВпользуОбучающихся2014>'
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<КоличествоОбучающихся>' + LTRIM(RTRIM(CONVERT(VARCHAR(5),ISNULL(@COUNT_STUD,0)))) + '</КоличествоОбучающихся>' 			
		UNION ALL SELECT @lcFNAME, 
			SPACE(4) + '<СведенияОбОбучающемся>' + CHAR(10) +		
				SPACE(5) + '<НомерПП>' + LTRIM(RTRIM(CONVERT(VARCHAR(5),ISNULL(link,0)))) + '</НомерПП>' + CHAR(10) + 		
				SPACE(5) + '<ФИО>' + CHAR(10) + 
					SPACE(6) + '<Фамилия>' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,1,','),'')))) + '</Фамилия>' + CHAR(10) + 		
					SPACE(6) + '<Имя>' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,2,','),'')))) + '</Имя>' + CHAR(10) + 		
					SPACE(6) + '<Отчество>' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,3,','),'')))) + '</Отчество>' + CHAR(10) + 										
				SPACE(5) + '</ФИО>' + CHAR(10) + 
				SPACE(5) + '<НомерСправкиОчленствеВстудОтряде>' + LTRIM(RTRIM(ISNULL(NUM_SPR1,''))) + '</НомерСправкиОчленствеВстудОтряде>' + CHAR(10) + 										
				SPACE(5) + '<ДатаВыдачиСправкиОчленствеВстудОтряде>' + LTRIM(RTRIM(ISNULL(DATE_SPR1,''))) + '</ДатаВыдачиСправкиОчленствеВстудОтряде>' + CHAR(10) + 	
				SPACE(5) + '<НомерСправкиОбОчномОбучении>' + LTRIM(RTRIM(ISNULL(NUM_SPR2,''))) + '</НомерСправкиОбОчномОбучении>' + CHAR(10) + 										
				SPACE(5) + '<ДатаВыдачиСправкиОбОчномОбучении>' + LTRIM(RTRIM(ISNULL(DATE_SPR2,''))) + '</ДатаВыдачиСправкиОбОчномОбучении>' + CHAR(10) + 										
				SPACE(5) + '<СуммыВыплатИвознаграждений>' + CHAR(10) + 
					SPACE(6) + '<СуммаВсегоСначалаРасчетногоПериода>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM_ALL,0)))) + '</СуммаВсегоСначалаРасчетногоПериода>' + CHAR(10) +
					SPACE(6) + '<СуммаПоследние1месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM1,0)))) + '</СуммаПоследние1месяц>' + CHAR(10) +	
					SPACE(6) + '<СуммаПоследние2месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM2,0)))) + '</СуммаПоследние2месяц>' + CHAR(10) +	
					SPACE(6) + '<СуммаПоследние3месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM3,0)))) + '</СуммаПоследние3месяц>' + CHAR(10) +	
				SPACE(5) + '</СуммыВыплатИвознаграждений>' + CHAR(10) + 
			SPACE(4) + '</СведенияОбОбучающемся>'
		FROM #STUD				


		UNION ALL SELECT @lcFNAME, 
			SPACE(4) + '<ИтогоВыплат>' + CHAR(10) +
					SPACE(5) + '<СуммаВсегоСначалаРасчетногоПериода>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SM_ALL,0))))) + '</СуммаВсегоСначалаРасчетногоПериода>' + CHAR(10) +			
					SPACE(5) + '<СуммаПоследние1месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SM1,0))))) + '</СуммаПоследние1месяц>' + CHAR(10) +
					SPACE(5) + '<СуммаПоследние2месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SM2,0))))) + '</СуммаПоследние2месяц>' + CHAR(10) +
					SPACE(5) + '<СуммаПоследние3месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SM3,0))))) + '</СуммаПоследние3месяц>' + CHAR(10) +
			SPACE(4) + '</ИтогоВыплат>' 
		FROM #STUD	

	if (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 16, 1, DEFAULT) WHERE COL = 3 and str_VAL <> '' ) > 0 
	begin
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<СведенияИзРеестраМДОО>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 2 THEN SPACE(5) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
								SPACE(5) + '<РеквизитыЗаписиВреестре>'
						WHEN 3 THEN SPACE(6) + '<ДатаЗаписиВреестре>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</ДатаЗаписиВреестре>'
						WHEN 4 THEN	SPACE(6) + '<НомерЗаписиВреестре>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</НомерЗаписиВреестре>' + CHAR(10) +	
								SPACE(5) + '</РеквизитыЗаписиВреестре>'
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 16, 1, DEFAULT) T WHERE T.COL IN (2,3,4) ORDER BY T.COL
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</СведенияИзРеестраМДОО>'
	end

	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '</Раздел5СведенияОВыплатахВпользуОбучающихся2014>'	
END

--end

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) 
SELECT @lcFNAME, 
	SPACE(3) + '<ЛицоПодтверждающееСведения>1</ЛицоПодтверждающееСведения>' + CHAR(10) +
	SPACE(3) + '<ФИОлицаПодтверждающегоСведения>' + CHAR(10) +
		SPACE(4) + '<Фамилия>' + UPPER(LTRIM(RTRIM(ISNULL(O.FM,'')))) + '</Фамилия>' + CHAR(10) +
		SPACE(4) + '<Имя>' + UPPER(LTRIM(RTRIM(ISNULL(O.IM,'')))) + '</Имя>' + CHAR(10) +
		SPACE(4) + '<Отчество>' + UPPER(LTRIM(RTRIM(ISNULL(O.OT,'')))) + '</Отчество>' + CHAR(10) +
	SPACE(3) + '</ФИОлицаПодтверждающегоСведения>' + CHAR(10) +
	SPACE(3) + '<НаименованиеОрганизацииПредставителя>' + UPPER(LTRIM(RTRIM(ISNULL(d.FULL_NAME,'')))) + '</НаименованиеОрганизацииПредставителя>' + CHAR(10) +
	SPACE(3) + '<ДокументПодтверждающийПолномочияПредставителя>' + CHAR(10) +
		SPACE(4) + '<НаименованиеУдостоверяющего>' + UPPER(LTRIM(RTRIM(ISNULL(F.NAME,'')))) + '</НаименованиеУдостоверяющего>' + CHAR(10) +
		SPACE(4) + '<СерияРимскиеЦифры>' + case when f.code='21' then substring(p.doc_num,1,2) else ' ' end + '</СерияРимскиеЦифры>' + CHAR(10) +
		SPACE(4) + '<СерияРусскиеБуквы>' + case when f.code='21' then substring(p.doc_num,4,2) else ' ' end + '</СерияРусскиеБуквы>' + CHAR(10) +
		SPACE(4) + '<НомерУдостоверяющего>' + LTRIM(RTRIM(case when f.code='21' then substring(p.doc_num,7,7) else ' ' end)) + '</НомерУдостоверяющего>' + CHAR(10) +
		SPACE(4) + '<ДатаВыдачи>' + LTRIM(RTRIM(ISNULL(convert(varchar(10),p.doc_date,104),''))) + '</ДатаВыдачи>' + CHAR(10) +
		SPACE(4) + '<КемВыдан>' + UPPER(LTRIM(RTRIM(ISNULL(p.DOC_WHOM,'')))) + '</КемВыдан>' + CHAR(10) +
	SPACE(3) + '</ДокументПодтверждающийПолномочияПредставителя>' 
FROM dbo.GetOtvFaceData(@LINK_DEP, 'Руководитель') O
inner join EMPL e on e.link = o.link_empl
inner join PERSON p on p.link = e.pers_link
inner join FACE_DOCUMENT f on f.link = p.doc_link
inner join DICTIONARY_DEPARTMENT d on d.link = @LINK_DEP


INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) 
SELECT @lcFNAME, SPACE(3) + '<ДатаЗаполнения>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),@modify_date,104),''))) + '</ДатаЗаполнения>'

--Заверешение
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(2) + '</РАСЧЕТ_ПО_СТРАХОВЫМ_ВЗНОСАМ_НА_ОПС_И_ОМС_ПЛАТЕЛЬЩИКАМИ_ПРОИЗВОДЯЩИМИ_ВЫПЛАТЫ_ФЛ_2014>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(1) + '</ПачкаВходящихДокументов>'
	UNION ALL SELECT @lcFNAME, SPACE(0) + '</ФайлПФР>'	


/*-----------------------------------------------------------------------------------------------*/


--Раздел_6 


--ОПИСЬ

CREATE TABLE #OPIS (
	LINK INT, [TYPE] INT, NOM_PP INT, NOM_PACH VARCHAR(10), SUM_BASE NUMERIC(18,2), SUM_STR NUMERIC(18,2), PERS_CNT NUMERIC(5), DATE_DOC VARCHAR(10), 
	PER VARCHAR(1), YEAR_BEGIN VARCHAR(4), PER_EDT VARCHAR(1), YEAR_EDT VARCHAR(4), F_NAME varchar(100), link_doc int)

CREATE TABLE #TAB16 (ROW_CODE VARCHAR(10), COL INT, SUMMA NUMERIC(18), SUMMA2 NUMERIC(18,2), STR_VAL VARCHAR(254))
INSERT INTO #TAB16 (ROW_CODE, COL, SUMMA, SUMMA2, STR_VAL)
SELECT ROW_CODE, COL, SUMMA, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, DEFAULT, DEFAULT) T WHERE T.COL >= 3 ORDER BY T.COL

CREATE TABLE #TAB17 (ROW_CODE VARCHAR(10), COL INT, SUMMA NUMERIC(18), SUMMA2 NUMERIC(18,2), STR_VAL VARCHAR(254))
INSERT INTO #TAB17 (ROW_CODE, COL, SUMMA,SUMMA2, STR_VAL)
SELECT ROW_CODE, COL, SUMMA, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, DEFAULT, DEFAULT) T WHERE T.COL >= 3 ORDER BY T.COL


INSERT INTO #OPIS ([TYPE], NOM_PACH, SUM_BASE, SUM_STR, PERS_CNT, DATE_DOC,	PER, YEAR_BEGIN,F_NAME, link_doc)
SELECT DISTINCT 
	[TYPE] = (SELECT TOP 1 summa FROM #TAB16 T WHERE T.COL = 8 AND T.ROW_CODE = T16.ROW_CODE),
	NOM_PACH = (SELECT TOP 1 LTRIM(RTRIM(ROW_CODE)) FROM #TAB16 T WHERE T.COL = 3 AND T.ROW_CODE = T16.ROW_CODE),
	SUM_BASE = (SELECT TOP 1 SUMMA2 FROM #TAB16 T WHERE T.COL = 3 AND T.ROW_CODE = T16.ROW_CODE),
	SUM_STR = (SELECT TOP 1 SUMMA2 FROM #TAB16 T WHERE T.COL = 4 AND T.ROW_CODE = T16.ROW_CODE),
	PERS_CNT = (SELECT TOP 1 SUMMA FROM #TAB16 T WHERE T.COL = 5 AND T.ROW_CODE = T16.ROW_CODE),
	DATE_DOC = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB16 T WHERE T.COL = 7 AND T.ROW_CODE = T16.ROW_CODE),
	PER = (SELECT TOP 1 LTRIM(RTRIM(str(SUMMA))) FROM #TAB16 T WHERE T.COL = 9 AND T.ROW_CODE = T16.ROW_CODE),
	YEAR_BEGIN = (SELECT TOP 1 LTRIM(RTRIM(str(SUMMA))) FROM #TAB16 T WHERE T.COL = 10 AND T.ROW_CODE = T16.ROW_CODE),
	F_NAME = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB16 T WHERE T.COL = 6 AND T.ROW_CODE = T16.ROW_CODE),
	LINK_DOC = (SELECT TOP 1 SUMMA FROM #TAB16 T WHERE T.COL = 11 AND T.ROW_CODE = T16.ROW_CODE)
FROM
	#TAB16 T16

INSERT INTO #OPIS ([TYPE], NOM_PACH, SUM_BASE, SUM_STR, PERS_CNT, DATE_DOC,	PER, YEAR_BEGIN, PER_EDT, YEAR_EDT,F_NAME, link_doc)
SELECT DISTINCT 
	[TYPE] = (SELECT TOP 1 summa FROM #TAB17 T WHERE T.COL = 11 AND T.ROW_CODE = T17.ROW_CODE),
	NOM_PACH = (SELECT TOP 1 LTRIM(RTRIM(ROW_CODE)) FROM #TAB17 T WHERE T.COL = 3 AND T.ROW_CODE = T17.ROW_CODE),
	SUM_BASE = (SELECT TOP 1 SUMMA2 FROM #TAB17 T WHERE T.COL = 14 AND T.ROW_CODE = T17.ROW_CODE),
	SUM_STR = (SELECT TOP 1 SUMMA2 FROM #TAB17 T WHERE T.COL = 15 AND T.ROW_CODE = T17.ROW_CODE),
	PERS_CNT = (SELECT TOP 1 SUMMA FROM #TAB17 T WHERE T.COL = 8 AND T.ROW_CODE = T17.ROW_CODE),
	DATE_DOC = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB17 T WHERE T.COL = 10 AND T.ROW_CODE = T17.ROW_CODE),
	PER = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB17 T WHERE T.COL = 12 AND T.ROW_CODE = T17.ROW_CODE),
	YEAR_BEGIN = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB17 T WHERE T.COL = 13 AND T.ROW_CODE = T17.ROW_CODE),
	PER_EDT = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB17 T WHERE T.COL = 3 AND T.ROW_CODE = T17.ROW_CODE),
	YEAR_EDT = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB17 T WHERE T.COL = 4 AND T.ROW_CODE = T17.ROW_CODE),
	F_NAME = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB17 T WHERE T.COL = 9 AND T.ROW_CODE = T17.ROW_CODE),
	LINK_DOC = (SELECT TOP 1 SUMMA FROM #TAB17 T WHERE T.COL = 16 AND T.ROW_CODE = T17.ROW_CODE)
FROM
	#TAB17 T17	



DROP TABLE #TAB16
DROP TABLE #TAB17


--Проставить номера попорядку
DECLARE @NEXT_NUM3 INT
SET @NEXT_NUM3 = 0
UPDATE #OPIS SET @NEXT_NUM3 = @NEXT_NUM3 + 1, LINK = @NEXT_NUM3

DECLARE @NEXT_NUM4 INT
SET @NEXT_NUM4 = 0
UPDATE #OPIS SET @NEXT_NUM4 = @NEXT_NUM4 + 1, NOM_PP = @NEXT_NUM4
WHERE TYPE = 1


SET @NEXT_NUM4 = 0
UPDATE #OPIS SET @NEXT_NUM4 = @NEXT_NUM4 + 1, NOM_PP = @NEXT_NUM4
WHERE TYPE = 2


---------------------------------------------------------------
----------------------------------------------------------------
DECLARE @Cur3 CURSOR, @Cur4 CURSOR, @LINK_OP INT, @NGROUP int /*Номер пачки*/, @lcF_NAME varchar(254) /*наименование файла*/,
	@NOM_PP INT, @TYP_D varchar(20), @DATE_DOC VARCHAR(10),@SUM_BASE NUMERIC(18,2), @SUM_STR NUMERIC(18,2), @PERS_CNT NUMERIC(5),
	@PER VARCHAR(1), @YEAR_BEGIN VARCHAR(4), @PER_EDT VARCHAR(1), @YEAR_EDT VARCHAR(4)


	CREATE TABLE #TAB61 (LINK INT , FM VARCHAR(100), IM VARCHAR(100), OT VARCHAR(100), SNILS VARCHAR(14), CODE VARCHAR(14), SNILS1 VARCHAR(14), [TYPE] TINYINT , NGROUP VARCHAR(10), FNAME varchar(80), doc_date varchar(10))
	INSERT INTO #TAB61 (CODE, SNILS, FM, IM, OT, SNILS1, [TYPE], NGROUP, FNAME, doc_date)
	exec dbo.RSA_RSV_1_PERS_UCH_SZV @Begin_Date , @END_Date , @LINK_DEP, 0 , @Link


	SET @NEXT_NUM3 = 0
	UPDATE #TAB61 SET @NEXT_NUM3 = @NEXT_NUM3 + 1, LINK = @NEXT_NUM3

	CREATE TABLE #TAB64 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18), SUMMA2 NUMERIC(18,2), STR_VAL VARCHAR(254))
	INSERT INTO #TAB64 (ROW_CODE, COL, SUMMA,SUMMA2, STR_VAL)
	SELECT ROW_CODE, COL, SUMMA, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 18, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

	CREATE TABLE #PACHKA_64 (
								LINK INT, [TYPE] varchar(15), NOM_PP INT, SNILS VARCHAR(14), CODE_STR int, CODE_KAT varchar(5), INSUR NUMERIC(18,2), B_BEF NUMERIC(18,2), GB_BEF NUMERIC(18,2),B_AFT NUMERIC(18,2),
								PER VARCHAR(1), YEAR_BEGIN VARCHAR(4), PER_EDT VARCHAR(1), YEAR_EDT VARCHAR(4), FM varchar(100), IM varchar(100), OT varchar(100),
								k_PER_EDT1 VARCHAR(1), k_YEAR_EDT1 VARCHAR(4), k_INSUR1 NUMERIC(18,2), k_INSUR_1 NUMERIC(18,2), k_GAIN1 NUMERIC(18,2),
								k_PER_EDT2 VARCHAR(1), k_YEAR_EDT2 VARCHAR(4), k_INSUR2 NUMERIC(18,2), k_INSUR_2 NUMERIC(18,2), k_GAIN2 NUMERIC(18,2),
								k_PER_EDT3 VARCHAR(1), k_YEAR_EDT3 VARCHAR(4), k_INSUR3 NUMERIC(18,2), k_INSUR_3 NUMERIC(18,2), k_GAIN3 NUMERIC(18,2),
								k_PER_EDT4 VARCHAR(1), k_YEAR_EDT4 VARCHAR(4), k_INSUR4 NUMERIC(18,2), k_INSUR_4 NUMERIC(18,2), k_GAIN4 NUMERIC(18,2),
								k_PER_EDT5 VARCHAR(1), k_YEAR_EDT5 VARCHAR(4), k_INSUR5 NUMERIC(18,2), k_INSUR_5 NUMERIC(18,2), k_GAIN5 NUMERIC(18,2),SUM_VZNOS NUMERIC(18,2))
	
	INSERT INTO #PACHKA_64 (/*LINK,*/ [TYPE], NOM_PP,SNILS,CODE_STR,CODE_KAT,INSUR,B_BEF, GB_BEF, B_AFT,
							PER,YEAR_BEGIN,PER_EDT,YEAR_EDT,FM,IM,OT,
							k_PER_EDT1,k_YEAR_EDT1,k_INSUR1,k_INSUR_1,k_GAIN1,k_PER_EDT2,k_YEAR_EDT2,k_INSUR2,k_INSUR_2,k_GAIN2,
							k_PER_EDT3,k_YEAR_EDT3,k_INSUR3,k_INSUR_3,k_GAIN3,k_PER_EDT4,k_YEAR_EDT4,k_INSUR4,k_INSUR_4,k_GAIN4,
							k_PER_EDT5,k_YEAR_EDT5,k_INSUR5,k_INSUR_5,k_GAIN5,SUM_VZNOS)
	SELECT 
				---LINK = dEnse_RANK() OVER (ORDER BY  [type],snils ),
				[TYPE],
				NOM_PP = ROW_NUMBER() OVER (PARTITION BY SNILS, [TYPE] ORDER BY CODE_STR),
				SNILS,CODE_STR,CODE_KAT,INSUR,B_BEF, GB_BEF, B_AFT,
							PER,YEAR_BEGIN,PER_EDT,YEAR_EDT,FM,IM,OT,
							k_PER_EDT1,k_YEAR_EDT1,k_INSUR1,k_INSUR_1,k_GAIN1,k_PER_EDT2,k_YEAR_EDT2,k_INSUR2,k_INSUR_2,k_GAIN2,
							k_PER_EDT3,k_YEAR_EDT3,k_INSUR3,k_INSUR_3,k_GAIN3,k_PER_EDT4,k_YEAR_EDT4,k_INSUR4,k_INSUR_4,k_GAIN4,
							k_PER_EDT5,k_YEAR_EDT5,k_INSUR5,k_INSUR_5,k_GAIN5,SUM_VZNOS

		FROM
	(
	SELECT DISTINCT 
		[TYPE] = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 12 AND T.ROW_CODE = T64.ROW_CODE),
		SNILS = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 2 AND T.ROW_CODE = T64.ROW_CODE),
		CODE_STR = convert(int, (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 4 AND T.ROW_CODE = T64.ROW_CODE)),
		CODE_KAT = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 5 AND T.ROW_CODE = T64.ROW_CODE),
		INSUR = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 6 AND T.ROW_CODE = T64.ROW_CODE),
		B_BEF = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 7 AND T.ROW_CODE = T64.ROW_CODE ),
		GB_BEF = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 8 AND T.ROW_CODE = T64.ROW_CODE ),
		B_AFT = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 9 AND T.ROW_CODE = T64.ROW_CODE ),
		PER = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL))FROM #TAB64 T WHERE T.COL = 10 AND T.ROW_CODE = T64.ROW_CODE),
		YEAR_BEGIN = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 11 AND T.ROW_CODE = T64.ROW_CODE),
		PER_EDT = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 13 AND T.ROW_CODE = T64.ROW_CODE),
		YEAR_EDT = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 14 AND T.ROW_CODE = T64.ROW_CODE),
		FM= (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 16 AND T.ROW_CODE = T64.ROW_CODE),
		IM= (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 17 AND T.ROW_CODE = T64.ROW_CODE),
		OT= (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 18 AND T.ROW_CODE = T64.ROW_CODE),
		k_PER_EDT1 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 19 AND T.ROW_CODE = T64.ROW_CODE ),
		k_YEAR_EDT1 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 20 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR1 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 21 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR_1 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 22 AND T.ROW_CODE = T64.ROW_CODE ),
		k_GAIN1 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 23 AND T.ROW_CODE = T64.ROW_CODE),
		
		k_PER_EDT2= (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 24 AND T.ROW_CODE = T64.ROW_CODE ),
		k_YEAR_EDT2 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA)))FROM #TAB64 T WHERE T.COL = 25 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR2 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 26 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR_2 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 27 AND T.ROW_CODE = T64.ROW_CODE ),
		k_GAIN2 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 28 AND T.ROW_CODE = T64.ROW_CODE),
		k_PER_EDT3 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 29 AND T.ROW_CODE = T64.ROW_CODE ),
		k_YEAR_EDT3 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 30 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR3 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 31 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR_3 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 32 AND T.ROW_CODE = T64.ROW_CODE ),
		k_GAIN3 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 33 AND T.ROW_CODE = T64.ROW_CODE),
		k_PER_EDT4 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 34 AND T.ROW_CODE = T64.ROW_CODE ),
		k_YEAR_EDT4 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 35 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR4 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 36 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR_4 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 37 AND T.ROW_CODE = T64.ROW_CODE ),
		k_GAIN4 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 38 AND T.ROW_CODE = T64.ROW_CODE),
		k_PER_EDT5 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 39 AND T.ROW_CODE = T64.ROW_CODE ),
		k_YEAR_EDT5 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 40 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR5 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 41 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR_5 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 42 AND T.ROW_CODE = T64.ROW_CODE ),
		k_GAIN5 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 43 AND T.ROW_CODE = T64.ROW_CODE),
		SUM_VZNOS = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 44 AND T.ROW_CODE = T64.ROW_CODE)
		
	FROM
	#TAB64 T64	
		) T	


	SET @NEXT_NUM3 = 0
	UPDATE  p  SET  LINK = (select top 1 link from #TAB61 where ltrim(rtrim(SNILS)) = ltrim(rtrim(p.SNILS)) 
																						 and  ltrim(rtrim(FM)) = ltrim(rtrim(p.FM)) 
																						 and ltrim(rtrim(IM)) = ltrim(rtrim(p.IM))	 and ltrim(rtrim(OT)) = ltrim(rtrim(p.OT))
																						 and [type] = (case p.[type] when 'ИСХОДНАЯ' then 1 when 'КОРРЕКТИРУЮЩАЯ' then 2 else 3 end))
	FROM #PACHKA_64 p   

--DECLARE @LINK_OLD INT , @LINK_T int
--SET @LINK_OLD = 0
--SET @NEXT_NUM3 = 0
--SET @Cur3 = CURSOR FORWARD_ONLY
--FOR 
--select 	
--	LINK
--from #PACHKA_64 order by LINK


--OPEN @Cur3
--FETCH NEXT FROM @Cur3 INTO @LINK_T

--WHILE (@@fetch_status <> -1)
--BEGIN
	
--	IF (@@fetch_status <> -2)
--	BEGIN	
--		IF @LINK_OLD <> @LINK_T
--		BEGIN 
--			UPDATE #PACHKA_64 SET @NEXT_NUM3 = @NEXT_NUM3 + 1, NOM_PP = @NEXT_NUM3
--			WHERE link = @LINK_T	
--		END
--		SET @LINK_OLD = @LINK_T
--		SET @NEXT_NUM3 = 0
--	END
--	FETCH NEXT FROM @Cur3 INTO @LINK_T
--END

--CLOSE @Cur3
--DEALLOCATE @Cur3		


DROP TABLE #TAB64


	CREATE TABLE #TAB66 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18), SUMMA2 NUMERIC(18,2), STR_VAL VARCHAR(254))
	INSERT INTO #TAB66 (ROW_CODE, COL, SUMMA,SUMMA2, STR_VAL)
	SELECT ROW_CODE, COL, SUMMA, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 19, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL
	

	CREATE TABLE #TAB67 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18), SUMMA2 NUMERIC(18,2), STR_VAL VARCHAR(254))
	INSERT INTO #TAB67 (ROW_CODE, COL, SUMMA,SUMMA2, STR_VAL)
	SELECT ROW_CODE, COL, SUMMA, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 20, DEFAULT, DEFAULT) T  ORDER BY T.COL	

	CREATE TABLE #PACHKA_67 (
								LINK INT, [TYPE] INT , NOM_PP INT, SNILS VARCHAR(14), CODE_STR INT, CODE_SPO varchar(5), INC_T1M NUMERIC(18,2), INC_T2M NUMERIC(18,2), 
								DATE_BEGIN1 varchar(10),DATE_END1 VARCHAR(10),TU_CODE1 VARCHAR(10), OS_CODE1 VARCHAR(20), EX_CODE1 VARCHAR(10), f_is_dop1 VARCHAR(100), P_CODE1 varchar(10), f_ud_dop1 varchar(100),
								DATE_BEGIN2 varchar(10),DATE_END2 VARCHAR(10),TU_CODE2 VARCHAR(10), OS_CODE2 VARCHAR(20), EX_CODE2 VARCHAR(10), f_is_dop2 VARCHAR(100), P_CODE2 varchar(10), f_ud_dop2 varchar(100),
								DATE_BEGIN3 varchar(10),DATE_END3 VARCHAR(10),TU_CODE3 VARCHAR(10), OS_CODE3 VARCHAR(20), EX_CODE3 VARCHAR(10), f_is_dop3 VARCHAR(100), P_CODE3 varchar(10), f_ud_dop3 varchar(100),
								DATE_BEGIN4 varchar(10),DATE_END4 VARCHAR(10),TU_CODE4 VARCHAR(10), OS_CODE4 VARCHAR(20), EX_CODE4 VARCHAR(10), f_is_dop4 VARCHAR(100), P_CODE4 varchar(10), f_ud_dop4 varchar(100)
							)
	
	INSERT INTO #PACHKA_67 (LINK, [TYPE], NOM_PP,SNILS,CODE_STR,CODE_SPO,INC_T1M,INC_T2M,
								DATE_BEGIN1,DATE_END1,TU_CODE1, OS_CODE1, EX_CODE1, f_is_dop1, P_CODE1, f_ud_dop1,
								DATE_BEGIN2,DATE_END2,TU_CODE2, OS_CODE2, EX_CODE2, f_is_dop2, P_CODE2, f_ud_dop2,
								DATE_BEGIN3,DATE_END3,TU_CODE3, OS_CODE3, EX_CODE3, f_is_dop3, P_CODE3, f_ud_dop3,
								DATE_BEGIN4,DATE_END4,TU_CODE4, OS_CODE4, EX_CODE4, f_is_dop4, P_CODE4, f_ud_dop4)
	SELECT 
				LINK = dEnse_RANK() OVER (ORDER BY  [type],snils ),
				[TYPE],
				NOM_PP = ROW_NUMBER() OVER (PARTITION BY SNILS, [TYPE] ORDER BY CODE_STR),
								SNILS,CODE_STR,CODE_SPO,INC_T1M,INC_T2M,
								DATE_BEGIN1,DATE_END1,TU_CODE1, OS_CODE1, EX_CODE1, f_is_dop1, P_CODE1, f_ud_dop1,
								DATE_BEGIN2,DATE_END2,TU_CODE2, OS_CODE2, EX_CODE2, f_is_dop2, P_CODE2, f_ud_dop2,
								DATE_BEGIN3,DATE_END3,TU_CODE3, OS_CODE3, EX_CODE3, f_is_dop3, P_CODE3, f_ud_dop3,
								DATE_BEGIN4,DATE_END4,TU_CODE4, OS_CODE4, EX_CODE4, f_is_dop4, P_CODE4, f_ud_dop4		
	FROM
	(
		SELECT DISTINCT 
			[TYPE] = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB67 T WHERE T.COL = 9 AND T.ROW_CODE = T67.ROW_CODE),
			SNILS = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 7 AND T.ROW_CODE = T67.ROW_CODE),
			CODE_STR = CONVERT( int ,(SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 3 AND T.ROW_CODE = T67.ROW_CODE)),
			CODE_SPO = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 4 AND T.ROW_CODE = T67.ROW_CODE),
			INC_T1M = (SELECT TOP 1 SUMMA2 FROM #TAB67 T WHERE T.COL = 5 AND T.ROW_CODE = T67.ROW_CODE),
			INC_T2M = (SELECT TOP 1 SUMMA2 FROM #TAB67 T WHERE T.COL = 6 AND T.ROW_CODE = T67.ROW_CODE ),

			DATE_BEGIN1 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 10 AND T.ROW_CODE = T67.ROW_CODE ),
			DATE_END1 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 11 AND T.ROW_CODE = T67.ROW_CODE),
			TU_CODE1 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 12 AND T.ROW_CODE = T67.ROW_CODE),
			OS_CODE1 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 13 AND T.ROW_CODE = T67.ROW_CODE ),
			EX_CODE1 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 14 AND T.ROW_CODE = T67.ROW_CODE),
			f_is_dop1 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 15 AND T.ROW_CODE = T67.ROW_CODE ),
			P_CODE1 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 16 AND T.ROW_CODE = T67.ROW_CODE),
			f_ud_dop1 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 17 AND T.ROW_CODE = T67.ROW_CODE),
			
			DATE_BEGIN2 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 18 AND T.ROW_CODE = T67.ROW_CODE ),
			DATE_END2 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 19 AND T.ROW_CODE = T67.ROW_CODE),
			TU_CODE2 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 20 AND T.ROW_CODE = T67.ROW_CODE),
			OS_CODE2 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 21 AND T.ROW_CODE = T67.ROW_CODE ),
			EX_CODE2 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 22 AND T.ROW_CODE = T67.ROW_CODE),
			f_is_dop2 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 23 AND T.ROW_CODE = T67.ROW_CODE ),
			P_CODE2 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 24 AND T.ROW_CODE = T67.ROW_CODE),
			f_ud_dop2 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 25 AND T.ROW_CODE = T67.ROW_CODE),
			
			DATE_BEGIN3 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 26 AND T.ROW_CODE = T67.ROW_CODE ),
			DATE_END3 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 27 AND T.ROW_CODE = T67.ROW_CODE),
			TU_CODE3 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 28 AND T.ROW_CODE = T67.ROW_CODE),
			OS_CODE3 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 29 AND T.ROW_CODE = T67.ROW_CODE ),
			EX_CODE3 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 30 AND T.ROW_CODE = T67.ROW_CODE),
			f_is_dop3 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 31 AND T.ROW_CODE = T67.ROW_CODE ),
			P_CODE3 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 32 AND T.ROW_CODE = T67.ROW_CODE),
			f_ud_dop3 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 33 AND T.ROW_CODE = T67.ROW_CODE),
			
			DATE_BEGIN4 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 34 AND T.ROW_CODE = T67.ROW_CODE ),
			DATE_END4 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 35 AND T.ROW_CODE = T67.ROW_CODE),
			TU_CODE4 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 36 AND T.ROW_CODE = T67.ROW_CODE),
			OS_CODE4 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 37 AND T.ROW_CODE = T67.ROW_CODE ),
			EX_CODE4 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 38 AND T.ROW_CODE = T67.ROW_CODE),
			f_is_dop4 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 39 AND T.ROW_CODE = T67.ROW_CODE ),
			P_CODE4 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 40 AND T.ROW_CODE = T67.ROW_CODE),
			f_ud_dop4 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 41 AND T.ROW_CODE = T67.ROW_CODE)
		FROM
		#TAB67 T67	
	) T	

	--SET @NEXT_NUM3 = 0
	--UPDATE  p  SET  LINK = (select top 1 link from #TAB61 where ltrim(rtrim(SNILS)) = ltrim(rtrim(p.SNILS)) 
	--														 and [type] = p.[type])
	--FROM #PACHKA_67 p   


----------------------

-------------------------
--exec SA_RSV1_EXPORT_0700_2014 41964
--exec SA_RSV1_EXPORT_0700_2014 216

DROP TABLE #TAB67


	CREATE TABLE #TAB68 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18), SUMMA2 NUMERIC(18,2), STR_VAL VARCHAR(254))
	INSERT INTO #TAB68	(ROW_CODE, COL, SUMMA,SUMMA2, STR_VAL)
	SELECT ROW_CODE, COL, SUMMA, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 21, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL	
	


	SELECT T1.LINK , t1.NGROUP , T1.FNAME, T1.DOC_DATE, t2.[TYPE],t2.SNILS, t2.NOM_PP,t2.CODE_STR,t2.CODE_KAT,t2.INSUR,t2.B_BEF, t2.GB_BEF, t2.B_AFT,
							t2.PER,t2.YEAR_BEGIN,t2.PER_EDT,t2.YEAR_EDT,t2.FM,t2.IM,t2.OT,
							t2.k_PER_EDT1,t2.k_YEAR_EDT1,t2.k_INSUR1,t2.k_INSUR_1,t2.k_GAIN1,t2.k_PER_EDT2,t2.k_YEAR_EDT2,t2.k_INSUR2,t2.k_INSUR_2,t2.k_GAIN2,
							t2.k_PER_EDT3,t2.k_YEAR_EDT3,t2.k_INSUR3,t2.k_INSUR_3,t2.k_GAIN3,t2.k_PER_EDT4,t2.k_YEAR_EDT4,t2.k_INSUR4,t2.k_INSUR_4,t2.k_GAIN4,
							t2.k_PER_EDT5,t2.k_YEAR_EDT5,t2.k_INSUR5,t2.k_INSUR_5,t2.k_GAIN5, t2.SUM_VZNOS
	INTO #RES
	FROM #PACHKA_64 t2  inner join #TAB61 t1  
	on 	t1.link= t2.link and t1.FM = t2.FM  and t1.IM = t2.IM and  t1.OT = t2.OT and t1.SNILS = t2.SNILS
	--where  @LINK_64 = @LINK_OP and @TYPE_64 = @TYP_D and @SNILS_64 = and @FM_64 =  and @IM_64 = and  @OT_64 = 
	order by T1.LINK, t2.link , t2.[type] , t2.fm, t2.IM, t2.OT, t2.CODE_STR


	SELECT T1.LINK , t1.NGROUP , T1.FNAME, T1.DOC_DATE,t1.FM,t1.IM,t1.OT, t2.[TYPE],t2.SNILS, t2.NOM_PP,t2.CODE_STR,t2.CODE_SPO,t2.INC_T1M,t2.INC_T2M,
								t2.DATE_BEGIN1,t2.DATE_END1,t2.TU_CODE1, t2.OS_CODE1, t2.EX_CODE1, t2.f_is_dop1, t2.P_CODE1, t2.f_ud_dop1,
								t2.DATE_BEGIN2,t2.DATE_END2,t2.TU_CODE2, t2.OS_CODE2, t2.EX_CODE2, t2.f_is_dop2, t2.P_CODE2, t2.f_ud_dop2,
								t2.DATE_BEGIN3,t2.DATE_END3,t2.TU_CODE3, t2.OS_CODE3, t2.EX_CODE3, t2.f_is_dop3, t2.P_CODE3, t2.f_ud_dop3,
								t2.DATE_BEGIN4,t2.DATE_END4,t2.TU_CODE4, t2.OS_CODE4, t2.EX_CODE4, t2.f_is_dop4, t2.P_CODE4, t2.f_ud_dop4
	INTO #RES1
	FROM #PACHKA_67 t2  inner join #TAB61 t1  
	on 	/*t1.link= t2.link and*/ t1.SNILS = t2.SNILS
	order by T1.LINK, t2.link , t2.[type], t1.fm, t1.IM, t1.OT, t2.CODE_STR


DECLARE	@LINK_R int, @TYPE_R varchar(15),@SNILS_R varchar(14),@CODE_STR_R varchar(4), 
		@CODE_KAT_R varchar(5),@FM_R varchar(100),@IM_R varchar(100),@OT_R varchar(100),
		@PER_R varchar(1),@YEAR_BEGIN_R varchar(4),@PER_EDT_R varchar(1),@YEAR_EDT_R varchar(4),
		@DATE_DOC_R varchar (10) ,  @FNAME_R varchar(150), @NOM_PACH_R varchar(4), @LINK_DOC_OP INT


SET @Cur3 = CURSOR FORWARD_ONLY
FOR 
select 	
	LINK , 
	[TYPE] = case [TYPE] when 1 then 'ИСХОДНАЯ' WHEN 2 then 'КОРРЕКТИРУЮЩАЯ' else 'ОТМЕНЯЮЩАЯ' end , 
	NOM_PP, 
	NOM_PACH, 
	SUM_BASE, 
	SUM_STR, 
	PERS_CNT, 
	DATE_DOC, 
	PER, 
	YEAR_BEGIN , 
	PER_EDT , 
	YEAR_EDT, 
	F_NAME,
	LINK_DOC
from #OPIS order by LINK,[TYPE], NOM_PP 


OPEN @Cur3
FETCH NEXT FROM @Cur3 INTO @LINK_OP, @TYP_D, @NOM_PP, @NGROUP /*Номер пачки*/,@SUM_BASE, @SUM_STR, @PERS_CNT,@DATE_DOC,@PER, @YEAR_BEGIN, @PER_EDT, @YEAR_EDT, @lcFNAME/*наименование файла*/ , @LINK_DOC_OP


WHILE (@@fetch_status <> -1)
BEGIN
	
	IF (@@fetch_status <> -2)
	BEGIN	
---------------------------------------------------------------
----------------------------------------------------------------

			-- Начало второго входящего документа (расширение блока входящий документ)
			IF (SELECT COUNT(*) FROM #OPIS) > 0 -- студенты
			BEGIN
							
				IF (SELECT COUNT (*) FROM #RES WHERE LTRIM(RTRIM([TYPE])) = LTRIM(RTRIM(@TYP_D)) and LTRIM(RTRIM(PER)) = LTRIM(RTRIM(ISNULL(@PER,'0'))) and LTRIM(RTRIM(YEAR_BEGIN)) = LTRIM(RTRIM(ISNULL(@YEAR_BEGIN,'0'))) 
										and LTRIM(RTRIM(PER_EDT)) =  LTRIM(RTRIM(ISNULL(@PER_EDT,'0'))) and LTRIM(RTRIM(YEAR_EDT)) =  LTRIM(RTRIM(ISNULL(@YEAR_EDT,'0'))) 
										and  LTRIM(RTRIM(DOC_DATE)) = LTRIM(RTRIM(@DATE_DOC)) and LTRIM(RTRIM(FNAME)) = LTRIM(RTRIM(@lcFNAME)) and LTRIM(RTRIM(NGROUP)) = LTRIM(RTRIM(@NGROUP))) > 0
				BEGIN
			

					SET @PERS_CNT  = (select distinct COUNT (*) FROM 
					(select distinct link , ngroup, snils from #RES WHERE LTRIM(RTRIM([TYPE])) = LTRIM(RTRIM(@TYP_D)) and LTRIM(RTRIM(PER)) = LTRIM(RTRIM(ISNULL(@PER,'0'))) and LTRIM(RTRIM(YEAR_BEGIN)) = LTRIM(RTRIM(ISNULL(@YEAR_BEGIN,'0'))) 
										and LTRIM(RTRIM(PER_EDT)) =  LTRIM(RTRIM(ISNULL(@PER_EDT,'0'))) and LTRIM(RTRIM(YEAR_EDT)) =  LTRIM(RTRIM(ISNULL(@YEAR_EDT,'0'))) 
										and  LTRIM(RTRIM(DOC_DATE)) = LTRIM(RTRIM(@DATE_DOC)) and LTRIM(RTRIM(FNAME)) = LTRIM(RTRIM(@lcFNAME)) and LTRIM(RTRIM(NGROUP)) = LTRIM(RTRIM(@NGROUP))
										GROUP BY link , ngroup , SNILS) s)
				
						
				DECLARE @NUM_PACH_PP INT 
				SET @NUM_PACH_PP = 1
				
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				 SELECT @lcFNAME, 'OEM' --Имя файла
				 UNION ALL SELECT @lcFNAME, SPACE(0) + '<?xml version="1.0" encoding="Windows-1251" ?>'
				 UNION ALL SELECT @lcFNAME, SPACE(0) + '<ФайлПФР>'
					UNION ALL SELECT @lcFNAME, SPACE(1) + '<ИмяФайла>' + RTRIM(LTRIM(@lcFNAME)) + '</ИмяФайла>'
					UNION ALL SELECT @lcFNAME, SPACE(1) + '<ЗаголовокФайла>'
					 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ВерсияФормата>07.00</ВерсияФормата>'
					 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ТипФайла>ВНЕШНИЙ</ТипФайла>'
					 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ПрограммаПодготовкиДанных>'
						UNION ALL SELECT @lcFNAME, SPACE(3) + '<НазваниеПрограммы>' + @NAME_PROG + '</НазваниеПрограммы>'
						UNION ALL SELECT @lcFNAME, SPACE(3) + '<Версия>' + @VERS_PROG + '</Версия>'
					 UNION ALL SELECT @lcFNAME, SPACE(2) + '</ПрограммаПодготовкиДанных>'
					 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ИсточникДанных>СТРАХОВАТЕЛЬ</ИсточникДанных> '
					UNION ALL SELECT @lcFNAME, SPACE(1) + '</ЗаголовокФайла>'
					UNION ALL SELECT @lcFNAME, SPACE(1) + '<ПачкаВходящихДокументов Окружение="В составе файла" Стадия="До обработки">'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
					SELECT @lcFNAME, SPACE(2) + '<СВЕДЕНИЯ_ПО_ПАЧКЕ_ДОКУМЕНТОВ_РАЗДЕЛА_6>' 


				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
					SELECT @lcFNAME, SPACE(3) + '<НомерВпачке>'+ RTRIM(LTRIM(STR(@NUM_PACH_PP)))+'</НомерВпачке>' + CHAR(10) + 
						SPACE(3) + '<ТипВходящейОписи>ОПИСЬ ПАЧКИ</ТипВходящейОписи>' + CHAR(10) + 
						SPACE(3) + '<СоставительПачки>' + CHAR(10) + 
							SPACE(4) + '<НалоговыйНомер>' + CHAR(10) + 
								SPACE(5) + '<ИНН>' + LTRIM(RTRIM(ISNULL((select TOP 1 INN1 FROM #DEP_DATA),'')))+ '</ИНН>' + CHAR(10) + 
								SPACE(5) + '<КПП>' + LTRIM(RTRIM(ISNULL((SELECT TOP 1 KPP1 FROM #DEP_DATA),''))) + '</КПП>' + CHAR(10) + 
							SPACE(4) + '</НалоговыйНомер>' + CHAR(10) + 
							SPACE(4) + '<НаименованиеОрганизации>' + LTRIM(RTRIM(ISNULL((SELECT TOP 1 CONVERT(varchar(50),FULL_NAME) FROM #DEP_DATA),'')))+ '</НаименованиеОрганизации>' + CHAR(10) + 
							SPACE(4) + '<НаименованиеКраткое>' + LTRIM(RTRIM(ISNULL( (SELECT TOP 1 ORGNAME FROM #DEP_DATA),''))) + '</НаименованиеКраткое>' + CHAR(10) + 
							SPACE(4) + '<РегистрационныйНомер>' + LTRIM(RTRIM(ISNULL( (SELECT TOP 1 PFNUMBER FROM #DEP_DATA),''))) + '</РегистрационныйНомер>' + CHAR(10) + 
						SPACE(3) + '</СоставительПачки>' + CHAR(10) + 
						SPACE(3) + '<НомерПачки>' + CHAR(10) + 
							SPACE(4) + '<Основной>'+LTRIM(RTRIM(@NGROUP))+'</Основной>' + CHAR(10) + 	
						SPACE(3) + '</НомерПачки>' + CHAR(10) + 	
						SPACE(3) + '<СоставДокументов>' + CHAR(10) + 	
							SPACE(4) + '<Количество>' + '1' /*@DOCCOUNT*/ + '</Количество>' + CHAR(10) + 	
							SPACE(4) + '<НаличиеДокументов>' + CHAR(10) + 	
								SPACE(5) + '<ТипДокумента>СВЕДЕНИЯ_О_СУММЕ_ВЫПЛАТ_И_СТРАХОВОМ_СТАЖЕ_ЗЛ</ТипДокумента>' + CHAR(10) + 	
								SPACE(5) + '<Количество>' + RTRIM(LTRIM(STR(@PERS_CNT)))+ '</Количество>' + CHAR(10) + 	
							SPACE(4) + '</НаличиеДокументов>' + CHAR(10) + 	
						SPACE(3) + '</СоставДокументов>' + CHAR(10) + 		

						SPACE(3) + '<ДатаСоставления>' + CONVERT(VARCHAR(10),@DATE_DOC,104)+ '</ДатаСоставления>' + CHAR(10) + 	
						SPACE(3) + '<ТипСведений>' + RTRIM(LTRIM(@TYP_D)) + '</ТипСведений>' + CHAR(10) + 	

						SPACE(3) + '<ОтчетныйПериод>'+ CHAR(10) + 	
							SPACE(4) + '<Квартал>' + CASE @PER WHEN '1' THEN '3' 
															 WHEN '2' THEN '6' 
															 WHEN '3' THEN '9'
															 ELSE '0' 
													 END + '</Квартал>' + CHAR(10) + 	
							SPACE(4) + '<Год>' + @YEAR_BEGIN + '</Год>' + CHAR(10) + 	
							SPACE(4) + '<Название>' 
										+	CASE @PER 
													WHEN '1' THEN 'С 01.01.'+@YEAR_BEGIN+' ПО 31.03.'+@YEAR_BEGIN
													WHEN '2' THEN 'С 01.01.'+@YEAR_BEGIN+' ПО 30.06.'+@YEAR_BEGIN
													WHEN '3' THEN 'С 01.01.'+@YEAR_BEGIN+' ПО 30.09.'+@YEAR_BEGIN
													WHEN '4' THEN 'С 01.01.'+@YEAR_BEGIN+' ПО 31.12.'+@YEAR_BEGIN
													ELSE ''
											END									
											+ '</Название>' + CHAR(10) + 	
						SPACE(3) + '</ОтчетныйПериод>' + CHAR(10) + 
											
						CASE WHEN @TYP_D = 'КОРРЕКТИРУЮЩАЯ' and @PER_EDT IS NOT NULL THEN ( SPACE(3) + '<КорректируемыйОтчетныйПериод>' + CHAR(10) + 
																SPACE(4) + '<Квартал>' + CASE @PER_EDT WHEN '1' THEN '3' 
																									 WHEN '2' THEN '6'
																									 WHEN '3' THEN '9'	
																									 ELSE '0' 
																						 END+ '</Квартал>' + CHAR(10) + 
																SPACE(4) + '<Год>' + @YEAR_EDT + '</Год>' + CHAR(10) + 
																SPACE(4) + '<Название>' + 
																			CASE @PER_EDT 
																					WHEN '1' THEN 'С 01.01.'+@YEAR_EDT+' ПО 31.03.'+@YEAR_EDT
																					WHEN '2' THEN 'С 01.01.'+@YEAR_EDT+' ПО 30.06.'+@YEAR_EDT
																					WHEN '3' THEN 'С 01.01.'+@YEAR_EDT+' ПО 30.09.'+@YEAR_EDT
																					WHEN '4' THEN 'С 01.01.'+@YEAR_EDT+' ПО 31.12.'+@YEAR_EDT
																					ELSE ''
																			END									
																			+ '</Название>' + CHAR(10) + 
															SPACE(3) + '</КорректируемыйОтчетныйПериод>' ) ELSE '' END + CHAR(10) + 
													SPACE(3) + '<БазаДляНачисленияСтраховыхВзносовНеПревышающаяПредельную>' + RTRIM(LTRIM(STR(COALESCE(@SUM_BASE,0),15,2))) + '</БазаДляНачисленияСтраховыхВзносовНеПревышающаяПредельную>' + CHAR(10) + 
													SPACE(3) + '<СтраховыхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE(@SUM_STR,0),15,2))) + '</СтраховыхВзносовОПС>' 
				
						INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
						SELECT @lcFNAME,SPACE(2) + '</СВЕДЕНИЯ_ПО_ПАЧКЕ_ДОКУМЕНТОВ_РАЗДЕЛА_6>'									


						DECLARE @NUM_l INT, @num_old INT
						SET @NUM_l = 0
						SET @num_old = 0
						
						SET @Cur4 = CURSOR FORWARD_ONLY
						FOR 
						SELECT LINK,[TYPE],SNILS,PER,YEAR_BEGIN,PER_EDT,YEAR_EDT,FM,IM,OT, DOC_DATE/*, FNAME, NGROUP*/
						FROM #RES where  LTRIM(RTRIM([TYPE])) = LTRIM(RTRIM(@TYP_D)) and LTRIM(RTRIM(PER)) = LTRIM(RTRIM(ISNULL(@PER,'0'))) and LTRIM(RTRIM(YEAR_BEGIN)) = LTRIM(RTRIM(ISNULL(@YEAR_BEGIN,'0'))) 
										and LTRIM(RTRIM(PER_EDT)) =  LTRIM(RTRIM(ISNULL(@PER_EDT,'0'))) and LTRIM(RTRIM(YEAR_EDT)) =  LTRIM(RTRIM(ISNULL(@YEAR_EDT,'0'))) 
										and  LTRIM(RTRIM(DOC_DATE)) = LTRIM(RTRIM(@DATE_DOC)) and LTRIM(RTRIM(FNAME)) = LTRIM(RTRIM(@lcFNAME)) and LTRIM(RTRIM(NGROUP)) = LTRIM(RTRIM(@NGROUP))  
						group BY LINK,[TYPE],SNILS,PER,YEAR_BEGIN,PER_EDT,YEAR_EDT,FM,IM,OT, DOC_DATE/*, FNAME, NGROUP*/
						order by link , fm, IM, OT, SNILS , [type]

						OPEN @Cur4
						FETCH NEXT FROM @Cur4 INTO @LINK_R, @TYPE_R,@SNILS_R,@PER_R,@YEAR_BEGIN_R,@PER_EDT_R,@YEAR_EDT_R, 
													@FM_R,@IM_R,@OT_R, @DATE_DOC_R/*, @FNAME_R, @NOM_PACH_R*/
						WHILE (@@fetch_status <> -1)
						BEGIN
							
							IF (@@fetch_status <> -2)
							BEGIN	
									set @NUM_PACH_PP = @NUM_PACH_PP + 1 					
								
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
										SELECT @lcFNAME, SPACE(2) + '<СВЕДЕНИЯ_О_СУММЕ_ВЫПЛАТ_И_СТРАХОВОМ_СТАЖЕ_ЗЛ>' 
							
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
										SELECT @lcFNAME, SPACE(3) + '<НомерВпачке>'+ RTRIM(LTRIM(STR(@NUM_PACH_PP)))+'</НомерВпачке>'
										UNION ALL SELECT @lcFNAME, SPACE(3) + '<ТипСведений>'+ UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),''))))+ '</ТипСведений>' 
										UNION ALL SELECT @lcFNAME, SPACE(3) + '<РегистрационныйНомер>'+ LTRIM(RTRIM(ISNULL( (SELECT TOP 1 PFNUMBER FROM #DEP_DATA),''))) +'</РегистрационныйНомер>'
										UNION ALL SELECT @lcFNAME, SPACE(3) + '<СтраховойНомер>'+ LTRIM(RTRIM(ISNULL( @SNILS_R,''))) +'</СтраховойНомер>'
										UNION ALL SELECT @lcFNAME, SPACE(3) + '<ФИО>' 
											UNION ALL SELECT @lcFNAME, SPACE(4) + '<Фамилия>' + UPPER(LTRIM(RTRIM(ISNULL(@FM_R,''))))+ '</Фамилия>' 
											UNION ALL SELECT @lcFNAME, SPACE(4) + '<Имя>' + UPPER(LTRIM(RTRIM(ISNULL(@iM_R,''))))+ '</Имя>' 
											UNION ALL SELECT @lcFNAME, SPACE(4) + '<Отчество>' + UPPER(LTRIM(RTRIM(ISNULL(@OT_R,''))))+ '</Отчество>' 
										UNION ALL SELECT @lcFNAME, SPACE(3) + '</ФИО>' 	
										UNION ALL SELECT @lcFNAME, SPACE(3) + '<ОтчетныйПериод>'
											UNION ALL SELECT @lcFNAME, SPACE(4) + '<Квартал>' + CASE @PER_r WHEN '1' THEN '3' 
																										  WHEN '2' THEN '6' 
																										  WHEN '3' THEN '9'
																										  ELSE '0' 
																										  END 
																				+ '</Квартал>' 	
											UNION ALL SELECT @lcFNAME, SPACE(4) + '<Год>' + @YEAR_BEGIN_r + '</Год>'	
											UNION ALL SELECT @lcFNAME, SPACE(4) + '<Название>' +	CASE @PER_R 
																											WHEN '1' THEN 'С 01.01.'+@YEAR_BEGIN_R+' ПО 31.03.'+@YEAR_BEGIN_R
																											WHEN '2' THEN 'С 01.01.'+@YEAR_BEGIN_R+' ПО 30.06.'+@YEAR_BEGIN_R
																											WHEN '3' THEN 'С 01.01.'+@YEAR_BEGIN_R+' ПО 30.09.'+@YEAR_BEGIN_R
																											WHEN '4' THEN 'С 01.01.'+@YEAR_BEGIN_R+' ПО 31.12.'+@YEAR_BEGIN_R
																											ELSE ''
																									END									
																				+ '</Название>' 	
											UNION ALL SELECT @lcFNAME,SPACE(3) + '</ОтчетныйПериод>' 
											
											IF UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'КОРРЕКТИРУЮЩАЯ'
												INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														 SELECT @lcFNAME, SPACE(3) + '<КорректируемыйОтчетныйПериод>' + CHAR(10) + CHAR(13) + 
																				SPACE(4) + '<Квартал>' + CASE @PER_EDT_R WHEN '1' THEN '3' 
																														 WHEN '2' THEN '6'
																														 WHEN '3' THEN '9'	
																														 ELSE '0' 
																										END
																						+ '</Квартал>' + CHAR(10) + CHAR(13) + 
																				SPACE(4) + '<Год>' + @YEAR_EDT_R + '</Год>' + CHAR(10) + CHAR(13) +
																				SPACE(4) + '<Название>' + 
																							CASE @PER_EDT_R 
																										WHEN '1' THEN 'С 01.01.'+@YEAR_EDT_R+' ПО 31.03.'+@YEAR_EDT_R
																										WHEN '2' THEN 'С 01.01.'+@YEAR_EDT_R+' ПО 30.06.'+@YEAR_EDT_R
																										WHEN '3' THEN 'С 01.01.'+@YEAR_EDT_R+' ПО 30.09.'+@YEAR_EDT_R
																										WHEN '4' THEN 'С 01.01.'+@YEAR_EDT_R+' ПО 31.12.'+@YEAR_EDT_R
																										ELSE ''
																							END									
																						+ '</Название>' + CHAR(10) + CHAR(13) +
																		SPACE(3) + '</КорректируемыйОтчетныйПериод>' + CHAR(10) + CHAR(13) +
																		SPACE(3) + '<РегистрационныйНомерКорректируемогоПериода>'+ LTRIM(RTRIM(ISNULL( (SELECT TOP 1 PFNUMBER FROM #DEP_DATA),''))) +'</РегистрационныйНомерКорректируемогоПериода>'
											
											 
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT  @lcFNAME, SPACE(3) + '<СведенияОсуммеВыплатИвознагражденийВпользуЗЛ>' + CHAR(10)+
																			 SPACE(4) + '<НомерСтроки>' + LTRIM(RTRIM(ISNULL( NOM_PP,''))) + '</НомерСтроки>' + CHAR(10)+
																			 SPACE(4) + '<ТипСтроки>' + LTRIM(RTRIM(ISNULL( (CASE WHEN CODE_STR = '400' OR CODE_STR = '410' OR CODE_STR = '420' THEN 'ИТОГ' ELSE 'МЕСЦ' END),''))) + '</ТипСтроки>' + CHAR(10)+
																			 SPACE(4) + (CASE WHEN CODE_STR = '400' OR CODE_STR ='410' OR CODE_STR ='420' THEN ''
																							  else  ( '<Месяц>' +	(CASE WHEN CODE_STR = '400' OR CODE_STR ='410' OR CODE_STR ='420' THEN ''
																							   
																														  WHEN CODE_STR = '401' OR CODE_STR ='411' OR CODE_STR ='421' THEN  
																														  						(CASE WHEN UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'ИСХОДНАЯ' 
																														  							  THEN (CASE @PER_r WHEN '1' THEN '1'
																														  												WHEN '2' THEN '4'
																														  												WHEN '3' THEN '7'
																														  												ELSE '10' end)
																														  							  ELSE (CASE @PER_EDT_R WHEN '1' THEN '1'
																														  													WHEN '2' THEN '4'
																														  													WHEN '3' THEN '7'
																														  													ELSE '10' end)    
																														  						END)
																																														
																														  WHEN CODE_STR = '402' OR CODE_STR ='412' OR CODE_STR ='422' THEN 
																														  						(CASE WHEN UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'ИСХОДНАЯ' 
																														  							  THEN (CASE @PER_r WHEN '1' THEN '2'
																														  												WHEN '2' THEN '5'
																														  												WHEN '3' THEN '8'
																														  												ELSE '11' end)
																														  							  ELSE (CASE @PER_EDT_R WHEN '1' THEN '2'
																														  													WHEN '2' THEN '5'
																														  													WHEN '3' THEN '8'
																														  													ELSE '11' end)    
																														  						END)
																														 
																														  ELSE 					(CASE WHEN UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'ИСХОДНАЯ' 
																														  							  THEN (CASE @PER_r WHEN '1' THEN '3'
																														  												WHEN '2' THEN '6'
																														  												WHEN '3' THEN '9'
																														  												ELSE '12' end)
																														  							  ELSE (CASE @PER_EDT_R WHEN '1' THEN '3'
																														  													WHEN '2' THEN '6'
																														  													WHEN '3' THEN '9'
																														  													ELSE '12' end)    
																														  						END)  
																							                     	      end ) + '</Месяц>'  ) 
																							  END)   + CHAR(10)+
																									
																			 SPACE(4) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(CODE_STR,''))) + '</КодСтроки>' + CHAR(10)+
																			 SPACE(4) + '<КодКатегории>' + LTRIM(RTRIM(ISNULL(CODE_KAT,''))) + '</КодКатегории>' + CHAR(10)+
																			 SPACE(4) + '<СуммаВыплатИныхВознаграждений>' + RTRIM(LTRIM(STR(COALESCE(INSUR,0),15,2))) + '</СуммаВыплатИныхВознаграждений>' + CHAR(10)+
																			 SPACE(4) + '<НеПревышающиеВсего>' + RTRIM(LTRIM(STR(COALESCE(B_BEF,0),15,2))) + '</НеПревышающиеВсего>' + CHAR(10)+
																			 SPACE(4) + '<НеПревышающиеПоДоговорам>' + RTRIM(LTRIM(STR(COALESCE(GB_BEF,0),15,2))) + '</НеПревышающиеПоДоговорам>' + CHAR(10)+
																			 SPACE(4) + '<ПревышающиеПредельную>' + RTRIM(LTRIM(STR(COALESCE(B_AFT,0),15,2))) + '</ПревышающиеПредельную>' + CHAR(10)+
																	  SPACE(3) + '</СведенияОсуммеВыплатИвознагражденийВпользуЗЛ>'	
													FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND PER = @PER_R AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R 
																	AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R /*and FNAME = @FNAME_R */and LTRIM(RTRIM(NGROUP)) = LTRIM(RTRIM(@NGROUP))
										
											
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT  @lcFNAME, SPACE(3) + '<СуммаВзносовНаОПС>' + RTRIM(LTRIM(STR(COALESCE(SUM(SUM_VZNOS),0),15,2))) + '</СуммаВзносовНаОПС>' 
													FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND PER = @PER_R AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R 
																	AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R */and LTRIM(RTRIM(NGROUP)) = LTRIM(RTRIM(@NGROUP)) 
																	AND CODE_STR IN ('400','410','420')

												
											IF UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'КОРРЕКТИРУЮЩАЯ'
											BEGIN
												

													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														SELECT  @lcFNAME,
															(CASE WHEN k_INSUR1 <> 0 AND k_GAIN1 <> 0 AND  K_YEAR_EDT1 <> 0
															THEN
																	+ SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																				 SPACE(4) + '<НомерСтроки>' + '1' + '</НомерСтроки>' + CHAR(10)+
																				 SPACE(4) + '<ТипСтроки>'+'МЕСЦ'+'</ТипСтроки>' + CHAR(10)+
																				 SPACE(4) + '<Квартал>' +	(CASE WHEN k_per_edt1 = '1' THEN '3' 
																										WHEN k_per_edt1 = '2' THEN '6' 
																										WHEN k_per_edt1 = '3' THEN '9'
																										ELSE '0'  end ) + '</Квартал>' + CHAR(10)+
																				 SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(K_YEAR_EDT1,''))) + '</Год>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR1,0),15,2))) + '</СуммаДоначисленныхВзносовОПС>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR_1,0),15,2))) + '</СуммаДоначисленныхВзносовНаСтраховую>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(k_GAIN1,0),15,2))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10)+
																		  SPACE(3) + '</СведенияОкорректировках>'	
															ELSE 
																''																
															END	)
														FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																		and OT = @OT_R AND PER = @PER_R AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R 
																		AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																		AND CODE_STR = '400' 

												

													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														SELECT  @lcFNAME, 
															(CASE WHEN k_INSUR2 <> 0 AND k_GAIN2 <> 0 AND  K_YEAR_EDT2 <> 0
															THEN		
																+ SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																				 SPACE(4) + '<НомерСтроки>' + '2' + '</НомерСтроки>' + CHAR(10)+
																				 SPACE(4) + '<ТипСтроки>'+'МЕСЦ'+'</ТипСтроки>' + CHAR(10)+
																				 SPACE(4) + '<Квартал>' +	(CASE WHEN k_per_edt2 = '1' THEN '3' 
																										WHEN k_per_edt2 = '2' THEN '6' 
																										WHEN k_per_edt2 = '3' THEN '9'
																										ELSE '0'  end ) + '</Квартал>' + CHAR(10)+
																				 SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(K_YEAR_EDT2,''))) + '</Год>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR2,0),15,2))) + '</СуммаДоначисленныхВзносовОПС>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR_2,0),15,2))) + '</СуммаДоначисленныхВзносовНаСтраховую>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(k_GAIN2,0),15,2))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10)+
																		  SPACE(3) + '</СведенияОкорректировках>'	
															ELSE 
																''
															END	)			  
																		  
														FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																		and OT = @OT_R AND PER = @PER_R AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R 
																		AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																		AND CODE_STR = '400' 

												

													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														SELECT  @lcFNAME, 
														    (CASE WHEN k_INSUR3 <> 0 AND k_GAIN3 <> 0 AND  K_YEAR_EDT3 <> 0
																  THEN
																		+ SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																				 SPACE(4) + '<НомерСтроки>' + '3' + '</НомерСтроки>' + CHAR(10)+
																				 SPACE(4) + '<ТипСтроки>'+'МЕСЦ'+'</ТипСтроки>' + CHAR(10)+
																				 SPACE(4) + '<Квартал>' +	(CASE WHEN k_per_edt3 = '1' THEN '3' 
																										WHEN k_per_edt3 = '2' THEN '6' 
																										WHEN k_per_edt3 = '3' THEN '9'
																										ELSE '0'  end ) + '</Квартал>' + CHAR(10)+
																				 SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(K_YEAR_EDT3,''))) + '</Год>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR3,0),15,2))) + '</СуммаДоначисленныхВзносовОПС>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR_3,0),15,2))) + '</СуммаДоначисленныхВзносовНаСтраховую>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(k_GAIN3,0),15,2))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10)+
																		  SPACE(3) + '</СведенияОкорректировках>'
																ELSE 
																	''
																END	)			  
																																			  	
														FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																		and OT = @OT_R AND PER = @PER_R AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R 
																		AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																		AND CODE_STR = '400' 

												
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
															SELECT  @lcFNAME, 
																			  
																	(CASE WHEN k_INSUR4 <> 0 AND k_GAIN4 <> 0 AND  K_YEAR_EDT4 <> 0
																		  THEN  
																			+ SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																					 SPACE(4) + '<НомерСтроки>' + '4' + '</НомерСтроки>' + CHAR(10)+
																					 SPACE(4) + '<ТипСтроки>'+'МЕСЦ'+'</ТипСтроки>' + CHAR(10)+
																					 SPACE(4) + '<Квартал>' +	(CASE WHEN k_per_edt4 = '1' THEN '3' 
																											WHEN k_per_edt4 = '2' THEN '6' 
																											WHEN k_per_edt4 = '3' THEN '9'
																											ELSE '0'  end ) + '</Квартал>' + CHAR(10)+
																					 SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(K_YEAR_EDT4,''))) + '</Год>' + CHAR(10)+
																					 SPACE(4) + '<СуммаДоначисленныхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR4,0),15,2))) + '</СуммаДоначисленныхВзносовОПС>' + CHAR(10)+
																					 SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR_4,0),15,2))) + '</СуммаДоначисленныхВзносовНаСтраховую>' + CHAR(10)+
																					 SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(k_GAIN4,0),15,2))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10)+
																			  SPACE(3) + '</СведенияОкорректировках>'	
																	  ELSE 
																		''
																	  END	)			  
																				  
															FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																			and OT = @OT_R AND PER = @PER_R AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R 
																			AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																			AND CODE_STR = '400' 																															


													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														SELECT  @lcFNAME,
																(CASE WHEN k_INSUR5 <> 0 AND k_GAIN5 <> 0 AND  K_YEAR_EDT5 <> 0
																	  THEN  
																		+	SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																				 SPACE(4) + '<НомерСтроки>' + '5' + '</НомерСтроки>' + CHAR(10)+
																				 SPACE(4) + '<ТипСтроки>'+'МЕСЦ'+'</ТипСтроки>' + CHAR(10)+
																				 SPACE(4) + '<Квартал>' +	(CASE WHEN k_per_edt5 = '1' THEN '3' 
																										WHEN k_per_edt5 = '2' THEN '6' 
																										WHEN k_per_edt5 = '3' THEN '9'
																										ELSE '0'  end ) + '</Квартал>' + CHAR(10)+
																				 SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(K_YEAR_EDT5,''))) + '</Год>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR5,0),15,2))) + '</СуммаДоначисленныхВзносовОПС>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR_5,0),15,2))) + '</СуммаДоначисленныхВзносовНаСтраховую>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(k_GAIN5,0),15,2))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10)+
																		  SPACE(3) + '</СведенияОкорректировках>'	
																	  ELSE 
																		''
																	  END	)  
														FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																		and OT = @OT_R AND PER = @PER_R AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R 
																		AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																		AND CODE_STR = '400' 

												
												INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT  @lcFNAME,
															(CASE WHEN k_INSUR1<>0 and k_INSUR2 <> 0 and k_INSUR3<>0 and k_INSUR4<>0 and k_INSUR5 <> 0
																  THEN  
																	+ SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																			 SPACE(4) + '<НомерСтроки>' + '6' + '</НомерСтроки>' + CHAR(10)+
																			 SPACE(4) + '<ТипСтроки>'+'ИТОГ'+'</ТипСтроки>' + CHAR(10)+
																			 SPACE(4) + '<Квартал>'  +	(CASE WHEN per_edt = '1' THEN '3' 
																										WHEN per_edt = '2' THEN '6' 
																										WHEN per_edt = '3' THEN '9'
																										ELSE '0'  end ) + '</Квартал>' + CHAR(10)+ 
																			 SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(YEAR_EDT,''))) + '</Год>' + CHAR(10)+
																			 SPACE(4) + '<СуммаДоначисленныхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE((k_INSUR1+k_INSUR2+k_INSUR3+k_INSUR4+k_INSUR5),0),15,2))) + '</СуммаДоначисленныхВзносовОПС>' + CHAR(10)+
																			 SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE((k_INSUR_1+k_INSUR_2+k_INSUR_3+k_INSUR_4+k_INSUR_5),0),15,2))) + '</СуммаДоначисленныхВзносовНаСтраховую>' + CHAR(10)+
																			 SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE((k_GAIN1+k_GAIN2+k_GAIN3+k_GAIN4+k_GAIN5),0),15,2))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10)+
																	  SPACE(3) + '</СведенияОкорректировках>'
															ELSE 
																''
															END		)	  	
													FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND PER = @PER_R AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R 
																	AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																	AND CODE_STR = '400'  
											end  
											--IF (SELECT COUNT (*) FROM #RES1 WHERE [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
											--						and OT = @OT_R AND DOC_DATE = @DATE_DOC_R ) > 1
											--BEGIN
											
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT  @lcFNAME, SPACE(3) + '<СведенияОсуммеВыплатИвознагражденийПоДопТарифу>' + CHAR(10)+
																			 SPACE(4) + '<НомерСтроки>' + LTRIM(RTRIM(ISNULL( NOM_PP,''))) + '</НомерСтроки>' + CHAR(10)+
																			 SPACE(4) + '<ТипСтроки>' + LTRIM(RTRIM(ISNULL( (CASE WHEN CODE_STR = '700' OR CODE_STR = '710' OR CODE_STR = '720' THEN 'ИТОГ' ELSE 'МЕСЦ' END),''))) + '</ТипСтроки>' + CHAR(10)+
																			 SPACE(4) + (CASE WHEN CODE_STR = '700' OR CODE_STR ='710' OR CODE_STR ='720' THEN '' 
																							else ('<Месяц>' +	(CASE WHEN CODE_STR = '700' OR CODE_STR ='710' OR CODE_STR ='720' THEN '' 
																									WHEN CODE_STR = '701' OR CODE_STR ='711' OR CODE_STR ='721' THEN '1' 
																									WHEN CODE_STR = '702' OR CODE_STR ='712' OR CODE_STR ='722' THEN '2'
																									ELSE '3'  end ) + '</Месяц>') 
																							end)		+ CHAR(10)+
																			 SPACE(4) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(CODE_STR,''))) + '</КодСтроки>' + CHAR(10)+
																			 SPACE(4) + '<КодСпециальнойОценкиУсловийТруда>' + LTRIM(RTRIM(ISNULL(CODE_SPO,'пустое'))) + '</КодСпециальнойОценкиУсловийТруда>' + CHAR(10)+
																			 SPACE(4) + '<СуммаВыплатПоДопТарифу27-1>' + RTRIM(LTRIM(STR(COALESCE(INC_T1M,0),15,2))) + '</СуммаВыплатПоДопТарифу27-1>' + CHAR(10)+
																			 SPACE(4) + '<СуммаВыплатПоДопТарифу27-2-18>' + RTRIM(LTRIM(STR(COALESCE(INC_T2M,0),15,2))) + '</СуммаВыплатПоДопТарифу27-2-18>' + CHAR(10)+
																	  SPACE(3) + '</СведенияОсуммеВыплатИвознагражденийПоДопТарифу>'	
													FROM #RES1 WHERE link = @LINK_R 	AND [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND DOC_DATE = @DATE_DOC_R  
																	AND ((SELECT top 1 isnull(INC_T1M,0) FROM #RES1 WHERE [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND DOC_DATE = @DATE_DOC_R AND CODE_STR = '700' ) > 0 OR
																		 (SELECT top 1 isnull(INC_T2M,0) FROM #RES1 WHERE [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND DOC_DATE = @DATE_DOC_R AND CODE_STR = '700' ) > 0 )
																	  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
											 --END	

																	
													CREATE TABLE #STAZH_TMP ( link INt, FM VARCHAR(100), IM VARCHAR(100), OT VARCHAR(100), SNILS VARCHAR(14), date1 VARCHAR(10), date2 VARCHAR(10), 
																			  T_DOG int , [TU_CODE] VARCHAR (31) ,ter_koef NUMERIC(18,2),[OS_CODE] VARCHAR(94),[EX_CODE] VARCHAR (10), 
																			  osob_spis VARCHAR(20), is_dop_m TINYINT,is_dop_d TINYINT , is_dop VARCHAR(20), 
																			  [f_is_dop] VARCHAR(63),[P_CODE] VARCHAR(10),ud_dop_m INT,ud_dop_d INT  , ud_dop_k NUMERIC(18,2) , [f_ud_dop] VARCHAR(54)) 
													INSERT INTO #STAZH_TMP  (link , FM , IM, OT, SNILS, date1, date2,T_DOG, [TU_CODE],ter_koef, [OS_CODE],
																			  [EX_CODE], osob_spis, is_dop_m,is_dop_d, is_dop,[f_is_dop],[P_CODE],ud_dop_m,ud_dop_d, ud_dop_k, [f_ud_dop])
													SELECT	link = st.orders,
															FM = S.FM,
															IM = S.IM,
															OT = S.OT,
															SNILS = S.PF_NUM,
															date1 = convert(varchar(10),ST.date1, 104),
															date2 = convert(varchar(10),ST.date2, 104),
															T_DOG= s.forma,
															[TU_CODE] = st.f_ter_usl ,
															st.ter_koef,
															[OS_CODE] = st.f_osob_usl,
															[EX_CODE] = st.is_osnov,
															osob_spis = RTRIM(LTRIM(COALESCE(st.osob_k1,''))) + RTRIM(LTRIM(COALESCE(st.osob_k2,''))) + RTRIM(LTRIM(COALESCE(st.osob_k3,''))),
															is_dop_m = st.is_dop_m,
															is_dop_d = st.is_dop_d,
															is_dop = st.is_dop,
															[f_is_dop] = st.f_is_dop,
															[P_CODE] = st.ud_osnov,
															ud_dop_m = st.ud_dop_m,
															ud_dop_d = st.ud_dop_d,
															ud_dop_k = st.ud_dop_k,
															[f_ud_dop] 
													FROM dbo.SA_SZV4_SVEDENIA s 
													LEFT JOIN  dbo.SA_SZV4_STAZH st ON S.link1 = ST.link
													WHERE s.link = @LINK_DOC_OP AND  s.FM = @FM_R and s.IM = @IM_R  and s.OT = @OT_R 
														AND  s.PF_NUM= @SNILS_R  
														AND ((s.forma = 2  and NOT EXISTS (	select * FROM dbo.SA_SZV4_SVEDENIA s 
																							LEFT JOIN  dbo.SA_SZV4_STAZH st ON S.link1 = ST.link
																							WHERE s.link = @LINK_DOC_OP AND  s.FM = @FM_R and s.IM = @IM_R  and s.OT = @OT_R 
																								AND  s.PF_NUM= @SNILS_R  AND   s.forma = 1)
																				AND EXISTS (select * FROM dbo.SA_SZV4_SVEDENIA s 
																							LEFT JOIN  dbo.SA_SZV4_STAZH st ON S.link1 = ST.link
																							WHERE s.link = @LINK_DOC_OP AND  s.FM = @FM_R and s.IM = @IM_R  and s.OT = @OT_R 
																								AND  s.PF_NUM= @SNILS_R  AND   s.forma = 2))
															  or s.forma = 1  )
														
														
													ORDER BY st.orders, ST.date1
													

												
 													
													/*первая строка*/
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													Select @lcFNAME,
													CASE WHEN @TYPE_R <> 'ОТМЕНЯЮЩАЯ' THEN	
													/*CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' 	THEN	''
													ELSE*/	
														(CASE WHEN DATE1 <> '' THEN  
														+	SPACE(3) + '<СтажевыйПериод>' + CHAR(10)
														+		SPACE(4) + '<НомерСтроки>' + ltrim(rtrim(CONVERT(VARCHAR(2),link))) + '</НомерСтроки>' + CHAR(10)
														+		SPACE(4) + '<ДатаНачалаПериода>' + CONVERT(VARCHAR(10),DATE1,104) + '</ДатаНачалаПериода>' + CHAR(10)
														+		SPACE(4) + '<ДатаКонцаПериода>' + CONVERT(VARCHAR(10),DATE2,104) + '</ДатаКонцаПериода>' + CHAR(10)
														+				CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE,''))) <> '' OR RTRIM(LTRIM(COALESCE([OS_CODE],''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE,''))) <> '' THEN 
														+		SPACE(4) + '<КоличествоЛьготныхСоставляющих>' + CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE,''))) <> '' THEN '1' ELSE '0' END + '</КоличествоЛьготныхСоставляющих>' + CHAR(10)		
														+		SPACE(4) + '<ЛьготныйСтаж>' + CHAR(10)
														+			SPACE(5) + '<НомерСтроки>1</НомерСтроки>' + CHAR(10)		
														+ 			SPACE(5) + '<ОсобенностиУчета>' + CHAR(10)
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE,''))) <> '' THEN
																			SPACE(7) + '<ТерриториальныеУсловия>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеТУ>' + RTRIM(LTRIM(COALESCE(TU_CODE,''))) + '</ОснованиеТУ>' + CHAR(10)
														+						CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE,''))) not in ('Ч31','Ч33','Ч34','Ч35','Ч36') then
																				(CASE WHEN RTRIM(LTRIM(COALESCE(STR(ter_koef,4,2),''))) <> '0.00' then SPACE(8) + '<Коэффициент>' + RTRIM(LTRIM(COALESCE(STR(ter_koef,4,2),''))) + '</Коэффициент>' + CHAR(10) else '' end)
																				else '' end
														+ 					SPACE(7) + '</ТерриториальныеУсловия>' + CHAR(10)
																			ELSE '' END
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(OS_CODE,''))) <> '' THEN
																			SPACE(7) + '<ОсобыеУсловияТруда>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеОУТ>' + LEFT(RTRIM(LTRIM(COALESCE(OS_CODE,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE,'')))) -1 )  + '</ОснованиеОУТ>' + CHAR(10)
														+						CASE WHEN LEFT(RTRIM(LTRIM(COALESCE(OS_CODE,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE,'')))) -1 ) = '27-1' or LEFT(RTRIM(LTRIM(COALESCE(OS_CODE,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE,'')))) -1 ) = '27-2' THEN
																					SPACE(8) + '<ПозицияСписка>' + UPPER(RTRIM(LTRIM(COALESCE(osob_spis,'')))) + '</ПозицияСписка>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ОсобыеУсловияТруда>' + CHAR(10)
																			ELSE '' END					
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(EX_CODE,''))) <> '' THEN
																			SPACE(7) + '<ИсчисляемыйСтаж>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеИС>' + RTRIM(LTRIM(COALESCE(EX_CODE,''))) + '</ОснованиеИС>' + CHAR(10)
														+						CASE WHEN COALESCE(f_is_dop,'') LIKE '%Ч.%' OR COALESCE(f_is_dop,'') LIKE '%МИН.%' THEN
																				SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
														+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE(is_dop_m,0),3))) + '</Часы>' + CHAR(10)
														+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE(is_dop_d,0),3))) + '</Минуты>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																				ELSE '' END
														+						CASE WHEN COALESCE(f_is_dop,'') LIKE '%МЕС.%' OR COALESCE(f_is_dop,'') LIKE '%ДН.%' THEN
																				SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
														+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
														+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE(is_dop_m,0),3))) + '</ВсеМесяцы>' + CHAR(10)
														+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE(is_dop_d,0),3))) + '</ВсеДни>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ИсчисляемыйСтаж>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE(is_dop,''))) <> '' THEN					
														+					SPACE(7) + '<ДекретДети>' + RTRIM(LTRIM(COALESCE(is_dop,''))) + '</ДекретДети>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE(is_dop,''))) <> '' and RTRIM(LTRIM(COALESCE(is_dop,''))) <> 'НЕОПЛ'  THEN
															+ 					(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_m,0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_d,0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_m,0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_d,0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(ud_dop_k,0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_k,0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																				WHEN RTRIM(LTRIM(COALESCE(is_dop,''))) = '' THEN
																				(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_m,0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_d,0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_m,0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_d,0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(ud_dop_k,0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_k,0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																			ELSE '' END
														+			SPACE(5) + '</ОсобенностиУчета>' + CHAR(10)
														+		SPACE(4) + '</ЛьготныйСтаж>' + CHAR(10)
																	ELSE '' END
														+	SPACE(3) + '</СтажевыйПериод>'
														ELSE '' END)
													/*END*/
													ELSE '' END
													FROM #STAZH_TMP
													WHERE SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R and OT = @OT_R  AND 
																( (T_DOG = 2 AND  NOT EXISTS (SELECT *  FROM #STAZH_TMP WHERE SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R and OT = @OT_R  AND T_DOG = 1)
																			AND  EXISTS (SELECT *  FROM #STAZH_TMP WHERE SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R and OT = @OT_R  AND T_DOG = 2))
																	OR  T_DOG = 1 	)	

																						
											/*		CREATE TABLE #STAZH_TMP ( link INt, FM VARCHAR(100), IM VARCHAR(100), OT VARCHAR(100), SNILS VARCHAR(14), date1 VARCHAR(10), date2 VARCHAR(10), ter_koef NUMERIC(18,2),osob_spis VARCHAR(20), is_dop_m TINYINT, 
															is_dop_d TINYINT , is_dop VARCHAR(20), ud_dop_m INT,ud_dop_d INT  , ud_dop_k NUMERIC(18,2)) 
													INSERT INTO #STAZH_TMP  (FM, IM, OT, SNILS, date1, date2, ter_koef,osob_spis, is_dop_m, 
															is_dop_d, is_dop, ud_dop_m,ud_dop_d, ud_dop_k)
													SELECT	FM = S.FM,
															IM = S.IM,
															OT = S.OT,
															SNILS = S.PF_NUM,
															date1 = convert(varchar(10),ST.date1, 104),
															date2 = convert(varchar(10),ST.date2, 104),
															st.ter_koef,
															osob_spis = RTRIM(LTRIM(COALESCE(st.osob_k1,''))) + RTRIM(LTRIM(COALESCE(st.osob_k2,''))) + RTRIM(LTRIM(COALESCE(st.osob_k3,''))),
															is_dop_m = st.is_dop_m,
															is_dop_d = st.is_dop_d,
															is_dop = st.is_dop,
															ud_dop_m = st.ud_dop_m,
															ud_dop_d = st.ud_dop_d,
															ud_dop_k = st.ud_dop_k
													FROM dbo.SA_SZV4_SVEDENIA s 
													LEFT JOIN  dbo.SA_SZV4_STAZH st ON S.link1 = ST.link
													WHERE s.link = @LINK_DOC_OP AND  s.FM = @FM_R and s.IM = @IM_R  and s.OT = @OT_R 
														AND  s.PF_NUM= @SNILS_R 
													ORDER BY ST.date1
													
													SET @NEXT_NUM3 = 0
													UPDATE #STAZH_TMP SET @NEXT_NUM3 = @NEXT_NUM3 + 1, link = @NEXT_NUM3

													
													/*первая строка*/
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													Select @lcFNAME,
													CASE WHEN @TYPE_R <> 'ОТМЕНЯЮЩАЯ' THEN	
													/*CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' 	THEN	''
													ELSE*/	
														(CASE WHEN DATE_BEGIN1 <> '' THEN  
														+	SPACE(3) + '<СтажевыйПериод>' + CHAR(10)
														+		SPACE(4) + '<НомерСтроки>' + '1' + '</НомерСтроки>' + CHAR(10)
														+		SPACE(4) + '<ДатаНачалаПериода>' + CONVERT(VARCHAR(10),DATE_BEGIN1,104) + '</ДатаНачалаПериода>' + CHAR(10)
														+		SPACE(4) + '<ДатаКонцаПериода>' + CONVERT(VARCHAR(10),DATE_END1,104) + '</ДатаКонцаПериода>' + CHAR(10)
														+				CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE1,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE1,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE1,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop1,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE1,''))) <> '' THEN 
														+		SPACE(4) + '<КоличествоЛьготныхСоставляющих>' + CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE1,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE1,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE1,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop1,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE1,''))) <> '' THEN '1' ELSE '0' END + '</КоличествоЛьготныхСоставляющих>' + CHAR(10)		
														+		SPACE(4) + '<ЛьготныйСтаж>' + CHAR(10)
														+			SPACE(5) + '<НомерСтроки>1</НомерСтроки>' + CHAR(10)		
														+ 			SPACE(5) + '<ОсобенностиУчета>' + CHAR(10)
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE1,''))) <> '' THEN
																			SPACE(7) + '<ТерриториальныеУсловия>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеТУ>' + RTRIM(LTRIM(COALESCE(TU_CODE1,''))) + '</ОснованиеТУ>' + CHAR(10)
														+						CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE1,''))) not in ('Ч31','Ч33','Ч34','Ч35','Ч36') then
																				(CASE WHEN RTRIM(LTRIM(COALESCE(STR((SELECT ter_koef FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),4,2),''))) <> '0.00' then SPACE(8) + '<Коэффициент>' + RTRIM(LTRIM(COALESCE(STR((SELECT ter_koef FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),4,2),''))) + '</Коэффициент>' + CHAR(10) else '' end)
																				else '' end
														+ 					SPACE(7) + '</ТерриториальныеУсловия>' + CHAR(10)
																			ELSE '' END
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(OS_CODE1,''))) <> '' THEN
																			SPACE(7) + '<ОсобыеУсловияТруда>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеОУТ>' + LEFT(RTRIM(LTRIM(COALESCE(OS_CODE1,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE1,'')))) -1 )  + '</ОснованиеОУТ>' + CHAR(10)
														+						CASE WHEN LEFT(RTRIM(LTRIM(COALESCE(OS_CODE1,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE1,'')))) -1 ) = '27-1' or LEFT(RTRIM(LTRIM(COALESCE(OS_CODE1,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE1,'')))) -1 ) = '27-2' THEN
																					SPACE(8) + '<ПозицияСписка>' + UPPER(RTRIM(LTRIM(COALESCE((SELECT osob_spis FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),'')))) + '</ПозицияСписка>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ОсобыеУсловияТруда>' + CHAR(10)
																			ELSE '' END					
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(EX_CODE1,''))) <> '' THEN
																			SPACE(7) + '<ИсчисляемыйСтаж>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеИС>' + RTRIM(LTRIM(COALESCE(EX_CODE1,''))) + '</ОснованиеИС>' + CHAR(10)
														+						CASE WHEN COALESCE(f_is_dop1,'') LIKE '%Ч.%' OR COALESCE(f_is_dop1,'') LIKE '%МИН.%' THEN
																				SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
														+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</Часы>' + CHAR(10)
														+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</Минуты>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																				ELSE '' END
														+						CASE WHEN COALESCE(f_is_dop1,'') LIKE '%МЕС.%' OR COALESCE(f_is_dop1,'') LIKE '%ДН.%' THEN
																				SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
														+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
														+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</ВсеМесяцы>' + CHAR(10)
														+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</ВсеДни>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ИсчисляемыйСтаж>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),''))) <> '' THEN					
														+					SPACE(7) + '<ДекретДети>' + RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),''))) + '</ДекретДети>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),''))) <> '' and RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),''))) <> 'НЕОПЛ'  THEN
															+ 					(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE1,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE1,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop1,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop1,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop1,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop1,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																				WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),''))) = '' THEN
																				(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE1,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE1,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop1,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop1,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop1,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop1,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																			ELSE '' END
														+			SPACE(5) + '</ОсобенностиУчета>' + CHAR(10)
														+		SPACE(4) + '</ЛьготныйСтаж>' + CHAR(10)
																	ELSE '' END
														+	SPACE(3) + '</СтажевыйПериод>'
														ELSE '' END)
													/*END*/
													ELSE '' END
													FROM #RES1 r
													WHERE link = @LINK_R 	AND [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																	and CODE_STR  ='700'													

													/*вторая строка*/
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													Select @lcFNAME,
													CASE WHEN @TYPE_R <> 'ОТМЕНЯЮЩАЯ' THEN	
													/*CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' 	THEN	''
													ELSE*/	
														(CASE WHEN DATE_BEGIN2 <> '' THEN  
														+	SPACE(3) + '<СтажевыйПериод>' + CHAR(10)
														+		SPACE(4) + '<НомерСтроки>' + '2' + '</НомерСтроки>' + CHAR(10)
														+		SPACE(4) + '<ДатаНачалаПериода>' + CONVERT(VARCHAR(10),DATE_BEGIN2,104) + '</ДатаНачалаПериода>' + CHAR(10)
														+		SPACE(4) + '<ДатаКонцаПериода>' + CONVERT(VARCHAR(10),DATE_END2,104) + '</ДатаКонцаПериода>' + CHAR(10)
														+				CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE2,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE2,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE2,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop2,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE2,''))) <> '' THEN 
														+		SPACE(4) + '<КоличествоЛьготныхСоставляющих>' + CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE2,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE2,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE2,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop2,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE2,''))) <> '' THEN '1' ELSE '0' END + '</КоличествоЛьготныхСоставляющих>' + CHAR(10)		
														+		SPACE(4) + '<ЛьготныйСтаж>' + CHAR(10)
														+			SPACE(5) + '<НомерСтроки>1</НомерСтроки>' + CHAR(10)		
														+ 			SPACE(5) + '<ОсобенностиУчета>' + CHAR(10)
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE2,''))) <> '' THEN
																			SPACE(7) + '<ТерриториальныеУсловия>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеТУ>' + RTRIM(LTRIM(COALESCE(TU_CODE2,''))) + '</ОснованиеТУ>' + CHAR(10)
														+						CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE2,''))) not in ('Ч31','Ч33','Ч34','Ч35','Ч36') then
																				(CASE WHEN RTRIM(LTRIM(COALESCE(STR((SELECT ter_koef FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),4,2),''))) <> '0.00' then SPACE(8) + '<Коэффициент>' + RTRIM(LTRIM(COALESCE(STR((SELECT ter_koef FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),4,2),''))) + '</Коэффициент>' + CHAR(10) else '' end)
																				else '' end
														+ 					SPACE(7) + '</ТерриториальныеУсловия>' + CHAR(10)
																			ELSE '' END
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(OS_CODE2,''))) <> '' THEN
																			SPACE(7) + '<ОсобыеУсловияТруда>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеОУТ>' + LEFT(RTRIM(LTRIM(COALESCE(OS_CODE2,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE2,''))))  -1) + '</ОснованиеОУТ>' + CHAR(10)
														+						CASE WHEN LEFT(RTRIM(LTRIM(COALESCE(OS_CODE2,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE2,''))))  -1) = '27-1' or LEFT(RTRIM(LTRIM(COALESCE(OS_CODE2,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE2,''))))  -1) = '27-2' THEN
																					SPACE(8) + '<ПозицияСписка>' + UPPER(RTRIM(LTRIM(COALESCE((SELECT osob_spis FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),'')))) + '</ПозицияСписка>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ОсобыеУсловияТруда>' + CHAR(10)
																			ELSE '' END					
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(EX_CODE2,''))) <> '' THEN
																			SPACE(7) + '<ИсчисляемыйСтаж>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеИС>' + RTRIM(LTRIM(COALESCE(EX_CODE2,''))) + '</ОснованиеИС>' + CHAR(10)
														+						CASE WHEN COALESCE(f_is_dop2,'') LIKE '%Ч.%' OR COALESCE(f_is_dop2,'') LIKE '%МИН.%' THEN
																				SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
														+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</Часы>' + CHAR(10)
														+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</Минуты>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																				ELSE '' END
														+						CASE WHEN COALESCE(f_is_dop2,'') LIKE '%МЕС.%' OR COALESCE(f_is_dop2,'') LIKE '%ДН.%' THEN
																				SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
														+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
														+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</ВсеМесяцы>' + CHAR(10)
														+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</ВсеДни>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ИсчисляемыйСтаж>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),''))) <> '' THEN					
														+					SPACE(7) + '<ДекретДети>' + RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),''))) + '</ДекретДети>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),''))) <> '' and RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),''))) <> 'НЕОПЛ'  THEN
															+ 					(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE2,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE2,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop2,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop2,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop2,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop2,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																				WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),''))) = '' THEN
																				(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE2,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE2,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop2,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop2,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop2,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop2,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																			ELSE '' END
														+			SPACE(5) + '</ОсобенностиУчета>' + CHAR(10)
														+		SPACE(4) + '</ЛьготныйСтаж>' + CHAR(10)
																	ELSE '' END
														+	SPACE(3) + '</СтажевыйПериод>'
														ELSE '' END)
													/*END*/
													ELSE '' END
													FROM #RES1 r
													WHERE link = @LINK_R 	AND [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																	and CODE_STR  ='700'				
													
													/*третья строка*/
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													Select @lcFNAME,
													CASE WHEN @TYPE_R <> 'ОТМЕНЯЮЩАЯ' THEN	
													/*CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' 	THEN	''
													ELSE*/	
														(CASE WHEN DATE_BEGIN3 <> '' THEN  
														+	SPACE(3) + '<СтажевыйПериод>' + CHAR(10)
														+		SPACE(4) + '<НомерСтроки>' + '3' + '</НомерСтроки>' + CHAR(10)
														+		SPACE(4) + '<ДатаНачалаПериода>' + CONVERT(VARCHAR(10),DATE_BEGIN3,104) + '</ДатаНачалаПериода>' + CHAR(10)
														+		SPACE(4) + '<ДатаКонцаПериода>' + CONVERT(VARCHAR(10),DATE_END3,104) + '</ДатаКонцаПериода>' + CHAR(10)
														+				CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE3,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE3,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE3,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop3,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE3,''))) <> '' THEN 
														+		SPACE(4) + '<КоличествоЛьготныхСоставляющих>' + CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE3,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE3,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE3,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop3,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE3,''))) <> '' THEN '1' ELSE '0' END + '</КоличествоЛьготныхСоставляющих>' + CHAR(10)		
														+		SPACE(4) + '<ЛьготныйСтаж>' + CHAR(10)
														+			SPACE(5) + '<НомерСтроки>1</НомерСтроки>' + CHAR(10)		
														+ 			SPACE(5) + '<ОсобенностиУчета>' + CHAR(10)
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE3,''))) <> '' THEN
																			SPACE(7) + '<ТерриториальныеУсловия>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеТУ>' + RTRIM(LTRIM(COALESCE(TU_CODE3,''))) + '</ОснованиеТУ>' + CHAR(10)
														+						CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE3,''))) not in ('Ч31','Ч33','Ч34','Ч35','Ч36') then
																				(CASE WHEN RTRIM(LTRIM(COALESCE(STR((SELECT ter_koef FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),4,2),''))) <> '0.00' then SPACE(8) + '<Коэффициент>' + RTRIM(LTRIM(COALESCE(STR((SELECT ter_koef FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),4,2),''))) + '</Коэффициент>' + CHAR(10) else '' end)
																				else '' end
														+ 					SPACE(7) + '</ТерриториальныеУсловия>' + CHAR(10)
																			ELSE '' END
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(OS_CODE3,''))) <> '' THEN
																			SPACE(7) + '<ОсобыеУсловияТруда>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеОУТ>' + LEFT(RTRIM(LTRIM(COALESCE(OS_CODE3,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE3,''))))  -1 ) + '</ОснованиеОУТ>' + CHAR(10)
														+						CASE WHEN LEFT(RTRIM(LTRIM(COALESCE(OS_CODE3,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE3,''))))  -1 ) = '27-1' or LEFT(RTRIM(LTRIM(COALESCE(OS_CODE3,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE3,''))))  -1 ) = '27-2' THEN
																					SPACE(8) + '<ПозицияСписка>' + UPPER(RTRIM(LTRIM(COALESCE((SELECT osob_spis FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),'')))) + '</ПозицияСписка>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ОсобыеУсловияТруда>' + CHAR(10)
																			ELSE '' END					
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(EX_CODE3,''))) <> '' THEN
																			SPACE(7) + '<ИсчисляемыйСтаж>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеИС>' + RTRIM(LTRIM(COALESCE(EX_CODE3,''))) + '</ОснованиеИС>' + CHAR(10)
														+						CASE WHEN COALESCE(f_is_dop3,'') LIKE '%Ч.%' OR COALESCE(f_is_dop3,'') LIKE '%МИН.%' THEN
																				SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
														+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</Часы>' + CHAR(10)
														+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</Минуты>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																				ELSE '' END
														+						CASE WHEN COALESCE(f_is_dop3,'') LIKE '%МЕС.%' OR COALESCE(f_is_dop3,'') LIKE '%ДН.%' THEN
																				SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
														+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
														+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</ВсеМесяцы>' + CHAR(10)
														+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</ВсеДни>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ИсчисляемыйСтаж>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),''))) <> '' THEN					
														+					SPACE(7) + '<ДекретДети>' + RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),''))) + '</ДекретДети>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),''))) <> '' and RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),''))) <> 'НЕОПЛ'  THEN
															+ 					(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE3,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE3,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop3,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop3,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop3,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop3,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																				WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),''))) = '' THEN
																				(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE3,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE3,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop3,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop3,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop3,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop3,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																			ELSE '' END
														+			SPACE(5) + '</ОсобенностиУчета>' + CHAR(10)
														+		SPACE(4) + '</ЛьготныйСтаж>' + CHAR(10)
																	ELSE '' END
														+	SPACE(3) + '</СтажевыйПериод>'
														ELSE '' END ) 
													/*END*/
													ELSE '' END
													FROM #RES1 r
													WHERE link = @LINK_R 	AND [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																	and CODE_STR  ='700'	

													/*четвертая строка*/
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													Select @lcFNAME,
													CASE WHEN @TYPE_R <> 'ОТМЕНЯЮЩАЯ' THEN	
													/*CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' 	THEN	''
													ELSE*/	
														(CASE WHEN DATE_BEGIN4 <> '' THEN  
														+	SPACE(3) + '<СтажевыйПериод>' + CHAR(10)
														+		SPACE(4) + '<НомерСтроки>' + '4' + '</НомерСтроки>' + CHAR(10)
														+		SPACE(4) + '<ДатаНачалаПериода>' + CONVERT(VARCHAR(10),DATE_BEGIN4,104) + '</ДатаНачалаПериода>' + CHAR(10)
														+		SPACE(4) + '<ДатаКонцаПериода>' + CONVERT(VARCHAR(10),DATE_END4,104) + '</ДатаКонцаПериода>' + CHAR(10)
														+				CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE4,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE4,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE4,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop4,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE4,''))) <> '' THEN 
														+		SPACE(4) + '<КоличествоЛьготныхСоставляющих>' + CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE4,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE4,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE4,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop4,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE4,''))) <> '' THEN '1' ELSE '0' END + '</КоличествоЛьготныхСоставляющих>' + CHAR(10)		
														+		SPACE(4) + '<ЛьготныйСтаж>' + CHAR(10)
														+			SPACE(5) + '<НомерСтроки>1</НомерСтроки>' + CHAR(10)		
														+ 			SPACE(5) + '<ОсобенностиУчета>' + CHAR(10)
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE4,''))) <> '' THEN
																			SPACE(7) + '<ТерриториальныеУсловия>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеТУ>' + RTRIM(LTRIM(COALESCE(TU_CODE4,''))) + '</ОснованиеТУ>' + CHAR(10)
														+						CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE4,''))) not in ('Ч31','Ч33','Ч34','Ч35','Ч36') then
																				(CASE WHEN RTRIM(LTRIM(COALESCE(STR((SELECT ter_koef FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),4,2),''))) <> '0.00' then SPACE(8) + '<Коэффициент>' + RTRIM(LTRIM(COALESCE(STR((SELECT ter_koef FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),4,2),''))) + '</Коэффициент>' + CHAR(10) else '' end)
																				else '' end
														+ 					SPACE(7) + '</ТерриториальныеУсловия>' + CHAR(10)
																			ELSE '' END
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(OS_CODE4,''))) <> '' THEN
																			SPACE(7) + '<ОсобыеУсловияТруда>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеОУТ>' + LEFT(RTRIM(LTRIM(COALESCE(OS_CODE4,''))), CHARINDEX(',',RTRIM(LTRIM(COALESCE(OS_CODE4,''))))  -1 ) + '</ОснованиеОУТ>' + CHAR(10)
														+						CASE WHEN LEFT(RTRIM(LTRIM(COALESCE(OS_CODE4,''))), CHARINDEX(',',RTRIM(LTRIM(COALESCE(OS_CODE4,''))))  -1 ) = '27-1' or LEFT(RTRIM(LTRIM(COALESCE(OS_CODE4,''))), CHARINDEX(',',RTRIM(LTRIM(COALESCE(OS_CODE4,''))))  -1 ) = '27-2' THEN
																					SPACE(8) + '<ПозицияСписка>' + UPPER(RTRIM(LTRIM(COALESCE((SELECT osob_spis FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),'')))) + '</ПозицияСписка>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ОсобыеУсловияТруда>' + CHAR(10)
																			ELSE '' END					
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(EX_CODE4,''))) <> '' THEN
																			SPACE(7) + '<ИсчисляемыйСтаж>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеИС>' + RTRIM(LTRIM(COALESCE(EX_CODE4,''))) + '</ОснованиеИС>' + CHAR(10)
														+						CASE WHEN COALESCE(f_is_dop4,'') LIKE '%Ч.%' OR COALESCE(f_is_dop4,'') LIKE '%МИН.%' THEN
																				SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
														+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</Часы>' + CHAR(10)
														+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</Минуты>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																				ELSE '' END
														+						CASE WHEN COALESCE(f_is_dop4,'') LIKE '%МЕС.%' OR COALESCE(f_is_dop4,'') LIKE '%ДН.%' THEN
																				SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
														+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
														+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</ВсеМесяцы>' + CHAR(10)
														+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</ВсеДни>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ИсчисляемыйСтаж>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),''))) <> '' THEN					
														+					SPACE(7) + '<ДекретДети>' + RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),''))) + '</ДекретДети>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),''))) <> '' and RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),''))) <> 'НЕОПЛ'  THEN
															+ 					(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE4,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE4,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop4,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop4,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop4,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop4,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																				WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),''))) = '' THEN
																				(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE4,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE4,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop4,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop4,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop4,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop4,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																			ELSE '' END
														+			SPACE(5) + '</ОсобенностиУчета>' + CHAR(10)
														+		SPACE(4) + '</ЛьготныйСтаж>' + CHAR(10)
																	ELSE '' END
														+	SPACE(3) + '</СтажевыйПериод>'
														ELSE '' END ) 	
													/*END*/
													ELSE '' END
													FROM #RES1 r
													WHERE link = @LINK_R 	AND [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																	and CODE_STR  ='700'	
												*/
												DROP TABLE #STAZH_TMP
												

												INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) 
												SELECT @lcFNAME, SPACE(3) + '<ДатаЗаполнения>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),@modify_date,104),''))) + '</ДатаЗаполнения>'		

										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
										SELECT @lcFNAME,SPACE(2) + '</СВЕДЕНИЯ_О_СУММЕ_ВЫПЛАТ_И_СТРАХОВОМ_СТАЖЕ_ЗЛ>'									
							end

							FETCH NEXT FROM @Cur4 INTO @LINK_R, @TYPE_R,@SNILS_R,@PER_R,@YEAR_BEGIN_R,@PER_EDT_R,@YEAR_EDT_R, 
													@FM_R,@IM_R,@OT_R, @DATE_DOC_R/*, @FNAME_R, @NOM_PACH_R*/
						END
						CLOSE @Cur4
						DEALLOCATE @Cur4		

				------- окончание файла (Документы раздела 6 РСВ-1)
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, SPACE(1) + '</ПачкаВходящихДокументов>'
				UNION ALL SELECT @lcFNAME, SPACE(0) + '</ФайлПФР>'	
				END
			END
	end
	


	FETCH NEXT FROM @Cur3 INTO @LINK_OP, @TYP_D, @NOM_PP, @NGROUP /*Номер пачки*/,@SUM_BASE, @SUM_STR, @PERS_CNT,@DATE_DOC,@PER, @YEAR_BEGIN, @PER_EDT, @YEAR_EDT, @lcFNAME/*наименование файла*/ , @LINK_DOC_OP

	
end

CLOSE @Cur3
DEALLOCATE @Cur3


				
SET NOCOUNT OFF

select * from #OUTPUT order by [ID]
--exec SA_RSV1_EXPORT_0700_2014 41964
    


GO


GRANT EXECUTE ON dbo.[SA_RSV1_EXPORT_0700_2014] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[I_REPORT_FORMULA_P4_PREPARE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[I_REPORT_FORMULA_P4_PREPARE]

GO

CREATE PROCEDURE DBO.I_REPORT_FORMULA_P4_PREPARE
	@OUT_VAL 	VARCHAR(20) OUTPUT,
	@BDATE		DATETIME,
	@ENDDATE	DATETIME,
	@DEP_LINK	INT,
	@VARILSF	INT
AS BEGIN
	DECLARE @PEOPLE_COUNT VARCHAR(100)
	EXEC DBO.X_GET_TABLE_NAME @PEOPLE_COUNT OUTPUT
	EXEC DBO.I_REPORT_FORMULA_ERASE_TABLES 0

DECLARE @FILTER_SUBDIV_NAME VARCHAR(254), @FILTER_SUBDIV_LINK INT
DECLARE @SUBDIV TABLE (LINK INT)

SET @FILTER_SUBDIV_NAME = (SELECT DBO.RN_GET_ATR_VALUE(@VARILSF, 'REPORTS_FILTER_SUBDIV'))

IF @FILTER_SUBDIV_NAME IS NOT NULL
	SET @FILTER_SUBDIV_LINK = 
		( SELECT TOP 1 LINK FROM DBO.REPORT_KBK 
		WHERE ('№' + CONVERT(VARCHAR(3),PROPERTY) + ' - ' + NAME) = @FILTER_SUBDIV_NAME
			AND CODE_FORM='FILTER_NABOR' AND CODE='REPORTS_FILTER_SUBDIV')

DECLARE @BUFFER_SUBDIV VARCHAR(20)

IF @FILTER_SUBDIV_LINK IS NOT NULL 
BEGIN

	EXEC DBO.GETRANDSTR 20, @BUFFER_SUBDIV OUT

	INSERT INTO @SUBDIV (LINK) 
	SELECT LINK FROM DBO.RN_VIEW_FILTER WHERE LINK_SELF = @FILTER_SUBDIV_LINK

END

/**********************************************************************************************************************/
/********СРЕДНЕСПИСОЧНАЯ ЧИСЛЕННОСТЬ**********/
DECLARE @D1	DATETIME,
	@D2	DATETIME,
	@DBYEAR DATETIME

/* ДАЖЕ ЕСЛИ КВАРТАЛЬНАЯ ФОРМА, МЕСЯЧНЫЕ ДАНЫЕ БЕРУТСЯ ЗА ПОСЛЕДНИЙ МЕС. КВАРТАЛА */
SET @D1 = DBO.DATEBEGINOFMONTH (@ENDDATE) 
SET @D2 = DATEADD(MONTH,1,@D1)-1
SET @DBYEAR = DBO.DATEBEGINOFYEAR(@BDATE)

DECLARE @SALARY_OPTIONS_OPT7_1 INT 
SET @SALARY_OPTIONS_OPT7_1 =  dbo.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPT7_1')

DECLARE @NAME VARCHAR(100)

INSERT INTO DBO.BUFFER (ID, LINK)
SELECT @BUFFER_SUBDIV, LINK FROM @SUBDIV WHERE @BUFFER_SUBDIV IS NOT NULL

DECLARE @CNT INT
SET @CNT = CONVERT(NUMERIC(18,1), DBO.SA_SCH_EMPLS(@D2, @DEP_LINK, 0, 0, 0, @BUFFER_SUBDIV))


/*** НАЧАЛЬНЫЕ УСТАНОВКИ ***/
/* ТАБЛИЦА РЕЗУЛЬТАТОВ РАСЧЕТА (СТОЛБЕЦ/ЗНАЧЕНИЕ) */
CREATE  TABLE #P4_PART1(COL	INT, VAL NUMERIC(18,1), VAL_STR VARCHAR(20))

INSERT INTO #P4_PART1 (COL, VAL_STR)
SELECT TOP 1 1 AS COL, OKVED FROM dbo.DEPARTMENTS WHERE LINK = @DEP_LINK


/* ВЫЧИСЛЯЕМ ОСН. РАБОТНИКОВ */
IF @CNT > 15 
	INSERT INTO #P4_PART1 (COL, VAL) SELECT 2, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@D1, @D2, @DEP_LINK, 0, 1, 0, @BUFFER_SUBDIV))
ELSE	
	INSERT INTO #P4_PART1 (COL, VAL) SELECT 2, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@DBYEAR, @D2, @DEP_LINK, 0, 1, 0, @BUFFER_SUBDIV))

/* ВЫЧИСЛЯЕМ ВНЕШ. СОВМЕСИТЕЛЕЙ */
IF @CNT > 15 
	INSERT INTO #P4_PART1 (COL, VAL) SELECT 3, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@D1, @D2, @DEP_LINK, 0, 3, 0, @BUFFER_SUBDIV))
ELSE
	INSERT INTO #P4_PART1 (COL, VAL) SELECT 3, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@DBYEAR, @D2, @DEP_LINK, 0, 3, 0, @BUFFER_SUBDIV))


if @SALARY_OPTIONS_OPT7_1 = 1 
begin 
	update  p 
		set val = CEILING(p.val)  
	from #P4_PART1 p where p.col in (2)
end 

if @SALARY_OPTIONS_OPT7_1 = 2 
begin 
	update  p 
		set val = CEILING(p.val)  
	from #P4_PART1 p where p.col in (2,3)
end 


		
DELETE FROM DBO.BUFFER WHERE ID = @BUFFER_SUBDIV AND @BUFFER_SUBDIV IS NOT NULL	

CREATE TABLE #EMPL (LINK INT, PERS_LINK INT, DEP_LINK INT, [STATUS] TINYINT, PERIOD_BEG DATETIME, PERIOD_END DATETIME)
INSERT INTO #EMPL
SELECT 
	EMPL_LINK, PERS_LINK, DEP_LINK, [STATUS], PERIOD_BEG, PERIOD_END 
FROM 
	DBO.SA_EMPLS_INFO_PERIOD(@D1, @D2, DEFAULT, @DEP_LINK)
WHERE 
	(
	@BUFFER_SUBDIV IS NULL 
		OR 
	@BUFFER_SUBDIV IS NOT NULL AND SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
	)
ORDER BY 
	DEP_LINK, EMPL_LINK

CREATE TABLE #EMPL1 (LINK INT, PERS_LINK INT, DEP_LINK INT, [STATUS] TINYINT, PERIOD_BEG DATETIME, PERIOD_END DATETIME)
INSERT INTO #EMPL1
SELECT 
	EMPL_LINK, PERS_LINK, DEP_LINK, [STATUS], PERIOD_BEG, PERIOD_END 
FROM 
	DBO.SA_EMPLS_INFO_PERIOD(@BDATE, @D2, DEFAULT, @DEP_LINK)
WHERE 
	(
	@BUFFER_SUBDIV IS NULL 
		OR 
	@BUFFER_SUBDIV IS NOT NULL AND SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
	)
ORDER BY 
	DEP_LINK, EMPL_LINK

--ПОДКОРРЕКТИРУЕМ КОНЕЧНУЮ ДАТУ ДЛЯ ТЕХ, КТО ПЕРЕВОДИЛСЯ, ДЛЯ ТОГО ЧТОБЫ ОПРЕДЕЛИТЬ СУММЫ НАЧИСЛЕНИЙ, НАЧИСЛЕННЫХ ПОСЛЕ ДАТЫ ИХ УВОЛЬНЕНИЯ
UPDATE E
SET E.PERIOD_END = @D2
FROM 
	#EMPL E
	INNER JOIN (SELECT LINK, MAX_PERIOD_END = MAX(PERIOD_END) FROM  #EMPL E1 GROUP BY LINK HAVING COUNT(*) > 1) A 
		ON E.LINK = A.LINK AND E.PERIOD_END = A.MAX_PERIOD_END
WHERE
	A.MAX_PERIOD_END < @D2

--ПОДКОРРЕКТИРУЕМ КОНЕЧНУЮ ДАТУ ДЛЯ ТЕХ, КТО ПЕРЕВОДИЛСЯ, ДЛЯ ТОГО ЧТОБЫ ОПРЕДЕЛИТЬ СУММЫ НАЧИСЛЕНИЙ, НАЧИСЛЕННЫХ ПОСЛЕ ДАТЫ ИХ УВОЛЬНЕНИЯ
UPDATE E
SET E.PERIOD_END = @D2
FROM 
	#EMPL1 E
	INNER JOIN (SELECT LINK, MAX_PERIOD_END = MAX(PERIOD_END) FROM  #EMPL1 E1 GROUP BY LINK HAVING COUNT(*) > 1) A 
		ON E.LINK = A.LINK AND E.PERIOD_END = A.MAX_PERIOD_END
WHERE
	A.MAX_PERIOD_END < @D2		

/* ДОГОВОРНИКИ */
DECLARE @M NUMERIC(18,2) 

IF @CNT > 15
	SELECT --За месяц
		@M=SUM(CASE 
			WHEN DGH.DATE1<=@D1 AND COALESCE(DGH.DATE2,@D2)>=@D2 THEN DATEDIFF(DAY,@D1,@D2)		-- РАБОТАЛ ВЕСЬ ПЕРИОД
			WHEN DGH.DATE1<=@D1 AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE2>@D1 THEN DATEDIFF(DAY,@D1,DGH.DATE2)+1	-- УВОЛЕН В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@D1  AND COALESCE(DGH.DATE2,@D2)>=@D2 AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,@D2) 		-- ПРИНЯТ В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@D1  AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,DGH.DATE2)+1	-- ПРИНЯТ И УВОЛЕН В РАБОЧИЙ ПЕРИОД
			 ELSE 0
		END)
	FROM 
		dbo.REESTR_DGH DGH
	WHERE
			DEP_LINK = @DEP_LINK 
		AND
			DGH.DATE1 <= @D2 AND DGH.DATE2 >= @D1
		AND
		NOT EXISTS (
			SELECT E.PERS_LINK FROM DBO.SD_EMPL_FN(DEFAULT,@D2,DEFAULT,@DEP_LINK) E
			WHERE DGH.PERS_LINK = E.PERS_LINK AND DGH.DATE1 <= ISNULL(E.DATE_END,ISNULL(DGH.DATE2,@D2)) AND ISNULL(DGH.DATE2,@D2) >= E.DATE_BEGIN 
			)
ELSE
	SELECT --С начала года
		@M=SUM(CASE 
			WHEN DGH.DATE1<=@DBYEAR AND COALESCE(DGH.DATE2,@D2)>=@D2 THEN DATEDIFF(DAY,@DBYEAR,@D2)		-- РАБОТАЛ ВЕСЬ ПЕРИОД
			WHEN DGH.DATE1<=@DBYEAR AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE2>@DBYEAR THEN DATEDIFF(DAY,@DBYEAR,DGH.DATE2)+1	-- УВОЛЕН В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@DBYEAR  AND COALESCE(DGH.DATE2,@D2)>=@D2 AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,@D2) 		-- ПРИНЯТ В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@DBYEAR  AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,DGH.DATE2)+1	-- ПРИНЯТ И УВОЛЕН В РАБОЧИЙ ПЕРИОД
			 ELSE 0
		END)
	FROM 
		dbo.REESTR_DGH DGH
	WHERE
			DEP_LINK = @DEP_LINK 
		AND
			DGH.DATE1 <= @D2 AND DGH.DATE2 >= @DBYEAR
		AND
		NOT EXISTS (
			SELECT E.PERS_LINK FROM DBO.SD_EMPL_FN(DEFAULT,@D2,DEFAULT,@DEP_LINK) E
			WHERE DGH.PERS_LINK = E.PERS_LINK AND DGH.DATE1 <= ISNULL(E.DATE_END,ISNULL(DGH.DATE2,@D2)) AND ISNULL(DGH.DATE2,@D2) >= E.DATE_BEGIN 
			)				

DECLARE	@NDAYSFEBR	INT
IF @CNT > 15
	SET @NDAYSFEBR = DAY(DBO.DATEENDOFMONTH(@D1))
ELSE
	SET @NDAYSFEBR = ISNULL((SELECT SUM(DAY(DBO.DATEENDOFMONTH(DATE_BEGIN))) FROM dbo.MONTHS_EX(@DBYEAR, @D2)),99999999)

INSERT INTO #P4_PART1 (COL, VAL)
SELECT 4 AS COL, @M/@NDAYSFEBR

if @SALARY_OPTIONS_OPT7_1 = 1 
begin 
	update  p 
		set val = ROUND(p.val,0) 
	from #P4_PART1 p where p.col = 4
end 

if @SALARY_OPTIONS_OPT7_1 = 2 
begin 
	update  p 
		set val = CEILING(p.val)  
	from #P4_PART1 p where p.col =4
end 


/*
declare @a float 
set @a = '' 
 exec I_REPORT_FORMULA_P4_PREPARE @a output, '20130101' , '20131231' ,74578 ,  39348 
 */
---- ВСЕГО (СУММА ГРАФ 2,3,4)
--INSERT INTO #P4_PART1
--SELECT 1 AS COL, SUM(VAL) FROM #P4_PART1 WHERE COL > 1

/* КОЛ-ВО ОТРАБОТ. ЧАСОВ */
DECLARE @ISMINUTES TINYINT
SET @ISMINUTES = DBO.SA_GET_OPTION_BY_CODE('TABEL_OPT10') --УЧЕТ ВРЕМЕНИ В ЧАСАХ И МИНУТАХ

/*КОЛИЧЕСТВО ОТРАБОТАННЫХ ЧЕЛОВЕКО-ЧАСОВ С НАЧАЛА ГОДА РАБОТНИКАМИ СПИСОЧНОГО СОСТАВА*/
INSERT INTO #P4_PART1 (COL, VAL)
SELECT [STATUS],  DBO.MINUTES_TO_NUM(SUM(DBO.NUM_TO_MINUTES([HOURS],@ISMINUTES)),@ISMINUTES)
FROM
(
	SELECT 
		[STATUS] = (CASE WHEN F.[STATUS] <> 3 THEN 5 ELSE 6 END),
		[HOURS] = DBO.SA_GET_EMPL_WH(LINK, DEFAULT,DEFAULT,PERIOD_BEG,PERIOD_END,DEFAULT,DEFAULT) 
	FROM 
		#EMPL1 F
) A
GROUP BY [STATUS]

-- очистка лишних задвоений для тех у кого перевод, и дальнейшая работа происходила в течении месяца
delete FROM 
	#EMPL1 
WHERE
	LINK in (SELECT LINK FROM  #EMPL1 E1 GROUP BY LINK HAVING COUNT(*) > 1 ) 
	AND PERIOD_END not in (SELECT min(PERIOD_END) FROM  #EMPL1 E1 GROUP BY LINK HAVING COUNT(*) > 1 /*and  min(PERIOD_END) = @D2*/ ) 

/* ФОНД НАЧИСЛ З/ПЛАТЫ */
CREATE  TABLE #P4_S_J_C (SUMMA NUMERIC(20,1), STAT_OTCHET TINYINT, DEP_TYPE TINYINT, COL TINYINT, PERIOD_END DATETIME)

DECLARE @LINKEKR213 INT
SELECT @LINKEKR213 = LINK FROM DBO.DICTIONARY_ITEM WHERE CODE = '213'



CREATE TABLE #CJ (PERS_LINK INT, LINK_EMPL INT, LINK_PAYS INT, PERIOD_END DATETIME, SUMMA NUMERIC(18,2), STAT_OTCHET TINYINT, WAY_CALC TINYINT, DEP_TYPE TINYINT)

INSERT INTO #CJ (PERS_LINK, LINK_EMPL, LINK_PAYS, PERIOD_END, SUMMA, STAT_OTCHET, WAY_CALC, DEP_TYPE)
SELECT 
	PERS_LINK, LINK_EMPL, LINK_PAYS, 
	JC.PERIOD_BEGIN , 
	SUMMA, STAT_OTCHET, WAY_CALC,
	CASE WHEN PERS_LINK IS NULL THEN 0 ELSE 5 END /* 5 - ФИЗ ЛИЦО */
FROM
	DBO.CALCULATE_JURNAL JC 
	INNER JOIN DBO.PAYS P ON JC.LINK_PAYS = P.LINK 
WHERE
	P.[OBJECT] = 1 /* ТОЛЬКО НАЧИСЛЕНИЯ */
	AND (P.WAY_CALC <> 15 AND YEAR(JC.PERIOD_BEGIN)=  YEAR(@D1) AND MONTH(JC.PERIOD_BEGIN) <= MONTH(@D1)
 		OR P.WAY_CALC = 15 AND YEAR(JC.PERIOD_BEGIN)=  YEAR(@D1) AND MONTH(JC.PERIOD_BEGIN) <= MONTH(@D1))	
	AND P.STAT_OTCHET <> 3
	AND JC.LINK_DEP = @DEP_LINK

----------- суммы договорников, которые являются сотрудниками помеячаем считать как для сотрудников
UPDATE J
SET LINK_EMPL = E.LINK, DEP_TYPE = 0
FROM #CJ J INNER JOIN #EMPL E ON E.PERS_LINK = J.PERS_LINK AND J.[PERIOD_END] BETWEEN E.PERIOD_BEG AND E.PERIOD_END
		

------------
INSERT INTO #P4_S_J_C 
SELECT SUMMA, STAT_OTCHET, DEP_TYPE, COALESCE(F.COL,0), J.[PERIOD_END]
FROM #CJ J INNER JOIN (SELECT LINK, (CASE WHEN STATUS=3 THEN 9 ELSE 8 END) AS COL, PERIOD_BEG, PERIOD_END FROM #EMPL1) F 
		ON J.LINK_EMPL = F.LINK AND YEAR(J.[PERIOD_END]) * 100 + MONTH(J.[PERIOD_END]) 
				BETWEEN YEAR(F.PERIOD_BEG) * 100 + MONTH(F.PERIOD_BEG) AND YEAR(F.PERIOD_END) * 100 + MONTH(F.PERIOD_END)

------------		
INSERT INTO #P4_S_J_C
SELECT SUMMA, STAT_OTCHET, DEP_TYPE, 0, PERIOD_END
FROM #CJ WHERE LINK_EMPL IS NULL


	/* COL8! */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 8, SUM(SUMMA)/1000 FROM #P4_S_J_C
		WHERE COL=8 AND STAT_OTCHET=1 AND DEP_TYPE<>5
			AND  
			(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)

	/* COL9! */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 9, SUM(SUMMA)/1000 FROM #P4_S_J_C
		WHERE COL=9 AND STAT_OTCHET=1 AND DEP_TYPE<>5
			AND 
			(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)

	/* COL10! */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 10, SUM(SUMMA)/1000 FROM #P4_S_J_C
		WHERE STAT_OTCHET=1 AND DEP_TYPE=5
			AND 
			(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)
	/* COL11! С НАЧАЛА ГОДА ЗА I КВАРТАЛ, I ПОЛУГОДИЕ, 9 МЕСЯЦЕВ, ГОД */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 11, SUM(SUMMA)/1000 FROM #P4_S_J_C
			WHERE STAT_OTCHET=2 -- СОЦВЫПЛАТЫ
				AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				--AND MONTH(@ENDDATE) % 3 = 0


/* РАЗД. 3 - ДВИЖЕНИЕ РАБОТНИКОВ */
	/* ROW 21 */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 21, COUNT(*) FROM ITEM_MOVE I LEFT JOIN #EMPL1 DF ON I.EMPL_LINK = DF.LINK AND I.DATE_BEGIN BETWEEN DF.PERIOD_BEG AND DF.PERIOD_END
			WHERE DF.DEP_LINK = @DEP_LINK
				AND NEW_FACE = 1
				AND I.DATE_BEGIN >= @DBYEAR AND I.DATE_BEGIN <= @ENDDATE

	/* ROW 22 */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 22, COUNT(*) FROM ITEM_MOVE I LEFT JOIN #EMPL1 DF ON I.EMPL_LINK = DF.LINK AND I.DATE_BEGIN BETWEEN DF.PERIOD_BEG AND DF.PERIOD_END
			WHERE DF.DEP_LINK = @DEP_LINK 
				AND NEW_FACE = 1
				AND I.DATE_BEGIN >= @DBYEAR AND I.DATE_BEGIN <= @ENDDATE
				AND I.STAFF_LINK IN ( SELECT LINK_UP FROM STAFF WHERE DATE_BEGIN >= @DBYEAR)

	/* ROW 23 */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 23, COUNT(*) FROM ITEM_DIS_FACE I LEFT JOIN #EMPL1 DF ON I.EMPL_LINK = DF.LINK AND I.DIS_DATE BETWEEN DF.PERIOD_BEG AND DF.PERIOD_END
			WHERE DF.DEP_LINK = @DEP_LINK
				AND DIS_DATE >= @DBYEAR AND DIS_DATE <= @ENDDATE

	/* ROW 24 */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 24, COUNT(*) FROM ITEM_DIS_FACE I LEFT JOIN #EMPL DF ON I.EMPL_LINK = DF.LINK AND I.DIS_DATE BETWEEN DF.PERIOD_BEG AND DF.PERIOD_END
			WHERE DF.DEP_LINK = @DEP_LINK 
				AND DIS_DATE >= @DBYEAR AND DIS_DATE <= @ENDDATE
				AND REASON IN (SELECT LINK FROM DICTIONARY_PUV WHERE CODE = '0402')
	
	/* ROW 26 */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 26, COUNT(*) 
		FROM 
			DBO.ITEM_DIS_FACE I 
			INNER JOIN DBO.DICTIONARY_PUV DP ON DP.LINK = I.REASON
			LEFT JOIN #EMPL1 DF ON I.EMPL_LINK = DF.LINK AND I.DIS_DATE BETWEEN DF.PERIOD_BEG AND DF.PERIOD_END
		WHERE DF.DEP_LINK = @DEP_LINK 
				AND DIS_DATE >= @DBYEAR AND DIS_DATE <= @ENDDATE
				AND DP.CODE IN ('0300','0707','2030','2016','0000')
	
	/* ROW 27 */
	INSERT INTO #P4_PART1 (COL, VAL) 
	SELECT 27, @CNT

	--СВОБОДНЫЕ СТАВКИ
	INSERT INTO #P4_PART1 (COL, VAL)
	SELECT 28, SUM(S.FREE_STAKES)
	FROM DBO.DICTIONARY_STAFF_FN(@ENDDATE) S 
		INNER JOIN DBO.DICTIONARY_SUBDIVISION_FN(@ENDDATE) D ON D.LINK = S.SUBDIV_LINK
	WHERE 
		S.DELETED = 0 AND S.DEP_LINK = @DEP_LINK
		AND D.DELETED = 0
		AND (
				@BUFFER_SUBDIV IS NULL
				OR
				@BUFFER_SUBDIV IS NOT NULL AND S.SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
			)				
--select * from #P4_PART1
DROP TABLE #P4_S_J_C

/**********************************************************************************************************************/
/* СОЗДАЕМ ВРЕМЕНННУЮ ТАБЛИЦУ */
DECLARE @RESULT_TABLE VARCHAR(100)
EXEC DBO.X_GET_TABLE_NAME @RESULT_TABLE OUTPUT

EXEC DBO.I_REPORT_FORMULA_ERASE_TABLES 0
EXEC ('SELECT * INTO ' + @RESULT_TABLE + ' FROM #P4_PART1 ')
EXEC DBO.BUFFERPUSH -151, @RESULT_TABLE
	SET @OUT_VAL = ''
DROP TABLE #P4_PART1
END










GO


GRANT EXECUTE ON dbo.[I_REPORT_FORMULA_P4_PREPARE] TO PUBLIC

GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FB_SVOD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FB_SVOD]
GO






CREATE	PROCEDURE FB_SVOD
	@varKSintFyear 	 int,
	@varKScObjSCode   char(100), 
	@varKSintPer_num int = 0,
	@varKSintRBS_Acc int,
	@varKSdDate	 datetime
	
AS
DECLARE	@varKSintObjLink	INT,
	@varKScObjCode   char(100), 
	@varKSnSummaType numeric(5,3),
	@varKSintTypePer	INT
DECLARE @varKSResTable TABLE
		(vkr	[int] NULL,
		 ekr	[int] NULL, 
		 dop_cl	[int] NULL, 
		 reg	[int] NULL, 
		 P1	[numeric](28, 2) NULL,
		 P2	[numeric](28, 2) NULL,
		 P3	[numeric](28, 2) NULL,
		 P4	[numeric](28, 2) NULL,
		 P5	[numeric](28, 2) NULL,
		 P6	[numeric](28, 2) NULL,
		 P7	[numeric](28, 2) NULL,
		 P8	[numeric](28, 2) NULL,
		 P9	[numeric](28, 2) NULL,
		 P10	[numeric](28, 2) NULL,
		 P11	[numeric](28, 2) NULL,
		 P12	[numeric](28, 2) NULL,
		 Y2	[numeric](28, 2) NULL,
		 Y3	[numeric](28, 2) NULL)

select @varKSintObjLink = link from s_objects where code = replace(@varKScObjSCode,'_SVOD','')
IF @varKScObjCode like '%_ASSIGN%'
BEGIN
	SELECT @varKSnSummaType = (case isnull(UM,1) when 1 then 1 else 0.001 end) FROM FINANS_ASSIGN_OPTIONS
	SELECT @varKSintTypePer = max(FIN_SMETA_PER)  FROM dbo.WORKMODE 
END
ELSE
BEGIN	
	SELECT @varKSnSummaType = (case isnull(UM,1) when 1 then 1 else 0.001 end) FROM FINANS_LIMIT_OPTIONS
	SELECT @varKSintTypePer = max(FIN_LIM_PER) + 10 * max(FIN_LIM_TYPE)  FROM dbo.WORKMODE 
END

INSERT INTO @varKSResTable
select F.VKR, F.EKR, F.DOP_CL, F.REG,
	F.P1 - isnull(FS.P1,0) as P1, 
	F.P2 - isnull(FS.P2,0) as P2, 
	F.P3 - isnull(FS.P3,0) as P3,  
	F.P4 - isnull(FS.P4,0) as P4,  
	F.P5 - isnull(FS.P5,0) as P5,  
	F.P6 - isnull(FS.P6,0) as P6,  
	F.P7 - isnull(FS.P7,0) as P7,  
	F.P8 - isnull(FS.P8,0) as P8,  
	F.P9 - isnull(FS.P9,0) as P9,  
	F.P10 - isnull(FS.P10,0) as P10,  
	F.P11 - isnull(FS.P11,0) as P11,  
	F.P12 - isnull(FS.P12,0) as P12, 
	F.Y2 - isnull(FS.Y2,0) as Y2, 
	F.Y3 - isnull(FS.Y3,0) as Y3

from (SELECT F.VKR, F.EKR, F.DOP_CL, F.REG,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 1) or (@varKSintTypePer = 13 and @varKSintPer_num = 1)) then sum(F.p1) * @varKSnSummaType else 0 end) as p1,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 1) or (@varKSintTypePer = 13 and @varKSintPer_num = 2)) then sum(F.p2) * @varKSnSummaType else 0 end) as p2,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 1) or (@varKSintTypePer = 13 and @varKSintPer_num = 3)) then sum(F.p3) * @varKSnSummaType else 0 end) as p3,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 4) or (@varKSintTypePer = 13 and @varKSintPer_num = 4)) then sum(F.p4) * @varKSnSummaType else 0 end) as p4,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 4) or (@varKSintTypePer = 13 and @varKSintPer_num = 5)) then sum(F.p5) * @varKSnSummaType else 0 end) as p5,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 4) or (@varKSintTypePer = 13 and @varKSintPer_num = 6)) then sum(F.p6) * @varKSnSummaType else 0 end) as p6,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 7) or (@varKSintTypePer = 13 and @varKSintPer_num = 7)) then sum(F.p7) * @varKSnSummaType else 0 end) as p7,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 7) or (@varKSintTypePer = 13 and @varKSintPer_num = 8)) then sum(F.p8) * @varKSnSummaType else 0 end) as p8,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 7) or (@varKSintTypePer = 13 and @varKSintPer_num = 9)) then sum(F.p9) * @varKSnSummaType else 0 end)as p9,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 10) or (@varKSintTypePer = 13 and @varKSintPer_num = 10)) then sum(F.p10) * @varKSnSummaType else 0 end) as p10,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 10) or (@varKSintTypePer = 13 and @varKSintPer_num = 11)) then sum(F.p11) * @varKSnSummaType else 0 end) as p11,
	(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 10) or (@varKSintTypePer = 13 and @varKSintPer_num = 12)) then sum(F.p12) * @varKSnSummaType else 0 end) as p12,
	sum(F.Y2) * @varKSnSummaType as y2,
	sum(F.Y3) * @varKSnSummaType as y3
from FINANSE F 
INNER JOIN g_pROV GP ON F.LINK_UP = GP.LINK and 
				GP.DATE_PROV is not null and 
				GP.OBJECT = @varKSintObjLink AND 
				GP.ACC = @varKSintRBS_Acc
INNER JOIN FINANSE_HEAD FH ON FH.LINK = GP.LINK and 
				FH.FYEAR = @varKSintFyear and 
				(FH.PER_NUM = @varKSintPer_num or @varKSintPer_num = 0) 
INNER JOIN DEPARTMENT_ACCOUNTS DA ON FH.ACCOUNT = DA.LINK and (DA.type = 2 or @varKScObjCode like '%_ASSIGN%')
WHERE F.vkr IS NOT NULL AND F.ekr IS NOT NULL
GROUP BY F.VKR, F.EKR, F.DOP_CL, F.REG) F
left join dbo.FB_REST_FINANS(@varKSintFyear, @varKSdDate, @varKSintPer_num, @varKSnSummaType,0, @varKScObjSCode, @varKSintTypePer, DEFAULT, DEFAULT) FS on FS.RBS_ACC = @varKSintRBS_Acc and 
																		  FS.VKR = F.VKR and
																		  FS.EKR = F.EKR and
																		 (FS.DOP_CL = F.DOP_CL or FS.DOP_CL is null and F.DOP_CL is null)

IF @varKSintTypePer = 1 or @varKSintTypePer > 10
	UPDATE @varKSResTable
		SET p1 = p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9 + p10 + p11 + p12,
		p2 = 0,	p3 = 0,	p4 = 0,	p5 = 0,	p6 = 0,	p7 = 0,	p8 = 0,	p9 = 0,	p10 = 0, p11 = 0, p12 = 0
IF @varKSintTypePer = 2
	UPDATE @varKSResTable
		SET p1 = p1 + p2 + p3, p2 = 0, p3 = 0,
		p4 = p4 + p5 + p6, p5 = 0, p6 = 0,
		p7 = p7 + p8 + p9, p8 = 0, p9 = 0,
		p10 = p10 + p11 + p12, p11 = 0, p12 = 0


SELECT F1.*, (p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9 + p10 + p11 + p12) * @varKSnSummaType as itog, 
	KBK.CODE   AS VKR_CODE, 
	KBK.NAME   AS VKR_NAME,  
	EKR.CODE   AS EKR_CODE, 
	EKR.NAME   AS EKR_NAME, 
	DCL.CODE   AS DOP_CL_CODE,
	DCL.NAME   AS DOP_CL_NAME,
	REG.CODE   AS REG_CODE,
	REG.NAME   AS REG_NAME
from @varKSResTable  F1
LEFT JOIN KL_KBK KBK ON F1.VKR = KBK.LINK
LEFT JOIN DICTIONARY_ITEM EKR ON F1.EKR = EKR.LINK 
left outer JOIN dbo.DOP_CLASSIF DCL ON DCL.LINK = F1.DOP_CL
left outer JOIN dbo.KL_REG REG ON REG.LINK = F1.REG
where p1 <> 0 or p2 <> 0 or p3 <> 0 or p4 <> 0 or p5 <> 0 or p6 <> 0 or
	p7 <> 0 or p8 <> 0 or p9 <> 0 or p10 <> 0 or p11 <> 0 or p12 <> 0 or Y2 <> 0 or Y3 <> 0



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_NZP_PREPARE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_NZP_PREPARE]

GO

CREATE PROCEDURE DBO.SA_NZP_PREPARE
	@OUT_VAL 	VARCHAR(20) OUTPUT,
	@BDATE		DATETIME,
	@ENDDATE	DATETIME,
	@DEP_LINK	INT,
	@VARILSF	INT
AS BEGIN
	DECLARE @PEOPLE_COUNT VARCHAR(100)
	EXEC DBO.X_GET_TABLE_NAME @PEOPLE_COUNT OUTPUT
	EXEC DBO.I_REPORT_FORMULA_ERASE_TABLES 0

DECLARE @FILTER_SUBDIV_NAME VARCHAR(254), @FILTER_SUBDIV_LINK INT
DECLARE @SUBDIV TABLE (LINK INT)

SET @FILTER_SUBDIV_NAME = (SELECT DBO.RN_GET_ATR_VALUE(@VARILSF, 'REPORTS_FILTER_SUBDIV'))


IF @FILTER_SUBDIV_NAME IS NOT NULL
	SET @FILTER_SUBDIV_LINK = 
		( SELECT TOP 1 LINK FROM DBO.REPORT_KBK 
		WHERE ('№' + CONVERT(VARCHAR(3),PROPERTY) + ' - ' + NAME) = @FILTER_SUBDIV_NAME
			AND CODE_FORM='FILTER_NABOR' AND CODE='REPORTS_FILTER_SUBDIV')


DECLARE @BUFFER_SUBDIV VARCHAR(20)

IF @FILTER_SUBDIV_LINK IS NOT NULL 
BEGIN

	EXEC DBO.GETRANDSTR 20, @BUFFER_SUBDIV OUT

	INSERT INTO @SUBDIV (LINK) 
	SELECT LINK FROM DBO.RN_VIEW_FILTER WHERE LINK_SELF = @FILTER_SUBDIV_LINK

END

DECLARE @ATR_INCR_ITOG TINYINT
SET @ATR_INCR_ITOG = (case when (SELECT DBO.RN_GET_ATR_VALUE(@VARILSF, 'REPORTS_ATR_INCR_ITOG')) = 'НЕТ' THEN 2 ELSE 1 END)



/**********************************************************************************************************************/
/********СРЕДНЕСПИСОЧНАЯ ЧИСЛЕННОСТЬ**********/
DECLARE @D1	DATETIME,
	@D2	DATETIME,
	@DBYEAR DATETIME

/* ДАЖЕ ЕСЛИ КВАРТАЛЬНАЯ ФОРМА, МЕСЯЧНЫЕ ДАНЫЕ БЕРУТСЯ ЗА ПОСЛЕДНИЙ МЕС. КВАРТАЛА */
SET @D1 = DBO.DATEBEGINOFMONTH (@ENDDATE) 
SET @D2 = DATEADD(MONTH,1,@D1)-1
SET @DBYEAR = DBO.DATEBEGINOFYEAR(@BDATE)

DECLARE @SALARY_OPTIONS_OPT8_1 INT 
SET @SALARY_OPTIONS_OPT8_1 =  dbo.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPT8_1')

DECLARE @NAME VARCHAR(100)

INSERT INTO DBO.BUFFER (ID, LINK)
SELECT @BUFFER_SUBDIV, LINK FROM @SUBDIV WHERE @BUFFER_SUBDIV IS NOT NULL

DECLARE @CNT INT
SET @CNT = CONVERT(NUMERIC(18,1), DBO.SA_SCH_EMPLS(@D2, @DEP_LINK, 0, 0, 0, @BUFFER_SUBDIV))

DECLARE @CODE_FORM varchar(10)
SET @CODE_FORM  = (select top 1 Ltrim(code) from RN_REPORT_SAVED_FORMS_ARH where link_SAVED_form = @VARILSF)

/*** НАЧАЛЬНЫЕ УСТАНОВКИ ***/
/* ТАБЛИЦА РЕЗУЛЬТАТОВ РАСЧЕТА (СТОЛБЕЦ/ЗНАЧЕНИЕ) */
CREATE  TABLE #NZP_PART1(CODE_STR VARCHAR(10) , COL	INT, VAL NUMERIC(18,2), VAL_STR VARCHAR(20))

/*********************************************************************************************/
--- Таблица категорий для формы
CREATE TABLE #CAT_CODES (link int, code varchar (10), name_cat varchar (256) )
declare @STR varchar(8000),
		@SPHERE tinyint 
	set @STR  = ' insert #CAT_CODES
					select link , code, name_cat
					from PERS_CATEGORY_BY_SPHERE 
				 where '

	set @STR  =  @STR  + CASE when @CODE_FORM = '0606045'  then ' ZDRAV = 1' 
						  when @CODE_FORM = '0606046'  then ' KULT = 1' 
						  when @CODE_FORM = '0606047'  then ' SCIENCE = 1' 
						  when @CODE_FORM = '0606048'  then ' EDUC = 1'
						  when @CODE_FORM = '0606049'  then ' SOC = 1' end
	exec(@str)

	--- Определим сферу деятельности
	SET @SPHERE = CASE WHEN @CODE_FORM = '0606045' then  (select link from STO_SPHERES where NAME = 'Медицина')
					   WHEN @CODE_FORM = '0606046' then  (select link from STO_SPHERES where NAME = 'Культура')
					   WHEN @CODE_FORM = '0606047' then  (select link from STO_SPHERES where NAME = 'Наука')
					   WHEN @CODE_FORM = '0606048' then  (select link from STO_SPHERES where NAME = 'Образование')
					   WHEN @CODE_FORM = '0606049' then  (select link from STO_SPHERES where NAME = 'Социальная сфера') end 

--- Обновим одинаковые коды в зависимости от наименования категории
update #CAT_CODES
	set code = '3011'
	where code = '301' and name_cat = 'Научные работники учреждений ВПО'
update #CAT_CODES
	set code = '3012'
	where code = '301' and name_cat = 'Научные работники учреждений дополнительного профессионального образования'	
update #CAT_CODES
	set code = '3013'
	where code = '301' and name_cat = 'Научные работники'	
update #CAT_CODES
	set code = '3014'
	where code = '301' and name_cat = 'научные работники (исследователи)'	
update #CAT_CODES
	set code = '3111'
	where code = '311' and name_cat = 'Научные сотрудники (ВПО)'	
update #CAT_CODES
	set code = '3112'
	where code = '311' and name_cat = 'Научные сотрудники (ДПО)'	
update #CAT_CODES
	set code = '3113'
	where code = '311' and name_cat = 'Научные сотрудники '	


-- КОД КАТЕГОРИИ '100' - ВСЕГО  
/* ВЫЧИСЛЯЕМ ОСН. РАБОТНИКОВ */
--- Списочность считаем с начала года 
IF @ATR_INCR_ITOG =2 
	INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT '100', 4, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@D1, @D2, @DEP_LINK, 0, 1, 0, @BUFFER_SUBDIV))
ELSE	
	INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT '100', 4, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@DBYEAR, @D2, @DEP_LINK, 0, 1, 0, @BUFFER_SUBDIV))

/* ВЫЧИСЛЯЕМ ВНЕШ. СОВМЕСИТЕЛЕЙ */
IF @ATR_INCR_ITOG =2 
	INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT '100', 5, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@D1, @D2, @DEP_LINK, 0, 3, 0, @BUFFER_SUBDIV))
ELSE
	INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT '100', 5, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@DBYEAR, @D2, @DEP_LINK, 0, 3, 0, @BUFFER_SUBDIV))



CREATE TABLE #ssch_empls_nzp_ALL(SSCH NUMERIC(18,6), CAT_NZP_LINK INT,CODE VARCHAR(4),SPHERE_LINK int,[STATUS] TINYINT,NAME_CAT VARCHAR(254),STAFF_HEAD int) 
IF @ATR_INCR_ITOG =2 
	INSERT INTO #ssch_empls_nzp_ALL(SSCH, CAT_NZP_LINK,CODE,SPHERE_LINK,[STATUS],NAME_CAT,STAFF_HEAD) 
	SELECT SSCH, CAT_NZP_LINK,CODE,SPHERE_LINK,[STATUS],NAME_CAT,STAFF_HEAD
	FROM sa_ssch_empls_nzp_ALL(@DBYEAR, @D2, @DEP_LINK, @BUFFER_SUBDIV)
ELSE
	INSERT INTO #ssch_empls_nzp_ALL(SSCH, CAT_NZP_LINK,CODE,SPHERE_LINK,[STATUS],NAME_CAT,STAFF_HEAD) 
	SELECT SSCH, CAT_NZP_LINK,CODE,SPHERE_LINK,[STATUS],NAME_CAT,STAFF_HEAD
	FROM sa_ssch_empls_nzp_ALL(@D1, @D2, @DEP_LINK, @BUFFER_SUBDIV)

/* Разбивка по категориям */
DECLARE @Cur1 CURSOR, @LINK_CAT INT , @CODE_CAT varchar(10), @NAME_CAT varchar(254)
SET @Cur1 = CURSOR FORWARD_ONLY

FOR SELECT LINK, CODE, NAME_CAT FROM #CAT_CODES order by link

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @LINK_CAT, @CODE_CAT, @NAME_CAT
WHILE (@@fetch_status <> -1)
BEGIN

	IF (@@fetch_status <> -2)
	BEGIN
		
		SET @CODE_CAT = LTRIM(@CODE_CAT)
		SET @NAME_CAT = LTRIM(@NAME_CAT)
		
		IF @CODE_CAT like ('%301%') 
		BEGIN
			/* ВЫЧИСЛЯЕМ ОСН. РАБОТНИКОВ */
			/*IF @CNT > 15 
				INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 4, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 1, 0,@SPHERE, @BUFFER_SUBDIV,'301',@NAME_CAT))
			ELSE*/
				INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 4,  ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 1 AND SPHERE_LINK = @SPHERE AND CODE = '301' and NAME_CAT = @NAME_CAT),0)
			/* ВЫЧИСЛЯЕМ ВНЕШ. СОВМЕСИТЕЛЕЙ */
			/*IF @CNT > 15 
				INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 5, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 3, 0,@SPHERE, @BUFFER_SUBDIV,'301',@NAME_CAT))
			ELSE*/
				INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 5,  ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 3 AND SPHERE_LINK = @SPHERE AND CODE = '301' and NAME_CAT = @NAME_CAT ),0)
		END
		ELSE BEGIN
			IF @CODE_CAT like ('%311%') 
			BEGIN
				/* ВЫЧИСЛЯЕМ ОСН. РАБОТНИКОВ */
				/*IF @CNT > 15 
					INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 4, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 1, 0,@SPHERE, @BUFFER_SUBDIV,'311',@NAME_CAT))
				ELSE*/
					INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 4, ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 1 AND SPHERE_LINK = @SPHERE AND CODE = '311' and NAME_CAT = @NAME_CAT ),0)
				/* ВЫЧИСЛЯЕМ ВНЕШ. СОВМЕСИТЕЛЕЙ */
				/*IF @CNT > 15 
					INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 5, CONVERT(NUMERIC(18,1),DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 3, 0,@SPHERE, @BUFFER_SUBDIV,'311',@NAME_CAT))
				ELSE*/
					INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 5, ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 3 AND SPHERE_LINK = @SPHERE AND CODE = '311' and NAME_CAT = @NAME_CAT ),0)
			END
			ELSE BEGIN
				IF @CODE_CAT like ('103%') 
				BEGIN
					
					/* ВЫЧИСЛЯЕМ ОСН. РАБОТНИКОВ */
					/*IF @CNT > 15 
						INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 4, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 1, 0,@SPHERE, @BUFFER_SUBDIV,@CODE_CAT,null))
					ELSE*/
						INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 4, ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 1 AND SPHERE_LINK = @SPHERE and CODE = @CODE_CAT),0)
					/* ВЫЧИСЛЯЕМ ВНЕШ. СОВМЕСИТЕЛЕЙ */
					/*IF @CNT > 15 
						INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 5, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 3, 0,@SPHERE, @BUFFER_SUBDIV,@CODE_CAT,null))
					ELSE*/
						INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 5, ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 3 AND SPHERE_LINK = @SPHERE and CODE = @CODE_CAT),0)
		
					/* ВЫЧИСЛЯЕМ ОСН. РАБОТНИКОВ */ -- добавляем необозначенных работников к прочему персоналу
					/*IF @CNT > 15 
						UPDATE  #NZP_PART1 
							set VAL = VAL + CONVERT(NUMERIC(18), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 1, 0,NULL, @BUFFER_SUBDIV,null,null))
						where CODE_STR = '103' and COL = 4
					ELSE */
						UPDATE  #NZP_PART1 
							set VAL = isnull(VAL,0) +	ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 1 AND staff_head is not null and isnull(cat_nzp_link,0) = 0),0)
						where CODE_STR = '103' and COL = 4
					/* ВЫЧИСЛЯЕМ ВНЕШ. СОВМЕСИТЕЛЕЙ */ -- добавляем необозначенных работников к прочему персоналу
					/*IF @CNT > 15 
						UPDATE  #NZP_PART1 
							set VAL = VAL + CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 3, 0,NULL, @BUFFER_SUBDIV,null,null))
						where CODE_STR = '103' and COL = 5
					ELSE */
						UPDATE  #NZP_PART1 
							set VAL = ISNULL(VAL,0) + ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 3 AND staff_head is not null and isnull(cat_nzp_link,0) = 0),0)
						where CODE_STR = '103' and COL = 5	
				END
				ELSE BEGIN
					/* ВЫЧИСЛЯЕМ ОСН. РАБОТНИКОВ */
					/*IF @CNT > 15 
						INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 4, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 1, 0,@SPHERE, @BUFFER_SUBDIV,@CODE_CAT,null))
					ELSE*/
						INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 4, ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 1 AND SPHERE_LINK = @SPHERE AND CODE = @CODE_CAT ),0) 
					/* ВЫЧИСЛЯЕМ ВНЕШ. СОВМЕСИТЕЛЕЙ */
					/*IF @CNT > 15 
						INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 5, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 3, 0,@SPHERE, @BUFFER_SUBDIV,@CODE_CAT,null))
					ELSE*/
						INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 5, ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 3 AND SPHERE_LINK = @SPHERE AND CODE = @CODE_CAT ),0) 
				END
			END 
		END
	END

	FETCH NEXT FROM @Cur1 INTO @LINK_CAT, @CODE_CAT,@NAME_CAT
END

CLOSE @Cur1
DEALLOCATE @Cur1


if @SALARY_OPTIONS_OPT8_1 = 1 
begin 
	update  p 
		set val = ceiling(val)  
	from #NZP_PART1 p where p.col = 4
end 

if @SALARY_OPTIONS_OPT8_1 = 2 
begin 
	update  p 
		set val = ceiling(val)  
	from #NZP_PART1 p where p.col = 4
	update  p 
		set val = ceiling(val)
	from #NZP_PART1 p where p.col = 5
end 


DROP TABLE #ssch_empls_nzp_ALL



/*Для каждой формы просуммируем количество работников ИЗ которых выделяются сотрудники в другие строки*/
IF @CODE_FORM = '0606045'
BEGIN
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '282' and COL = 4)	
	where CODE_STR = '281' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '282' and COL = 5)	
	where CODE_STR = '281' and COL = 5	
	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '3113' and COL = 4)	
	where CODE_STR = '3013' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '3113' and COL = 5)	
	where CODE_STR = '3013' and COL = 5	
END


IF @CODE_FORM = '0606046'  
BEGIN

	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '3113' and COL = 4)			
	where CODE_STR = '3013' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '3113' and COL = 5)	
	where CODE_STR = '3013' and COL = 5	

	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '401'  and COL = 4) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '291'  and COL = 4)	+ (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '3013'  and COL = 4)			
	where CODE_STR = '621' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '401'  and COL = 5) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '291'  and COL = 5)	+ (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '3013' and COL = 5)	
	where CODE_STR = '621' and COL = 5	

END

IF @CODE_FORM = '0606047' 
BEGIN
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('312','313') and COL = 4)			
	where CODE_STR = '3113' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('312','313') and COL = 5)	
	where CODE_STR = '3113' and COL = 5	


	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('3113','102','101','302') and COL = 4)			
	where CODE_STR = '3014' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('3113','102','101','302') and COL = 5)	
	where CODE_STR = '3014' and COL = 5	
END 

IF @CODE_FORM = '0606048'  
BEGIN
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '212' and COL = 4)			
	where CODE_STR = '211' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '212' and COL = 5)	
	where CODE_STR = '211' and COL = 5	


	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('232','233') and COL = 4)			
	where CODE_STR = '231' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('232','233') and COL = 5)	
	where CODE_STR = '231' and COL = 5	

	UPDATE  #NZP_PART1 
	set VAL = ISNULL(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('242','243') and COL = 4)			
	where CODE_STR = '241' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = ISNULL(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('242','243') and COL = 5)	
	where CODE_STR = '241' and COL = 5		

	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('252','253') and COL = 4)			
	where CODE_STR = '251' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('252','253') and COL = 5)	
	where CODE_STR = '251' and COL = 5		

	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR ='3111' and COL = 4)			
	where CODE_STR = '3011' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR ='3111' and COL = 5)	
	where CODE_STR = '3011' and COL = 5		

	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR ='3112' and COL = 4)			
	where CODE_STR = '3012' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR ='3112' and COL = 5)	
	where CODE_STR = '3012' and COL = 5		
END

IF @CODE_FORM = '0606049'
BEGIN
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '282' and COL = 4)	
	where CODE_STR = '281' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '282' and COL = 5)	
	where CODE_STR = '281' and COL = 5	
	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '3113' and COL = 4)	
	where CODE_STR = '3013' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '3113' and COL = 5)	
	where CODE_STR = '3013' and COL = 5	
END


/*********************************************************************************************/

/*INSERT INTO #NZP_PART1 (COL, VAL_STR)
SELECT TOP 1 1 AS COL, OKVED FROM dbo.DEPARTMENTS WHERE LINK = @DEP_LINK
*/

DELETE FROM DBO.BUFFER WHERE ID = @BUFFER_SUBDIV AND @BUFFER_SUBDIV IS NOT NULL	

CREATE TABLE #EMPL (LINK INT, PERS_LINK INT, DEP_LINK INT, [STATUS] TINYINT, CAT_NZP_LINK int , CAT_NZP_CODE varchar(3), PERIOD_BEG DATETIME, PERIOD_END DATETIME)
INSERT INTO #EMPL
SELECT 
	i.EMPL_LINK, i.PERS_LINK, i.DEP_LINK, i.[STATUS], st.CAT_NZP_LINK, pc.CODE ,i.PERIOD_BEG, i.PERIOD_END 
FROM 
	DBO.SA_EMPLS_INFO_PERIOD(@D1, @D2, DEFAULT, @DEP_LINK) i
	inner join sd_empl se on se.link = i.EMPL_LINK
	left join staff st on st.link_up = se.staff_head and  st.link = se.staff_link and (st.SPHERE_LINK = @sphere or  st.SPHERE_LINK is null)
	left join PERS_CATEGORY_BY_SPHERE pc on pc.link = st.cat_nzp_link 	
WHERE 
	(
	@BUFFER_SUBDIV IS NULL 
		OR 
	@BUFFER_SUBDIV IS NOT NULL AND i.SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
	)
	
ORDER BY 
	i.DEP_LINK, i.EMPL_LINK

CREATE TABLE #EMPL1 (LINK INT, PERS_LINK INT, DEP_LINK INT, [STATUS] TINYINT, CAT_NZP_LINK int , CAT_NZP_CODE varchar(3), PERIOD_BEG DATETIME, PERIOD_END DATETIME)
INSERT INTO #EMPL1
SELECT 
	i.EMPL_LINK, i.PERS_LINK, i.DEP_LINK, i.[STATUS], st.CAT_NZP_LINK, pc.CODE , i.PERIOD_BEG, i.PERIOD_END 
FROM 
	DBO.SA_EMPLS_INFO_PERIOD(@DBYEAR, @D2, DEFAULT, @DEP_LINK) i
	inner join sd_empl se on se.link = i.EMPL_LINK
	left join staff st on st.link_up = se.staff_head and  st.link = se.staff_link and (st.SPHERE_LINK = @sphere or  st.SPHERE_LINK is null)
	left join PERS_CATEGORY_BY_SPHERE pc on pc.link = st.cat_nzp_link 	
WHERE 
	(
	@BUFFER_SUBDIV IS NULL 
		OR 
	@BUFFER_SUBDIV IS NOT NULL AND i.SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
	)
ORDER BY 
	i.DEP_LINK, i.EMPL_LINK



--ПОДКОРРЕКТИРУЕМ КОНЕЧНУЮ ДАТУ ДЛЯ ТЕХ, КТО ПЕРЕВОДИЛСЯ, ДЛЯ ТОГО ЧТОБЫ ОПРЕДЕЛИТЬ СУММЫ НАЧИСЛЕНИЙ, НАЧИСЛЕННЫХ ПОСЛЕ ДАТЫ ИХ УВОЛЬНЕНИЯ
UPDATE E
SET E.PERIOD_END = @D2
FROM 
	#EMPL E
	INNER JOIN (SELECT LINK, MAX_PERIOD_END = MAX(PERIOD_END) FROM  #EMPL E1 GROUP BY LINK HAVING COUNT(*) > 1) A 
		ON E.LINK = A.LINK AND E.PERIOD_END = A.MAX_PERIOD_END
WHERE
	A.MAX_PERIOD_END < @D2

--ПОДКОРРЕКТИРУЕМ КОНЕЧНУЮ ДАТУ ДЛЯ ТЕХ, КТО ПЕРЕВОДИЛСЯ, ДЛЯ ТОГО ЧТОБЫ ОПРЕДЕЛИТЬ СУММЫ НАЧИСЛЕНИЙ, НАЧИСЛЕННЫХ ПОСЛЕ ДАТЫ ИХ УВОЛЬНЕНИЯ

UPDATE E
SET E.PERIOD_END = @D2
FROM 
	#EMPL1 E
	INNER JOIN (SELECT LINK, MAX_PERIOD_END = MAX(PERIOD_END) FROM  #EMPL1 E1 GROUP BY LINK HAVING COUNT(*) > 1) A 
		ON E.LINK = A.LINK AND E.PERIOD_END < A.MAX_PERIOD_END
WHERE
	A.MAX_PERIOD_END <= @D2	


/* ДОГОВОРНИКИ */
DECLARE @M NUMERIC(18,2) 

IF @ATR_INCR_ITOG =2 
	SELECT --За месяц
		@M=SUM(CASE 
			WHEN DGH.DATE1<=@D1 AND COALESCE(DGH.DATE2,@D2)>=@D2 THEN DATEDIFF(DAY,@D1,@D2)		-- РАБОТАЛ ВЕСЬ ПЕРИОД
			WHEN DGH.DATE1<=@D1 AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE2>@D1 THEN DATEDIFF(DAY,@D1,DGH.DATE2)+1	-- УВОЛЕН В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@D1  AND COALESCE(DGH.DATE2,@D2)>=@D2 AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,@D2) 		-- ПРИНЯТ В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@D1  AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,DGH.DATE2)+1	-- ПРИНЯТ И УВОЛЕН В РАБОЧИЙ ПЕРИОД
			 ELSE 0
		END)
	FROM 
		dbo.REESTR_DGH DGH
	WHERE
			DEP_LINK = @DEP_LINK 
		AND
			DGH.DATE1 <= @D2 AND DGH.DATE2 >= @D1
		AND
		NOT EXISTS (
			SELECT E.PERS_LINK FROM DBO.SD_EMPL_FN(DEFAULT,@D2,DEFAULT,@DEP_LINK) E
			WHERE DGH.PERS_LINK = E.PERS_LINK AND DGH.DATE1 <= ISNULL(E.DATE_END,ISNULL(DGH.DATE2,@D2)) AND ISNULL(DGH.DATE2,@D2) >= E.DATE_BEGIN 
			)
ELSE
	SELECT --С начала года
		@M=SUM(CASE 
			WHEN DGH.DATE1<=@DBYEAR AND COALESCE(DGH.DATE2,@D2)>=@D2 THEN DATEDIFF(DAY,@DBYEAR,@D2)		-- РАБОТАЛ ВЕСЬ ПЕРИОД
			WHEN DGH.DATE1<=@DBYEAR AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE2>@DBYEAR THEN DATEDIFF(DAY,@DBYEAR,DGH.DATE2)+1	-- УВОЛЕН В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@DBYEAR  AND COALESCE(DGH.DATE2,@D2)>=@D2 AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,@D2) 		-- ПРИНЯТ В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@DBYEAR  AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,DGH.DATE2)+1	-- ПРИНЯТ И УВОЛЕН В РАБОЧИЙ ПЕРИОД
			 ELSE 0
		END)
	FROM 
		dbo.REESTR_DGH DGH
	WHERE
			DEP_LINK = @DEP_LINK 
		AND
			DGH.DATE1 <= @D2 AND DGH.DATE2 >= @DBYEAR
		AND
		NOT EXISTS (
			SELECT E.PERS_LINK FROM DBO.SD_EMPL_FN(DEFAULT,@D2,DEFAULT,@DEP_LINK) E
			WHERE DGH.PERS_LINK = E.PERS_LINK AND DGH.DATE1 <= ISNULL(E.DATE_END,ISNULL(DGH.DATE2,@D2)) AND ISNULL(DGH.DATE2,@D2) >= E.DATE_BEGIN 
			)				

DECLARE	@NDAYSFEBR	INT
IF @ATR_INCR_ITOG =2 
	SET @NDAYSFEBR = DAY(DBO.DATEENDOFMONTH(@D1))
ELSE
	SET @NDAYSFEBR = ISNULL((SELECT SUM(DAY(DBO.DATEENDOFMONTH(DATE_BEGIN))) FROM dbo.MONTHS_EX(@DBYEAR, @D2)),99999999)


----INSERT INTO #NZP_PART1 (COL, VAL)
----SELECT 4 AS COL, ROUND(@M/@NDAYSFEBR,0)

---- ВСЕГО (СУММА ГРАФ 2,3,4)
--INSERT INTO #P4_PART1
--SELECT 1 AS COL, SUM(VAL) FROM #P4_PART1 WHERE COL > 1

/* КОЛ-ВО ОТРАБОТ. ЧАСОВ */
DECLARE @ISMINUTES TINYINT
SET @ISMINUTES = DBO.SA_GET_OPTION_BY_CODE('TABEL_OPT10') --УЧЕТ ВРЕМЕНИ В ЧАСАХ И МИНУТАХ

/*КОЛИЧЕСТВО ОТРАБОТАННЫХ ЧЕЛОВЕКО-ЧАСОВ С НАЧАЛА ГОДА РАБОТНИКАМИ СПИСОЧНОГО СОСТАВА*/
/*INSERT INTO #P4_PART1 (COL, VAL)
SELECT [STATUS],  DBO.MINUTES_TO_NUM(SUM(DBO.NUM_TO_MINUTES([HOURS],@ISMINUTES)),@ISMINUTES)
FROM
(
	SELECT 
		[STATUS] = (CASE WHEN F.[STATUS] <> 3 THEN 5 ELSE 6 END),
		[HOURS] = DBO.SA_GET_EMPL_WH(LINK, DEFAULT,DEFAULT,PERIOD_BEG,PERIOD_END,DEFAULT,DEFAULT) 
	FROM 
		#EMPL1 F
) A
GROUP BY [STATUS]
*/
-- очистка лишних задвоений для тех у кого перевод, и дальнейшая работа происходила в течении месяца
delete FROM 
	#EMPL1 
WHERE
	LINK in (SELECT LINK FROM  #EMPL1 E1 GROUP BY LINK HAVING COUNT(*) > 1 ) 
	AND PERIOD_beg not in (SELECT min(PERIOD_beg) FROM  #EMPL1 E1 GROUP BY LINK HAVING COUNT(*) > 1 /*and  min(PERIOD_END) = @D2*/ ) 

/* ФОНД НАЧИСЛ З/ПЛАТЫ */
CREATE  TABLE #NZP_S_J_C ( SUMMA NUMERIC(20,1), STAT_OTCHET TINYINT, DEP_TYPE TINYINT, COL TINYINT,  CAT_NZP_LINK int, [SOURCE] TINYINT,  PERIOD_END DATETIME)

DECLARE @LINKEKR213 INT
SELECT @LINKEKR213 = LINK FROM DBO.DICTIONARY_ITEM WHERE CODE = '213'

CREATE TABLE #CJ (PERS_LINK INT, LINK_EMPL INT, LINK_PAYS INT, PERIOD_END DATETIME, SUMMA NUMERIC(18,2), STAT_OTCHET TINYINT, WAY_CALC TINYINT, DEP_TYPE TINYINT, CAT_NZP_LINK int , LINK_VKR int , [SOURCE] TINYINT)

INSERT INTO #CJ (PERS_LINK, LINK_EMPL, LINK_PAYS, PERIOD_END, SUMMA, STAT_OTCHET, WAY_CALC, DEP_TYPE , CAT_NZP_LINK, LINK_VKR , [SOURCE])
SELECT 
	PERS_LINK, LINK_EMPL, LINK_PAYS, 
	JC.PERIOD_BEGIN, 
	SUMMA, STAT_OTCHET, WAY_CALC,
	CASE WHEN PERS_LINK IS NULL THEN 0 ELSE 5 END /* 5 - ФИЗ ЛИЦО */,
	null,
	JC.LINK_VKR,
	S.[SOURCE]
FROM
	DBO.CALCULATE_JURNAL JC 
	INNER JOIN DBO.PAYS P ON JC.LINK_PAYS = P.LINK 
	inner join SALARY_SRC_FIN S on S.LINK = JC.LINK_VKR
WHERE
	P.[OBJECT] = 1 /* ТОЛЬКО НАЧИСЛЕНИЯ */
	AND (P.WAY_CALC <> 15 AND YEAR(JC.PERIOD_BEGIN)=  YEAR(@D1) AND MONTH(JC.PERIOD_BEGIN) <= MONTH(@D1)
		OR P.WAY_CALC = 15 AND YEAR(JC.PERIOD_BEGIN)=  YEAR(@D1) AND MONTH(JC.PERIOD_BEGIN) <= MONTH(@D1))	
	AND P.STAT_OTCHET <> 3
	AND JC.LINK_DEP = @DEP_LINK


----------- суммы договорников, которые являются сотрудниками помеячаем считать как для сотрудников
UPDATE J
SET LINK_EMPL = E.LINK , dep_type = 1
FROM #CJ J INNER JOIN #EMPL1 E ON J.PERS_LINK = E.PERS_LINK AND J.[PERIOD_END] BETWEEN E.PERIOD_BEG AND E.PERIOD_END
----------- определим для всех имеющихся link_empl , категорию к которой они относятся 
UPDATE J
SET CAT_NZP_LINK = E.CAT_NZP_LINK 
FROM #CJ J INNER JOIN #EMPL1 E ON j.LINK_EMPL = E.link  


--- Для сотрудников которые были уволены, и выплаты для них были в следующем месяце входящем в период расчета, проставим конец периода как период последней оплаты  
UPDATE E
SET E.PERIOD_END = A.MAX_PERIOD_END
FROM 
	#EMPL1 E
	INNER JOIN (SELECT LINK_EMPL, MAX_PERIOD_END = MAX(PERIOD_END) FROM  #CJ  GROUP BY LINK_EMPL ) A 
		ON E.LINK = a.LINK_EMPL AND E.PERIOD_END < A.MAX_PERIOD_END
WHERE
	A.MAX_PERIOD_END <= @D2	
------------

INSERT INTO #NZP_S_J_C 
SELECT  SUMMA, STAT_OTCHET, DEP_TYPE, COALESCE(F.COL,0) , j.CAT_NZP_LINK, j.[SOURCE], J.[PERIOD_END]
FROM #CJ J INNER JOIN (SELECT LINK, (CASE WHEN STATUS=3 THEN 8 WHEN STATUS=2 THEN 7 ELSE 6 END) AS COL,PERIOD_BEG, PERIOD_END FROM #EMPL1) F 
		ON J.LINK_EMPL = F.LINK AND YEAR(j.[PERIOD_END]) * 100 + MONTH(J.[PERIOD_END]) 
				BETWEEN YEAR(F.PERIOD_BEG) * 100 + MONTH(F.PERIOD_BEG) AND YEAR(F.PERIOD_END) * 100 + MONTH(F.PERIOD_END)

------договорников , которые являются сотрудниками , пометим как внутренних совместителей------------------------------
update j
	set col = 7 
	from #NZP_S_J_C j where j.dep_type = 1
	

--------------------------------------
INSERT INTO #NZP_S_J_C
SELECT SUMMA, STAT_OTCHET, DEP_TYPE, 0,null, [SOURCE], PERIOD_END
FROM #CJ WHERE LINK_EMPL IS NULL


/*Фонд начисленной заработной платы работников за отчетный период*/
	/*списочного состава (без внешних совместителей)*/
	/* ВСЕГО */
	/* COL6!  ВСЕ код 100 */
	--INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	--	SELECT '100' , 6, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C
	--	WHERE COL <>(8) AND STAT_OTCHET=1 AND DEP_TYPE<>5
	--		AND CAT_NZP_LINK IS NOT NULL
	--		AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
			
	/* COL6! ВСЕ код 100  */		
	INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	SELECT '100' , 6, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C 
	WHERE COL <>(8) AND STAT_OTCHET=1 AND DEP_TYPE<>5
			AND CAT_NZP_LINK IS NOT NULL
			AND  
			(	@ATR_INCR_ITOG <> 2  AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@ATR_INCR_ITOG =2  AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)	


		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT c.code, 6, 0 FROM #CAT_CODES c 
		
		UPDATE N
			set  VAL = isnull((SELECT isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
																WHERE  s.CAT_NZP_LINK = c1.link and  s.COL <>(8) AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5
																	AND s.CAT_NZP_LINK IS NOT NULL
																	--AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																	AND  
																	(	@ATR_INCR_ITOG <> 2  AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																		OR
																		@ATR_INCR_ITOG =2  AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
																	)	
																	
																		
																GROUP BY s.CAT_NZP_LINK),0)
		FROM #NZP_PART1 n  inner join #CAT_CODES c1 on c1.code = n.CODE_STR and n.COL = 6

    /*в том числе по внутреннему совместительству*/	
	/* COL7! ВСЕ  - код 100 */
	INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT '100', 7, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C 
		WHERE COL=7 AND STAT_OTCHET=1 AND DEP_TYPE<>5
			AND CAT_NZP_LINK IS NOT NULL
			--AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
			AND  
			(	@ATR_INCR_ITOG <> 2  AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@ATR_INCR_ITOG =2  AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)			

	
		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT c.code, 7, 0 FROM #CAT_CODES c 
		
		UPDATE N
			set  VAL = isnull((SELECT isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
																WHERE  s.CAT_NZP_LINK = c1.link and  s.COL=7 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5
																	AND s.CAT_NZP_LINK IS NOT NULL
																	--AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																	AND  
																	(	@ATR_INCR_ITOG != 2  AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																		OR
																		@ATR_INCR_ITOG =2  AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
																	)	
																		
																GROUP BY s.CAT_NZP_LINK),0)
		FROM #NZP_PART1 n  inner join #CAT_CODES c1 on c1.code = n.CODE_STR and n.COL = 7
	
	/*внешних совместителей*/	

	/* COL8! ВСЕ  - код 100 */
	INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT '100',8, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C
		WHERE COL=8 AND STAT_OTCHET=1 AND DEP_TYPE<>5
			AND CAT_NZP_LINK IS NOT NULL
			--AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
			AND  
			(	@ATR_INCR_ITOG <> 2  AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@ATR_INCR_ITOG =2  AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)	
			
	/* COL8! РАЗБИВКА ПО КОДАМ*/
	--INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	--	SELECT c.code,8, isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
	--	inner join #CAT_CODES c on  s.CAT_NZP_LINK = c.link
	--	WHERE s.COL=8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5
	--		AND s.CAT_NZP_LINK IS NOT NULL
	--		AND
	--		(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
	--			OR
	--			@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
	--		)	
	--	GROUP BY c.code		

		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT c.code, 8, 0 FROM #CAT_CODES c 
		
		UPDATE N
			set  VAL = isnull((SELECT isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
																WHERE  s.CAT_NZP_LINK = c1.link and  s.COL=8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5
																	AND s.CAT_NZP_LINK IS NOT NULL
																	--AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																	AND  
																	(	@ATR_INCR_ITOG <> 2  AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																		OR
																		@ATR_INCR_ITOG =2  AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
																	)	
																																
																GROUP BY s.CAT_NZP_LINK),0)
		FROM #NZP_PART1 n  inner join #CAT_CODES c1 on c1.code = n.CODE_STR and n.COL = 8


	/*Фонд начисленной заработной платы работников по источникам финансирования*/
	/*из гр. 3 списочного состава (без внешних совместителей) col6 */
	/*за счет средств бюджетов всех уровней (субсидий)*/
	/* COL9! Все - код 100*/
	INSERT INTO #NZP_PART1 (CODE_STR,COL, VAL)
		SELECT '100', 9, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C
		WHERE COL<>8 AND STAT_OTCHET=1 AND DEP_TYPE<>5 and [SOURCE] not in (2,7)
			AND CAT_NZP_LINK IS NOT NULL
			--AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
			AND  
			(	@ATR_INCR_ITOG <> 2  AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@ATR_INCR_ITOG =2  AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)	
			
			
	/* COL9! Разбивка по кодам*/
	--INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	--	SELECT c.code,9, isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
	--	inner join #CAT_CODES c on  s.CAT_NZP_LINK = c.link
	--	WHERE s.COL<>8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] not in (2,7)
	--		AND s.CAT_NZP_LINK IS NOT NULL
	--		AND
	--		(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
	--			OR
	--			@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
	--		)	
	--	GROUP BY c.code		


		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT c.code, 9, 0 FROM #CAT_CODES c 
		
		UPDATE N
			set  VAL = isnull((SELECT isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
																WHERE  s.CAT_NZP_LINK = c1.link and  s.COL<>8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] not in (2,7)
																	AND s.CAT_NZP_LINK IS NOT NULL
																	--AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																	AND  
																	(	@ATR_INCR_ITOG <> 2  AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																		OR
																		@ATR_INCR_ITOG =2  AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
																	)	
																GROUP BY s.CAT_NZP_LINK),0)
		FROM #NZP_PART1 n  inner join #CAT_CODES c1 on c1.code = n.CODE_STR and n.COL = 9


	/*Фонд начисленной заработной платы работников по источникам финансирования*/
	/*из гр. 3 списочного состава (без внешних совместителей) col6 */
	/*ОМС*/
	/* COL10! Все - код 100*/
	INSERT INTO #NZP_PART1 (CODE_STR,COL, VAL)
		SELECT '100', 10, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C
		WHERE COL<>8 AND STAT_OTCHET=1 AND DEP_TYPE<>5 and [SOURCE]= 7
			AND CAT_NZP_LINK IS NOT NULL
			--AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
			AND  
			(	@ATR_INCR_ITOG <> 2  AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@ATR_INCR_ITOG =2  AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)
			
	/* COL10! Разбивка по кодам*/
	--INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	--	SELECT c.code,10, isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
	--	inner join #CAT_CODES c on  s.CAT_NZP_LINK = c.link
	--	WHERE s.COL<>8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] =7
	--		AND s.CAT_NZP_LINK IS NOT NULL
	--		AND
	--		(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
	--			OR
	--			@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
	--		)	
	--	GROUP BY c.code	

		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT c.code, 10, 0 FROM #CAT_CODES c 
		
		UPDATE N
			set  VAL = isnull((SELECT isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
																WHERE  s.CAT_NZP_LINK = c1.link and  s.COL<>8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] =7
																	AND s.CAT_NZP_LINK IS NOT NULL
																	--AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																	AND  
																	(	@ATR_INCR_ITOG <> 2  AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																		OR
																		@ATR_INCR_ITOG =2  AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
																	)	
																GROUP BY s.CAT_NZP_LINK),0)
		FROM #NZP_PART1 n  inner join #CAT_CODES c1 on c1.code = n.CODE_STR and n.COL = 10


	/*Фонд начисленной заработной платы работников по источникам финансирования*/
	/*из гр. 3 списочного состава (без внешних совместителей) col6 */
	/*средства от приносящей доход деятельности*/
	/* COL11! Все - код 100*/
	INSERT INTO #NZP_PART1 (CODE_STR,COL, VAL)
		SELECT '100', 11, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C
		WHERE COL<>8 AND STAT_OTCHET=1 AND DEP_TYPE<>5 and [SOURCE]= 2
			AND CAT_NZP_LINK IS NOT NULL
			--AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
			AND  
			(	@ATR_INCR_ITOG <> 2  AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@ATR_INCR_ITOG =2  AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)
	/* COL11! Разбивка по кодам*/
	--INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	--	SELECT c.code,11, isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
	--	inner join #CAT_CODES c on  s.CAT_NZP_LINK = c.link
	--	WHERE s.COL<>8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] =2
	--		AND s.CAT_NZP_LINK IS NOT NULL
	--		AND
	--		(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
	--			OR
	--			@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
	--		)	
	--	GROUP BY c.code	

		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT c.code, 11, 0 FROM #CAT_CODES c 
		
		UPDATE N
			set  VAL = isnull((SELECT isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
																WHERE  s.CAT_NZP_LINK = c1.link and  s.COL<>8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] =2
																	AND s.CAT_NZP_LINK IS NOT NULL
																	--AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																	AND  
																	(	@ATR_INCR_ITOG <> 2  AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																		OR
																		@ATR_INCR_ITOG =2  AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
																	)																		
																GROUP BY s.CAT_NZP_LINK),0)
		FROM #NZP_PART1 n  inner join #CAT_CODES c1 on c1.code = n.CODE_STR and n.COL = 11


	/*Фонд начисленной заработной платы работников по источникам финансирования*/
	/*из гр.5 внешних совместителей col8 */
	/*за счет средств бюджетов всех уровней (субсидий)*/
	/* COL12! Все - код 100*/
	INSERT INTO #NZP_PART1 (CODE_STR,COL, VAL)
		SELECT '100', 12, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C
		WHERE COL=8 AND STAT_OTCHET=1 AND DEP_TYPE<>5 and [SOURCE] not in (2,7)
			AND CAT_NZP_LINK IS NOT NULL
			--AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
			AND  
			(	@ATR_INCR_ITOG <> 2  AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@ATR_INCR_ITOG =2  AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)			
	/* COL12! Разбивка по кодам*/
	--INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	--	SELECT c.code,12, isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
	--	inner join #CAT_CODES c on  s.CAT_NZP_LINK = c.link
	--	WHERE s.COL=8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] not in (2,7)
	--		AND s.CAT_NZP_LINK IS NOT NULL
	--		AND
	--		(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
	--			OR
	--			@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
	--		)	
	--	GROUP BY c.code	
		
		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT c.code, 12, 0 FROM #CAT_CODES c 
		
		UPDATE N
			set  VAL = isnull((SELECT isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
																WHERE  s.CAT_NZP_LINK = c1.link and  s.COL=8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] not in (2,7)
																	AND s.CAT_NZP_LINK IS NOT NULL
																	--AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																	AND  
																	(	@ATR_INCR_ITOG <> 2  AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																		OR
																		@ATR_INCR_ITOG =2  AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
																	)																		
																GROUP BY s.CAT_NZP_LINK),0)
		FROM #NZP_PART1 n  inner join #CAT_CODES c1 on c1.code = n.CODE_STR and n.COL = 12	

	/*Фонд начисленной заработной платы работников по источникам финансирования*/
	/*из гр.5 внешних совместителей col8 */
	/*ОМС*/
	/* COL13! Все - код 100*/
	INSERT INTO #NZP_PART1 (CODE_STR,COL, VAL)
		SELECT '100', 13, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C
		WHERE COL=8 AND STAT_OTCHET=1 AND DEP_TYPE<>5 and [SOURCE]=7
			AND CAT_NZP_LINK IS NOT NULL
			--AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
			AND  
			(	@ATR_INCR_ITOG <> 2  AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@ATR_INCR_ITOG =2  AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)			
	/* COL13! Разбивка по кодам*/
	--INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	--	SELECT c.code,13, isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
	--	inner join #CAT_CODES c on  s.CAT_NZP_LINK = c.link
	--	WHERE s.COL=8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] =7
	--		AND s.CAT_NZP_LINK IS NOT NULL
	--		AND
	--		(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
	--			OR
	--			@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
	--		)	
	--	GROUP BY c.code	

		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT c.code, 13, 0 FROM #CAT_CODES c 
		
		UPDATE N
			set  VAL = isnull((SELECT isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
																WHERE  s.CAT_NZP_LINK = c1.link and  s.COL=8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] =7
																	AND s.CAT_NZP_LINK IS NOT NULL
																	--AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																	AND  
																	(	@ATR_INCR_ITOG <> 2  AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																		OR
																		@ATR_INCR_ITOG =2  AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
																	)																		
																GROUP BY s.CAT_NZP_LINK),0)
		FROM #NZP_PART1 n  inner join #CAT_CODES c1 on c1.code = n.CODE_STR and n.COL = 13	


	/*Фонд начисленной заработной платы работников по источникам финансирования*/
	/*из гр.5 внешних совместителей col8 */
	/*средства от приносящей доход деятельности*/
	/* COL14! Все - код 100*/
	INSERT INTO #NZP_PART1 (CODE_STR,COL, VAL)
		SELECT '100', 14, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C
		WHERE COL=8 AND STAT_OTCHET=1 AND DEP_TYPE<>5 and [SOURCE]=2
			AND CAT_NZP_LINK IS NOT NULL
			--AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
			AND  
			(	@ATR_INCR_ITOG <> 2  AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@ATR_INCR_ITOG =2  AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)			
	/* COL14! Разбивка по кодам*/
	--INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	--	SELECT c.code,14, isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
	--	inner join #CAT_CODES c on  s.CAT_NZP_LINK = c.link
	--	WHERE s.COL=8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE]=2
	--		AND s.CAT_NZP_LINK IS NOT NULL
	--		AND
	--		(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
	--			OR
	--			@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
	--		)	
	--	GROUP BY c.code							

		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT c.code, 14, 0 FROM #CAT_CODES c 
		
		UPDATE N
			set  VAL = isnull((SELECT isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
																WHERE  s.CAT_NZP_LINK = c1.link and  s.COL=8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE]=2
																	AND s.CAT_NZP_LINK IS NOT NULL
																	--AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																	AND  
																	(	@ATR_INCR_ITOG <> 2  AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																		OR
																		@ATR_INCR_ITOG =2  AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
																	)																		
																GROUP BY s.CAT_NZP_LINK),0)
		FROM #NZP_PART1 n  inner join #CAT_CODES c1 on c1.code = n.CODE_STR and n.COL = 14


/*Для каждой формы просуммируем строки ИЗ которых выделяются другие строки*/
IF @CODE_FORM = '0606045'
BEGIN
	declare @i int
	set @i = 6 
	WHILE @i <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR = '282' and COL = @i),0)	
		where CODE_STR = '281' and COL = @i	
		set @i = @i+1 
	END 	

	set @i = 6 
	WHILE @i <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR = '3113' and COL = @i),0)	
		where CODE_STR = '3013' and COL = @i	
		set @i = @i + 1
	END 	

END
IF @CODE_FORM = '0606046'  
BEGIN
	declare @i1 int
	set @i1 = 6 
	WHILE @i1 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR = '3113' and COL = @i1),0)			
		where CODE_STR = '3013' and COL = @i1	
		set @i1 = @i1 +1 	
	END

	set @i1 = 6 
	WHILE @i1 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + ISNULL((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR = '401'  and COL = @i1),0) + ISNULL((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR = '291'  and COL = @i1),0) + ISNULL((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR = '3013'  and COL = @i1),0)			
		where CODE_STR = '621' and COL = @i1	
		set @i1 = @i1 +1 	
	END

END


IF @CODE_FORM = '0606047' 
BEGIN
	declare @i2 int
	set @i2 = 6 
	WHILE @i2 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT SUM(isnull(VAL,0)) FROM #NZP_PART1 WHERE CODE_STR IN ('312','313') and COL = @i2),0)			
		where CODE_STR = '3113' and COL = @i2
		set @i2 = @i2+1 
	END 
	
	set @i2 = 6 
	WHILE @i2 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT SUM(isnull(VAL,0)) FROM #NZP_PART1 WHERE CODE_STR IN ('3113','102','101','302') and COL = @i2),0)			
		where CODE_STR = '3014' and COL = @i2
		set @i2 = @i2+1 
	END 

END 
IF @CODE_FORM = '0606048'  
BEGIN
	declare @i3 int
	set @i3 = 6 
	WHILE @i3 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR = '212' and COL = @i3),0)			
		where CODE_STR = '211' and COL = @i3
		set @i3 = @i3+1 
	END 	

	set @i3 = 6 
	WHILE @i3 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT SUM(isnull(VAL,0)) FROM #NZP_PART1 WHERE CODE_STR IN ('232','233') and COL = @i3),0)			
		where CODE_STR = '231' and COL = @i3	
		set @i3 = @i3+1 
	END 	

	set @i3 = 6 
	WHILE @i3 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT SUM(isnull(VAL,0)) FROM #NZP_PART1 WHERE CODE_STR IN ('242','243') and COL = @i3),0)			
		where CODE_STR = '241' and COL = @i3	
		set @i3 = @i3+1 
	END 		

	set @i3 = 6 
	WHILE @i3 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT SUM(isnull(VAL,0)) FROM #NZP_PART1 WHERE CODE_STR IN ('252','253') and COL = @i3),0)			
		where CODE_STR = '251' and COL = @i3	
		set @i3 = @i3+1 
	END 

	set @i3 = 6 
	WHILE @i3 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR ='3111' and COL = @i3),0)			
		where CODE_STR = '3011' and COL = @i3	
		set @i3 = @i3+1 
	END 	

	set @i3 = 6 
	WHILE @i3 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR ='3112' and COL = @i3),0)			
		where CODE_STR = '3012' and COL = @i3	
		set @i3 = @i3+1 
	END 	

END

IF @CODE_FORM = '0606049'
BEGIN
	
	declare @i4 int
	set @i4 = 6 
	WHILE @i4 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR = '282' and COL = @i4),0)	
		where CODE_STR = '281' and COL = @i4	
		set @i4 = @i4+1 
	END 			

	set @i4 = 6 
	WHILE @i4 <= 14
	begin	
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR = '3113' and COL = @i4),0)	
		where CODE_STR = '3013' and COL = @i4
		set @i4 = @i4+1 
	END 	

END




DROP TABLE #NZP_S_J_C
DROP TABLE #CAT_CODES

/**********************************************************************************************************************/
/* СОЗДАЕМ ВРЕМЕНННУЮ ТАБЛИЦУ */
DECLARE @RESULT_TABLE VARCHAR(100)
EXEC DBO.X_GET_TABLE_NAME @RESULT_TABLE OUTPUT

EXEC DBO.I_REPORT_FORMULA_ERASE_TABLES 0
EXEC ('SELECT * INTO ' + @RESULT_TABLE + ' FROM #NZP_PART1 ')
EXEC DBO.BUFFERPUSH -151, @RESULT_TABLE
	SET @OUT_VAL = ''


DROP TABLE #NZP_PART1

END









GO


GRANT EXECUTE ON dbo.[SA_NZP_PREPARE] TO PUBLIC

GO


GO

--AFTER CODE 03.07.2014
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXBD140331' AND CODE = 'BD'
IF @varKSModelLink is null
begin
	INSERT INTO EXPORT_MODELS(CODE, NAME, MODEL_VER, ISONCE, NORM_DOC, FILE_NAME_MASK, FILE_NAME_PROC, PROC_EXP, PROC_DOP_PARAM, DEP_NAME, PROG_SAVE, DATE_END)
	SELECT 'BD','Информация из расчетных документов','TXBD140331',0,'','XXXXXDNN.TTM','fb_file_name_doc','BB_EXPORT_PP','cModelVer','KOD_UBP','bb_import_BD()',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Информация из расчетных документов',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'BB_EXPORT_PP',
		PROC_DOP_PARAM   = 'cModelVer',
		PROG_SAVE   = 'bb_import_BD()',
		DEP_NAME   = 'KOD_UBP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FK',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'сылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','сылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация о получателе файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация о получателе файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,1,1,'NAME_TOFK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TO',3,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,0,0,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,0,0,'NAME_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Уровень бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BUDG_LEVEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'BUDG_LEVEL','Уровень бюджета','STRING',1,1,0,1,'BUDG_LEVEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Код УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'KOD_UBP','Код УБП','STRING',5,1,1,1,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Наименование УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'NAME_UBP','Наименование УБП','STRING',254,0,1,1,'NAME_UBP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'BD'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'BD',4,0,'Общая информация',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 0,
			NAME   = 'Общая информация',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер лицевого счета клиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'LS','Номер лицевого счета клиента','STRING',11,0,0,0,'LS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Дата',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'DATE','Дата','DATE',0,0,0,0,'DATE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_OTCH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Глобальный уникальный идентификатор',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'GUID_OTCH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_OTCH'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'GUID_OTCH','Глобальный уникальный идентификатор','GUID',36,1,0,1,'GUID_OTCH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Код документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'KOD_DOC','Код документа','STRING',2,1,1,1,'KOD_DOC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OTCH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Признак принад-лежности к про-межуточному отчёту',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'VID_OTCH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OTCH'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'VID_OTCH','Признак принад-лежности к про-межуточному отчёту','STRING',1,1,1,1,'VID_OTCH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Количество документов',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'KOL','Количество документов','NUMBER',5,1,1,1,'KOL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_TOTAL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Контрольная сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_TOTAL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_TOTAL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'SUM_TOTAL','Контрольная сумма','NUMBER2',0,0,1,1,'SUM_TOTAL','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'BDPD'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'BDPD',5,2,'Информация из расчетных до-кументов',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 5,
			ISONCE = 2,
			NAME   = 'Информация из расчетных до-кументов',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= '№ платежного поручения',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NOM_PP','№ платежного поручения','STRING',10,0,1,1,'NOM_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Дата платежного поручения',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'DATE_PP','Дата платежного поручения','DATE',0,1,1,1,'DATE_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Сумма платежного поручения',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'SUM_PP','Сумма платежного поручения','NUMBER2',0,1,1,1,'SUM_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Вид платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'VID_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'VID_PL','Вид платежа','STRING',1,1,0,0,'VID_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP_IN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Поступило в банк платель-щика.',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_PP_IN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP_IN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'DATE_PP_IN','Поступило в банк платель-щика.','DATE',0,0,0,0,'DATE_PP_IN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP_SPS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Дата списания со счета плательщика.',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_PP_SPS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP_SPS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'DATE_PP_SPS','Дата списания со счета плательщика.','DATE',0,0,0,0,'DATE_PP_SPS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OPER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Вид операции.',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'VID_OPER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OPER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'VID_OPER','Вид операции.','STRING',2,1,0,0,'VID_OPER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'ИНН Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'INN_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'INN_PAY','ИНН Плательщика','STRING',12,0,0,0,'INN_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'КПП Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KPP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'KPP_PAY','КПП Плательщика','STRING',9,1,0,0,'KPP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Наименование Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'CNAME_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'CNAME_PAY','Наименование Плательщика','STRING',160,0,0,0,'CNAME_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Расчетный счет Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'BS_PAY','Расчетный счет Плательщика','STRING',20,1,0,0,'BS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'БИК банка Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BIC_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 13,'BIC_PAY','БИК банка Плательщика','STRING',9,1,0,0,'BIC_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Наименование банка Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BIC_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'NAME_BIC_PAY','Наименование банка Плательщика','STRING',160,0,0,0,'NAME_BIC_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Коррсчет банка Плательщика в РКЦ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_KS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 15,'BS_KS_PAY','Коррсчет банка Плательщика в РКЦ','STRING',20,1,0,0,'BS_KS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'ИНН получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'INN_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 16,'INN_RCP','ИНН получателя','STRING',12,0,0,0,'INN_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'КПП получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KPP_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 17,'KPP_RCP','КПП получателя','STRING',9,0,0,0,'KPP_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Наименование получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 18,'NAME_RCP','Наименование получателя','STRING',160,0,0,0,'NAME_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'Расчетный счет Получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 19,'BS_RCP','Расчетный счет Получателя','STRING',20,0,0,0,'BS_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'БИК банка Получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BIC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 20,'BIC_RCP','БИК банка Получателя','STRING',9,1,0,0,'BIC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Наименование банка получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BIC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 21,'NAME_BIC_RCP','Наименование банка получателя','STRING',160,0,0,0,'NAME_BIC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'Корсчет банка получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_KS_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 22,'BS_KS_RCP','Корсчет банка получателя','STRING',20,1,0,0,'BS_KS_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'Срок платежа',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 23,'DATE_PAY','Срок платежа','DATE',0,0,0,0,'DATE_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Очередность платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ORDER_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 24,'ORDER_PAY','Очередность платежа','STRING',1,1,0,0,'ORDER_PAY','',''

delete from dbo.EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'UIN'

if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'UIN_CODE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'Уникальный идентификатор начисления (Код)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'UIN_CODE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'UIN_CODE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 25,'UIN_CODE','Уникальный идентификатор начисления (Код)','STRING',20,1,0,0,'UIN_CODE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 26,
		NAME   		= 'Назначение платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 210,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PURPOSE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 26,'PURPOSE','Назначение платежа','STRING',210,0,0,0,'PURPOSE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYSTATUS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 27,
		NAME   		= 'Статус составителя расчетного документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PAYSTATUS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYSTATUS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 27,'PAYSTATUS','Статус составителя расчетного документа','STRING',2,0,0,0,'PAYSTATUS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 28,
		NAME   		= 'Код бюджетной классификации',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 28,'KBK','Код бюджетной классификации','STRING',20,1,0,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 29,
		NAME   		= 'Код ОКТМО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OKATO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 29,'OKATO','Код ОКТМО','STRING',11,0,0,0,'OKATO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OSNPLAT')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 30,
		NAME   		= 'Показатель основания платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OSNPLAT',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OSNPLAT'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 30,'OSNPLAT','Показатель основания платежа','STRING',2,0,0,0,'OSNPLAT','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAL_PER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 31,
		NAME   		= 'Показатель налогового периода',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAL_PER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAL_PER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 31,'NAL_PER','Показатель налогового периода','STRING',10,0,0,0,'NAL_PER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_DOK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 32,
		NAME   		= 'Показатель номера документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_DOK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_DOK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 32,'NOM_DOK','Показатель номера документа','STRING',15,0,0,0,'NOM_DOK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 33,
		NAME   		= 'Показатель даты документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_DOK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 33,'DATE_DOK','Показатель даты документа','STRING',10,0,0,0,'DATE_DOK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 34,
		NAME   		= 'Тип платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 34,'TYPE_PL','Тип платежа','STRING',2,0,0,0,'TYPE_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PL_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 35,
		NAME   		= 'Номер частичного платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_PL_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PL_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 35,'NOM_PL_PO','Номер частичного платежа','STRING',3,0,0,0,'NOM_PL_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SHIFR_RD_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 36,
		NAME   		= 'Шифр платежно-го документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SHIFR_RD_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SHIFR_RD_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 36,'SHIFR_RD_PO','Шифр платежно-го документа','STRING',2,1,0,0,'SHIFR_RD_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_RD_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 37,
		NAME   		= 'Номер платежного документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_RD_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_RD_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 37,'NOM_RD_PO','Номер платежного документа','STRING',3,0,0,0,'NOM_RD_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_RD_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 38,
		NAME   		= 'Дата платежного документа',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_RD_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_RD_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 38,'DATE_RD_PO','Дата платежного документа','DATE',0,0,0,0,'DATE_RD_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_OST_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 39,
		NAME   		= 'Сумма остатка платежа',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM_OST_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_OST_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 39,'SUM_OST_PO','Сумма остатка платежа','NUMBER2',0,0,0,0,'SUM_OST_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OPER_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 40,
		NAME   		= 'Содержание опе-рации',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 16,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OPER_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OPER_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 40,'OPER_PO','Содержание опе-рации','STRING',16,0,0,0,'OPER_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_IN_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 41,
		NAME   		= 'Дата выписки',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_IN_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_IN_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 41,'DATE_IN_TOFK','Дата выписки','DATE',0,0,0,0,'DATE_IN_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 42,
		NAME   		= 'Глобальный уни-кальный идентификатор',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 42,'GUID','Глобальный уни-кальный идентификатор','GUID',36,1,0,0,'GUID','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'BDPDST'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'BDPDST',6,2,'Строки платежного поручения по бюджетной классификации',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 6,
			ISONCE = 2,
			NAME   = 'Строки платежного поручения по бюджетной классификации',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код по КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KBK','Код по КБК','STRING',20,1,0,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'TYPE_KBK','Тип КБК','STRING',2,1,0,0,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код цели субсидии',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'ADD_KLASS','Код цели субсидии','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_BO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Номер бюджетного обязательства',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 16,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NUM_BO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_BO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NUM_BO','Номер бюджетного обязательства','STRING',16,1,0,0,'NUM_BO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ОКАТО')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'ОКТMО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ОКАТО',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ОКАТО'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'ОКАТО','ОКТMО','STRING',11,1,0,0,'ОКАТО','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'SUM','Сумма','NUMBER2',0,1,1,1,'SUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DIR_SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Направление пла-тежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DIR_SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DIR_SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'DIR_SUM','Направление пла-тежа','STRING',1,1,1,1,'DIR_SUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'MES_FIN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Месяц финансиро-вания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'MES_FIN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'MES_FIN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'MES_FIN','Месяц финансиро-вания','STRING',2,1,0,0,'MES_FIN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'REZERV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Резервное поле',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 40,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'REZERV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'REZERV'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'REZERV','Резервное поле','STRING',40,0,0,0,'REZERV','',''
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXPP140701' AND CODE = 'PP'
IF @varKSModelLink is null
begin
	INSERT INTO EXPORT_MODELS(CODE, NAME, MODEL_VER, ISONCE, NORM_DOC, FILE_NAME_MASK, FILE_NAME_PROC, PROC_EXP, PROC_DOP_PARAM, DEP_NAME, PROG_SAVE, DATE_END)
	SELECT 'PP','Платежное поручение','TXPP140701',0,'','XXXXXDNN.TTM','fb_file_name_doc','BB_EXPORT_PP','cModelVer','KOD_UBP','bb_import_PP()',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Платежное поручение',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'BB_EXPORT_PP',
		PROC_DOP_PARAM   = 'cModelVer',
		PROG_SAVE   = 'bb_import_PP()',
		DEP_NAME   = 'KOD_UBP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FK',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'сылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','сылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Уровень бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BUDG_LEVEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'BUDG_LEVEL','Уровень бюджета','STRING',1,1,0,1,'BUDG_LEVEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Код клиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KOD_UBP','Код клиента','STRING',5,1,1,1,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Наименование клиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'NAME_UBP','Наименование клиента','STRING',254,0,1,1,'NAME_UBP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TO',3,0,'Почтовая информация о получателе файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 0,
			NAME   = 'Почтовая информация о получателе файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,1,1,'NAME_TOFK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'PP'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'PP',4,0,'Пакет',0
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 0,
			NAME   = 'Пакет',
			OBLIGATORY = 0
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Дата',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'DATE','Дата','DATE',0,0,1,1,'DATE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Количество документов',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KOL','Количество документов','NUMBER',5,1,1,1,'KOL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_TOTAL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Контрольная сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_TOTAL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_TOTAL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'SUM_TOTAL','Контрольная сумма','NUMBER2',0,0,1,1,'SUM_TOTAL','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'PPT'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'PPT',5,2,'Платежное поручение',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 5,
			ISONCE = 2,
			NAME   = 'Платежное поручение',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= '№ платежного поручения',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NOM_PP','№ платежного поручения','STRING',10,0,1,1,'NOM_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Дата платежного поручения',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'DATE_PP','Дата платежного поручения','DATE',0,1,1,1,'DATE_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Сумма платежного поручения',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'SUM_PP','Сумма платежного поручения','NUMBER2',0,1,1,1,'SUM_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Вид платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'VID_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'VID_PL','Вид платежа','STRING',1,1,1,1,'VID_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OPER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Вид операции.',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'VID_OPER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OPER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'VID_OPER','Вид операции.','STRING',2,1,1,1,'VID_OPER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'ИНН Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'INN_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'INN_PAY','ИНН Плательщика','STRING',12,0,1,1,'INN_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'КПП Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KPP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'KPP_PAY','КПП Плательщика','STRING',9,1,1,1,'KPP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Наименование Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'CNAME_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'CNAME_PAY','Наименование Плательщика','STRING',160,0,1,1,'CNAME_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Расчетный счет Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'BS_PAY','Расчетный счет Плательщика','STRING',20,1,1,1,'BS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'БИК банка Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BIC_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'BIC_PAY','БИК банка Плательщика','STRING',9,1,1,1,'BIC_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Наименование банка Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_BIC_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'NAME_BIC_PAY','Наименование банка Плательщика','STRING',160,0,1,1,'NAME_BIC_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Коррсчет банка Плательщика в РКЦ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_KS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 13,'BS_KS_PAY','Коррсчет банка Плательщика в РКЦ','STRING',20,1,1,0,'BS_KS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'ИНН получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'INN_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'INN_RCP','ИНН получателя','STRING',12,0,0,0,'INN_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'КПП получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KPP_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 15,'KPP_RCP','КПП получателя','STRING',9,0,0,0,'KPP_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_UBP_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'Наименование получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'CNAME_UBP_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_UBP_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 16,'CNAME_UBP_RCP','Наименование получателя','STRING',160,0,1,1,'CNAME_UBP_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Расчетный счет Получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 17,'BS_RCP','Расчетный счет Получателя','STRING',20,0,0,0,'BS_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'БИК банка Получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BIC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 18,'BIC_RCP','БИК банка Получателя','STRING',9,1,1,1,'BIC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'Наименование банка получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_BIC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 19,'NAME_BIC_RCP','Наименование банка получателя','STRING',160,0,1,1,'NAME_BIC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'Корсчет банка получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_KS_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 20,'BS_KS_RCP','Корсчет банка получателя','STRING',20,1,0,0,'BS_KS_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Срок платежа',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 21,'DATE_PAY','Срок платежа','DATE',0,0,0,0,'DATE_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'Очередность платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'ORDER_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 22,'ORDER_PAY','Очередность платежа','STRING',1,1,1,1,'ORDER_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'UIN_CODE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'уин',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 25,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'UIN_CODE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'UIN_CODE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 23,'UIN_CODE','уин','STRING',25,0,0,0,'UIN_CODE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Назначение платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 210,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'PURPOSE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 24,'PURPOSE','Назначение платежа','STRING',210,0,1,1,'PURPOSE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYSTATUS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'Статус составителя расчетного документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PAYSTATUS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYSTATUS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 25,'PAYSTATUS','Статус составителя расчетного документа','STRING',2,0,0,0,'PAYSTATUS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 26,
		NAME   		= 'Код бюджетной классификации',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 26,'KBK','Код бюджетной классификации','STRING',20,1,0,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 27,
		NAME   		= 'Код ОКАТО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OKATO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 27,'OKATO','Код ОКАТО','STRING',11,0,0,0,'OKATO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OSNPLAT')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 28,
		NAME   		= 'Показатель основания платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OSNPLAT',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OSNPLAT'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 28,'OSNPLAT','Показатель основания платежа','STRING',2,0,0,0,'OSNPLAT','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAL_PER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 29,
		NAME   		= 'Показатель налогового периода',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAL_PER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAL_PER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 29,'NAL_PER','Показатель налогового периода','STRING',10,0,0,0,'NAL_PER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_DOK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 30,
		NAME   		= 'Показатель номера документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NUM_DOK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_DOK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 30,'NUM_DOK','Показатель номера документа','STRING',15,0,0,0,'NUM_DOK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 31,
		NAME   		= 'Показатель даты документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_DOK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 31,'DATE_DOK','Показатель даты документа','STRING',10,0,0,0,'DATE_DOK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 32,
		NAME   		= 'Тип платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 32,'TYPE_PL','Тип платежа','STRING',2,0,0,0,'TYPE_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 33,
		NAME   		= 'Глобальный уни-кальный идентификатор',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 33,'GUID_FK','Глобальный уни-кальный идентификатор','GUID',0,0,0,0,'GUID_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 34,
		NAME   		= 'Код ОрФК  клиента-плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 34,'KOD_TOFK_PAY','Код ОрФК  клиента-плательщика','STRING',4,1,1,1,'KOD_TOFK_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 35,
		NAME   		= 'Наименование ОрФК клиента- плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 35,'NAME_TOFK_PAY','Наименование ОрФК клиента- плательщика','STRING',2000,0,1,1,'NAME_TOFK_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 36,
		NAME   		= 'Код клиента - плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_UBP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 36,'KOD_UBP_PAY','Код клиента - плательщика','STRING',5,1,1,1,'KOD_UBP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 37,
		NAME   		= 'Полное наименование клиента - Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 37,'NAME_UBP_PAY','Полное наименование клиента - Плательщика','STRING',2000,0,1,1,'NAME_UBP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 38,
		NAME   		= 'Л/с клиента - плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 38,'LS_PAY','Л/с клиента - плательщика','STRING',11,1,0,0,'LS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_PAY_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 39,
		NAME   		= 'Л/с клиента - получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LS_PAY_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_PAY_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 39,'LS_PAY_RCP','Л/с клиента - получателя','STRING',11,1,0,0,'LS_PAY_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PRINT_KPP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 40,
		NAME   		= 'Признак печати КПП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PRINT_KPP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PRINT_KPP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 40,'PRINT_KPP','Признак печати КПП','STRING',1,1,0,0,'PRINT_KPP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIZ')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 41,
		NAME   		= 'Признак наличия Расшифровки к платежному поручению',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'PRIZ',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIZ'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 41,'PRIZ','Признак наличия Расшифровки к платежному поручению','STRING',1,1,1,1,'PRIZ','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'PPST'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'PPST',6,2,'Строки платежного поручения по бюджетной классификации',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 6,
			ISONCE = 2,
			NAME   = 'Строки платежного поручения по бюджетной классификации',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код по КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KBK','Код по КБК','STRING',20,1,0,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'TYPE_KBK','Тип КБК','STRING',2,1,0,0,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код цели плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'ADD_KLASS','Код цели плательщика','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Код цели получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'ADD_KLASS_RCP','Код цели получателя','STRING',20,0,0,0,'ADD_KLASS_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'SUM','Сумма','NUMBER2',0,1,1,1,'SUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DIR_SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Направление пла-тежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DIR_SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DIR_SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'DIR_SUM','Направление пла-тежа','STRING',1,1,1,1,'DIR_SUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'MES_FIN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Месяц финансиро-вания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'MES_FIN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'MES_FIN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'MES_FIN','Месяц финансиро-вания','STRING',2,1,0,0,'MES_FIN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'REZERV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Резервное поле',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 40,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'REZERV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'REZERV'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'REZERV','Резервное поле','STRING',40,0,0,0,'REZERV','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_FIN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Код источника финансирования',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_FIN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_FIN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'KOD_FIN','Код источника финансирования','STRING',1,1,0,0,'KOD_FIN','',''
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXUF140101' AND CODE = 'UF'
IF @varKSModelLink is null
begin
	INSERT INTO EXPORT_MODELS(CODE, NAME, MODEL_VER, ISONCE, NORM_DOC, FILE_NAME_MASK, FILE_NAME_PROC, PROC_EXP, PROC_DOP_PARAM, DEP_NAME, PROG_SAVE, DATE_END)
	SELECT 'UF','Уведомление об уточнении вида и принадлежности платежа','TXUF140101',0,'','XXXXXDNN.TTM','fb_file_name_doc','BB_EXPORT_UF','','KOD_UBP','',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Уведомление об уточнении вида и принадлежности платежа',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'BB_EXPORT_UF',
		PROC_DOP_PARAM   = '',
		PROG_SAVE   = '',
		DEP_NAME   = 'KOD_UBP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FK',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Ссылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','Ссылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Уровень бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BUDG_LEVEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'BUDG_LEVEL','Уровень бюджета','STRING',1,1,1,1,'BUDG_LEVEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Код УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KOD_UBP','Код УБП','STRING',5,1,1,1,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Наименование УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'NAME_UBP','Наименование УБП','STRING',2000,0,1,1,'NAME_UBP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TO',3,0,'Почтовая информация о получателе файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 0,
			NAME   = 'Почтовая информация о получателе файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,1,1,'NAME_TOFK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'UF'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'UF',4,2,'Уведомление об уточнении вида и принадлежности платежа',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 2,
			NAME   = 'Уведомление об уточнении вида и принадлежности платежа',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Глобальный уникальный идентификатор',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'GUID_FK','Глобальный уникальный идентификатор','STRING',36,0,0,0,'GUID_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_UF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Номер Уведомления',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_UF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_UF'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NOM_UF','Номер Уведомления','STRING',15,0,1,1,'NOM_UF','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_UF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Дата Уведомления',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_UF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_UF'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'DATE_UF','Дата Уведомления','DATE',NULL,0,1,1,'DATE_UF','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Наименование ПБС/АДБ/АИФДБ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NAME_UBP','Наименование ПБС/АДБ/АИФДБ','STRING',2000,0,0,0,'NAME_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Код по Сводному реестру ПБС/АДБ/АИФДБ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'KOD_UBP','Код по Сводному реестру ПБС/АДБ/АИФДБ','STRING',5,0,0,0,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Номер лицевого счета ПБС/АДБ/АИФДБ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LS_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'LS_UBP','Номер лицевого счета ПБС/АДБ/АИФДБ','STRING',11,1,1,0,'LS_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_GRS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Наименование ГРБС/ГАДБ/ГАИФДБ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_GRS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_GRS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'NAME_GRS','Наименование ГРБС/ГАДБ/ГАИФДБ','STRING',2000,0,0,0,'NAME_GRS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA_GRS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Глава по БК ГРБС/ГАДБ/ГАИФДБ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GLAVA_GRS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA_GRS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'GLAVA_GRS','Глава по БК ГРБС/ГАДБ/ГАИФДБ','STRING',3,1,1,0,'GLAVA_GRS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Наименование бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_BUD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'NAME_BUD','Наименование бюджета','STRING',512,0,1,1,'NAME_BUD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Наименование финансового органа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_UBP_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'NAME_UBP_FO','Наименование финансового органа','STRING',2000,0,0,0,'NAME_UBP_FO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OKPO_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Код по ОКПО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 8,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OKPO_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OKPO_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'OKPO_FO','Код по ОКПО','STRING',8,1,0,0,'OKPO_FO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Лицевой счет финансового органа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LS_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'LS_FO','Лицевой счет финансового органа','STRING',11,1,0,0,'LS_FO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Наименование органа ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 13,'NAME_TOFK','Наименование органа ФК','STRING',2000,0,0,1,'NAME_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Код органа ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'KOD_TOFK','Код органа ФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FUND_SOURCE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Вид средств',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'FUND_SOURCE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FUND_SOURCE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 15,'FUND_SOURCE','Вид средств','STRING',1,1,0,0,'FUND_SOURCE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'Номер запроса ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_ZF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZF'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 16,'NOM_ZF','Номер запроса ОрФК','STRING',15,0,0,0,'NOM_ZF','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ZF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Дата запроса',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_ZF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ZF'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 17,'DATE_ZF','Дата запроса','DATE',NULL,0,0,0,'DATE_ZF','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'СNAME_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Наименование плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'СNAME_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'СNAME_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 18,'СNAME_PL','Наименование плательщика','STRING',160,0,0,0,'СNAME_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'ИНН плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'INN_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 19,'INN_PL','ИНН плательщика','STRING',12,0,0,0,'INN_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'КПП плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KPP_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 20,'KPP_PL','КПП плательщика','STRING',9,0,0,0,'KPP_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PASP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Паспортные данные плательщика.',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PASP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PASP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 21,'PASP','Паспортные данные плательщика.','STRING',1000,0,0,0,'PASP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'Номер банковского счета плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 22,'BS_PL','Номер банковского счета плательщика','STRING',20,1,0,0,'BS_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'Должность руководителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DOL_RUK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 23,'DOL_RUK','Должность руководителя','STRING',100,0,1,1,'DOL_RUK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'ФИО руководителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_RUK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 24,'NAME_RUK','ФИО руководителя','STRING',50,0,1,1,'NAME_RUK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'Должность ответственного исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DOL_ISP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 25,'DOL_ISP','Должность ответственного исполнителя','STRING',100,0,1,1,'DOL_ISP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 26,
		NAME   		= 'ФИО ответственного исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_ISP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 26,'NAME_ISP','ФИО ответственного исполнителя','STRING',50,0,1,1,'NAME_ISP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TEL_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 27,
		NAME   		= 'Телефон ответственного исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TEL_ISP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TEL_ISP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 27,'TEL_ISP','Телефон ответственного исполнителя','STRING',50,0,0,0,'TEL_ISP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_POD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 28,
		NAME   		= 'Дата подписания документа',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_POD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_POD'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 28,'DATE_POD','Дата подписания документа','DATE',NULL,0,1,1,'DATE_POD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 29,
		NAME   		= 'Должность руководителя ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_RUK_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 29,'DOL_RUK_TOFK','Должность руководителя ОрФК','STRING',100,0,0,0,'DOL_RUK_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 30,
		NAME   		= 'Руководитель ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_RUK_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 30,'NAME_RUK_TOFK','Руководитель ОрФК','STRING',50,0,0,0,'NAME_RUK_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 31,
		NAME   		= 'Должность исполнителя ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_ISP_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 31,'DOL_ISP_TOFK','Должность исполнителя ОрФК','STRING',100,0,0,0,'DOL_ISP_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 32,
		NAME   		= 'Исполнитель ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_ISP_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 32,'NAME_ISP_TOFK','Исполнитель ОрФК','STRING',50,0,0,0,'NAME_ISP_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TEL_ISP_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 33,
		NAME   		= 'Телефон исполнителя ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TEL_ISP_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TEL_ISP_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 33,'TEL_ISP_TOFK','Телефон исполнителя ОрФК','STRING',50,0,0,0,'TEL_ISP_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 34,
		NAME   		= 'Дата отметки',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 34,'DATE_TOFK','Дата отметки','DATE',NULL,0,0,0,'DATE_TOFK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'UFPP'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'UFPP',5,2,'Реквизиты уточняемого платежного документа',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 5,
			ISONCE = 2,
			NAME   = 'Реквизиты уточняемого платежного документа',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LINE_NOM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер записи',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'LINE_NOM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LINE_NOM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'LINE_NOM','Номер записи','NUMBER',NULL,0,1,1,'LINE_NOM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Глобальный идентификатор платежного документа',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'GUID','Глобальный идентификатор платежного документа','GUID',NULL,0,0,0,'GUID','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код платежного документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'KOD_DOC','Код платежного документа','STRING',2,1,1,0,'KOD_DOC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Наименование платежного документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NAME_PP','Наименование платежного документа','STRING',160,0,1,0,'NAME_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Номер платежного документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'NOM_PP','Номер платежного документа','STRING',15,0,1,0,'NOM_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Дата платежного документа',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'DATE_PP','Дата платежного документа','DATE',NULL,0,1,0,'DATE_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Наименование получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'CNAME_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'CNAME_PP','Наименование получателя','STRING',160,0,1,0,'CNAME_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'ИНН получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'INN_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'INN_PP','ИНН получателя','STRING',12,0,1,1,'INN_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'КПП получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KPP_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'KPP_PP','КПП получателя','STRING',9,0,1,1,'KPP_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Код по ОКАТО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OKATO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'OKATO','Код по ОКАТО','STRING',11,1,0,0,'OKATO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Код по КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'KBK','Код по КБК','STRING',20,1,1,1,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'TYPE_KBK','Тип КБК','STRING',2,1,1,1,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Код цели',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 13,'ADD_KLASS','Код цели','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'SUM_PP','Сумма','NUMBER2',NULL,0,1,1,'SUM_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Назначение платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 210,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PURPOSE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 15,'PURPOSE','Назначение платежа','STRING',210,0,0,0,'PURPOSE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'Номер заявки на кассовый расход',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_ZR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZR'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 16,'NOM_ZR','Номер заявки на кассовый расход','STRING',15,0,0,0,'NOM_ZR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ZR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Дата заявки на кассовый расход',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_ZR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ZR'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 17,'DATE_ZR','Дата заявки на кассовый расход','DATE',NULL,0,0,0,'DATE_ZR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Примечание',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOTE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 18,'NOTE','Примечание','STRING',254,0,0,0,'NOTE','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'UFPP_N'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'UFPP_N',6,2,'Новые реквизиты платежного документа',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 6,
			ISONCE = 2,
			NAME   = 'Новые реквизиты платежного документа',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LINE_NOM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер записи',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'LINE_NOM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LINE_NOM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'LINE_NOM','Номер записи','NUMBER',NULL,0,1,1,'LINE_NOM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'CNAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'CNAME_UBP','Наименование получателя','STRING',160,0,1,0,'CNAME_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'ИНН получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'INN_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'INN_UBP','ИНН получателя','STRING',12,0,1,0,'INN_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'КПП получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KPP_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'KPP_UBP','КПП получателя','STRING',9,0,1,0,'KPP_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Код по ОКАТО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OKATO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'OKATO','Код по ОКАТО','STRING',11,1,1,0,'OKATO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Лицевой счет Получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LS_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'LS_UBP','Лицевой счет Получателя','STRING',11,1,1,0,'LS_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Код по КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'KBK','Код по КБК','STRING',20,1,1,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'TYPE_KBK','Тип КБК','STRING',2,1,1,0,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Код цели',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'ADD_KLASS','Код цели','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Уточняемая сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'SUM','Уточняемая сумма','NUMBER2',NULL,0,0,0,'SUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Назначение платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 210,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PURPOSE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'PURPOSE','Назначение платежа','STRING',210,0,0,0,'PURPOSE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FUND_SOURCE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Вид средств',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'FUND_SOURCE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FUND_SOURCE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'FUND_SOURCE','Вид средств','STRING',1,1,0,0,'FUND_SOURCE','',''
GO

GO
/****** Объект: Код ЭКР******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_CODE_EKR_DED_PR_DGH')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_CODE_EKR_DED_PR_DGH')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_CODE_EKR_DED_PR_DGH')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_CODE_EKR_DED_PR_DGH')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_CODE_EKR_DED_PR_DGH'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_CODE_EKR_DED_PR_DGH')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_CODE_EKR_DED_PR_DGH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_CODE_EKR_DED_PR_DGH', 'Код ЭКР', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DED_PAYROLL_DGH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_CODE_EKR_DED_PR_DGH', NAME = 'Код ЭКР', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DED_PAYROLL_DGH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_CODE_EKR_DED_PR_DGH'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DED_PR_DGH', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DED_PR_DGH', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_ITEM'', oForm.ALIAS, ''LINK,CODE'', ''LINK_EKR,CODE_EKR'', '''', '''', "CODE LIKE ''21%'' OR CODE LIKE ''22%''  OR CODE LIKE ''26%''", .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DED_PR_DGH', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DED_PR_DGH', 'CONTROLSOURCE', 'm.cAlias + ".CODE_EKR"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DED_PR_DGH', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DED_PR_DGH', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DED_PR_DGH', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_EKR"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DED_PR_DGH', 'CONTROL_NAME_EDIT', 'Apageframe1.Page1.Asel_spr2'
GO



GO
/****** Объект: Код ЭКР******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_CODE_EKR_PR_T_DGH')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_CODE_EKR_PR_T_DGH')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_CODE_EKR_PR_T_DGH')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_CODE_EKR_PR_T_DGH')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_CODE_EKR_PR_T_DGH'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_CODE_EKR_PR_T_DGH')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_CODE_EKR_PR_T_DGH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_CODE_EKR_PR_T_DGH', 'Код ЭКР', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DED_PR_TABLE_DGH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_CODE_EKR_PR_T_DGH', NAME = 'Код ЭКР', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DED_PR_TABLE_DGH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_CODE_EKR_PR_T_DGH'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_PR_T_DGH', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_PR_T_DGH', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_ITEM'', oForm.APageframe1.Page2.BSpisok.BGrid1.RecordSource, ''LINK,CODE'', ''LINK_EKR,CODE_EKR'', '''', '''', "CODE LIKE ''21%'' OR CODE LIKE ''22%'' OR CODE LIKE ''26%''", .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_PR_T_DGH', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_PR_T_DGH', 'CONTROLSOURCE', 'm.cAlias + ".CODE_EKR"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_PR_T_DGH', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_PR_T_DGH', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_EKR"'
GO


GO
/****** Объект: Ссылка ЭКР******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_LINK_EKR_DED_PR_DGH')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_LINK_EKR_DED_PR_DGH')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_LINK_EKR_DED_PR_DGH')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_LINK_EKR_DED_PR_DGH')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_LINK_EKR_DED_PR_DGH'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_LINK_EKR_DED_PR_DGH')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_LINK_EKR_DED_PR_DGH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_LINK_EKR_DED_PR_DGH', 'Ссылка ЭКР', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DED_PAYROLL_DGH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_LINK_EKR_DED_PR_DGH', NAME = 'Ссылка ЭКР', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DED_PAYROLL_DGH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_LINK_EKR_DED_PR_DGH'
GO
EXEC X_SET_PROP 'COLUMN_LINK_EKR_DED_PR_DGH', 'TITLE', 'Ссылка ЭКР (Используется, если аванс суммой)'
GO
EXEC X_SET_PROP 'COLUMN_LINK_EKR_DED_PR_DGH', 'CONTROLSOURCE', 'm.cAlias + ".LINK_EKR"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_EKR_DED_PR_DGH', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'COLUMN_LINK_EKR_DED_PR_DGH', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK_EKR"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_EKR_DED_PR_DGH', 'COMMENTARY', 'ЭКР (Используется, если аванс суммой)'
GO
GO
/****** Объект: Должности******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'DICTIONARY_POST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'DICTIONARY_POST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'DICTIONARY_POST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'DICTIONARY_POST')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'DICTIONARY_POST'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DICTIONARY_POST')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICTIONARY_POST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICTIONARY_POST', 'Должности', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICTION_KADR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),1,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICTIONARY_POST', NAME = 'Должности', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICTION_KADR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DICTIONARY_POST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_POST_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_POST_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_POST_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_POST_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_POST_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_POST_CODE', 'Код должности', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_POST_CODE', NAME = 'Код должности', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_POST_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_POST_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_POST_NAME', 'Наименование должности', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_POST_NAME', NAME = 'Наименование должности', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_POST_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_PKG_POST_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_PKG_POST_CODE', 'Код группы', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_PKG_POST_CODE', NAME = 'Код группы', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_PKG_POST_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_PKG_POST_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_PKG_POST_NAME', 'Наименование группы', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_PKG_POST_NAME', NAME = 'Наименование группы', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_PKG_POST_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_PKG_POST_DATE_BEGIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_PKG_POST_DATE_BEGIN', 'Начало периода', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_PKG_POST_DATE_BEGIN', NAME = 'Начало периода', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_PKG_POST_DATE_BEGIN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_PKG_POST_DATE_END')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_PKG_POST_DATE_END', 'Конец периода', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_PKG_POST_DATE_END', NAME = 'Конец периода', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_PKG_POST_DATE_END'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICTIONARY_POST_HIST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICTIONARY_POST_HIST', 'История должности', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICTIONARY_POST_HIST', NAME = 'История должности', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DICTIONARY_POST_HIST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICT_POST_LIST_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICT_POST_LIST_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST_HIST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICT_POST_LIST_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST_HIST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICT_POST_LIST_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICT_POST_LIST_CODE_PKG')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICT_POST_LIST_CODE_PKG', 'Код ПКГ', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST_HIST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICT_POST_LIST_CODE_PKG', NAME = 'Код ПКГ', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST_HIST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICT_POST_LIST_CODE_PKG'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICT_POST_LIST_NAME_PKG')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICT_POST_LIST_NAME_PKG', 'Наименование ПКГ', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST_HIST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICT_POST_LIST_NAME_PKG', NAME = 'Наименование ПКГ', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST_HIST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICT_POST_LIST_NAME_PKG'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICT_POST_LIST_DATE_BEGIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICT_POST_LIST_DATE_BEGIN', 'Начало периода', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST_HIST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICT_POST_LIST_DATE_BEGIN', NAME = 'Начало периода', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST_HIST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICT_POST_LIST_DATE_BEGIN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICT_POST_LIST_DATE_END')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICT_POST_LIST_DATE_END', 'Конец периода', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST_HIST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICT_POST_LIST_DATE_END', NAME = 'Конец периода', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_POST_HIST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICT_POST_LIST_DATE_END'
GO
EXEC X_SET_PROP 'DICTIONARY_POST', 'TITLE', 'Должности'
GO
EXEC X_SET_PROP 'DICTIONARY_POST', 'INIT_OBJECT_METHOD', 'X_SPISOK("DICTIONARY_POST")'
GO
EXEC X_SET_PROP 'DICTIONARY_POST', 'REMOVE_OBJECT_METHOD', 'KU_POST_DELETE(oForm.Alias)'
GO
EXEC X_SET_PROP 'DICTIONARY_POST', 'SAVE_OBJECT_METHOD', 'post_save(oForm)'
GO
EXEC X_SET_PROP 'DICTIONARY_POST', 'EDIT_OBJECT_METHOD', 'X_BROW(''x_brow_rec_post'')'
GO
EXEC X_SET_PROP 'DICTIONARY_POST', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''DICTIONARY_POST'')'
GO
EXEC X_SET_PROP 'DICTIONARY_POST', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS(''DICTIONARY_POST'')'
GO
EXEC X_SET_PROP 'DICTIONARY_POST', 'OPEN_CODE', 'CODE'
GO
EXEC X_SET_PROP 'DICTIONARY_POST', 'SERVER_TABLE_NAME', 'POST'
GO
EXEC X_SET_PROP 'DICTIONARY_POST', 'HELP_TOPIC', 'Должности'
GO
EXEC X_SET_PROP 'DICTIONARY_POST', 'PREPARE_NEW_RECORD', 'XU_NEW_TABLE_RECORD(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'DICTIONARY_POST', 'OPERATION_MASK', '31'
GO
EXEC X_SET_PROP 'DICTIONARY_POST', 'EDIT_OBJECT_METHOD_SQL', 'KU_EDIT_OBJECT_METHOD @cObject = ''DICTIONARY_POST'''
GO
EXEC X_SET_PROP 'DICTIONARY_POST', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''DICTIONARY_POST'''
GO
EXEC X_SET_PROP 'DICTIONARY_POST', 'SAVE_OBJECT_METHOD_SQL', 'KU_WEB_SAVE_OBJECT @ProcName = ''KU_POST_SAVE'', @ObjName = ''DICTIONARY_POST'', @ParList = ''CODE, NAME'''
GO
EXEC X_SET_PROP 'COLUMN_POST_CHECKED', 'VISIBLE', '25'
GO
EXEC X_SET_PROP 'COLUMN_POST_CHECKED', 'CONTROLSOURCE', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_POST_CHECKED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_POST_CHECKED', 'ROWSOURCE', 'CHECKED'
GO
EXEC X_SET_PROP 'COLUMN_POST_CHECKED', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'COLUMN_POST_CHECKED', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_POST_CHECKED', 'ASPTYPE', 'checkbox'
GO
EXEC X_SET_PROP 'COLUMN_POST_CHECKED', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'COLUMN_POST_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'COLUMN_POST_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'COLUMN_POST_CODE', 'CONTROLSOURCE', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'COLUMN_POST_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_POST_CODE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_POST_CODE', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'COLUMN_POST_CODE', 'TYPE_FIELD_DICT', 'CHAR(6)'
GO
EXEC X_SET_PROP 'COLUMN_POST_CODE', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'COLUMN_POST_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'COLUMN_POST_CODE', 'CONTROL_NAME', 'ATxt1'
GO
EXEC X_SET_PROP 'COLUMN_POST_CODE', 'CONTROL_NAME_EDIT', 'Atxt1'
GO
EXEC X_SET_PROP 'COLUMN_POST_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'COLUMN_POST_CODE', 'COMMENTARY', 'Код должности'
GO
EXEC X_SET_PROP 'COLUMN_POST_CODE', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'COLUMN_POST_CODE', 'ATTRIBUTES', ' style="Z-INDEX: 102; LEFT: 136px; POSITION: absolute; TOP: 16px"'
GO
EXEC X_SET_PROP 'COLUMN_POST_CODE', 'LABEL_ATTRIBUTES', ' style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 16px"'
GO
EXEC X_SET_PROP 'COLUMN_POST_CODE', 'FIELD_ALIAS', 'DICTIONARY_POST'
GO
EXEC X_SET_PROP 'COLUMN_POST_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'CONTROLSOURCE', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(150)'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'SHORT_CODE_OBJ', 'NAME'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'CONTROL_NAME', 'ATxt2'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'CONTROL_NAME_EDIT', 'Atxt2'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'QUICKSEARCH', '1'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'COMMENTARY', 'Наименование должности'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'ATTRIBUTES', ' style="Z-INDEX: 104; LEFT: 136px; POSITION: absolute; TOP: 56px"
Width="377px"'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'LABEL_ATTRIBUTES', ' style="Z-INDEX: 103; LEFT: 16px; POSITION: absolute; TOP: 56px"'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'FIELD_ALIAS', 'DICTIONARY_POST'
GO
EXEC X_SET_PROP 'COLUMN_POST_NAME', 'FIELD_DATA', 'NAME'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_CODE', 'TITLE', 'Код группы'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("SA_PKG_POST",oForm.ALIAS,"LINK, CODE, NAME", "LINK_PKG, CODE_PKG, NAME_PKG", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_CODE', 'CONTROLSOURCE', 'm.cAlias+".CODE_PKG"'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_CODE', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_CODE', 'TYPE_FIELD_DICT', 'CHAR(6)'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_CODE', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CODE_PKG"'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_CODE', 'CONTROL_NAME', 'Asel_spr3'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_CODE', 'CONTROL_NAME_EDIT', 'Asel_spr3'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_CODE', 'COMMENTARY', 'Код профессионально-квалификационной группы должности'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_CODE', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_CODE', 'ATTRIBUTES', ' style="Z-INDEX: 102; LEFT: 136px; POSITION: absolute; TOP: 16px"'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_CODE', 'LABEL_ATTRIBUTES', ' style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 16px"'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_CODE', 'FIELD_ALIAS', 'DICTIONARY_POST'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_NAME', 'TITLE', 'Наименование группы'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_NAME', 'CONTROLSOURCE', 'm.cAlias+".NAME_PKG"'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_NAME', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(150)'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_NAME', 'SHORT_CODE_OBJ', 'NAME'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NAME_PKG"'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_NAME', 'CONTROL_NAME', 'ATxtN3'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_NAME', 'CONTROL_NAME_EDIT', 'ATxtN3'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_NAME', 'QUICKSEARCH', '1'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_NAME', 'COMMENTARY', 'Наименование профессионально-квалификационной группы должности'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_NAME', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_NAME', 'ATTRIBUTES', ' style="Z-INDEX: 104; LEFT: 136px; POSITION: absolute; TOP: 56px"
Width="377px"'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_NAME', 'LABEL_ATTRIBUTES', ' style="Z-INDEX: 103; LEFT: 16px; POSITION: absolute; TOP: 56px"'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_NAME', 'FIELD_ALIAS', 'DICTIONARY_POST'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_NAME', 'FIELD_DATA', 'NAME'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_DATE_BEGIN', 'TITLE', 'Начало периода'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_DATE_BEGIN', 'EDIT_OBJECT_METHOD', 'ALIB_GET_DATE(oForm,oForm.pageframe1.page1.BSpisok.bgrid1.column4.text1)'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_DATE_BEGIN', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_DATE_BEGIN', 'CONTROLSOURCE', 'm.cAlias + ".date_begin"'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_DATE_BEGIN', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_DATE_BEGIN', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_DATE_BEGIN', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_DATE_BEGIN', 'SHORT_CODE_OBJ', 'date_begin'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_DATE_BEGIN', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".date_begin"'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_DATE_END', 'TITLE', 'Конец периода'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_DATE_END', 'EDIT_OBJECT_METHOD', 'ALIB_GET_DATE(oForm,oForm.pageframe1.page1.BSpisok.bgrid1.column5.text1)'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_DATE_END', 'CONTROLSOURCE', 'm.cAlias + ".date_end"'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_DATE_END', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_DATE_END', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_DATE_END', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_DATE_END', 'SHORT_CODE_OBJ', 'date_end'
GO
EXEC X_SET_PROP 'COLUMN_PKG_POST_DATE_END', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".date_end"'
GO
EXEC X_SET_PROP 'DICTIONARY_POST_HIST', 'TITLE', 'История должности'
GO
EXEC X_SET_PROP 'DICTIONARY_POST_HIST', 'INIT_OBJECT_METHOD', 'X_SPISOK("DICTIONARY_POST_LIST_PKG")'
GO
EXEC X_SET_PROP 'DICTIONARY_POST_HIST', 'INIT_OBJECT_PROG', 'A_SPISOK_MENU(oForm)
A_SPISOK_UPD (oForm, 0, .T.)'
GO
EXEC X_SET_PROP 'DICTIONARY_POST_HIST', 'SELECT_RECORDS_METHOD', 'sa_child_table_alias_POST(m.nLink, m.cAlias, ''DICTIONARY_POST_LIST_PKG'',''CODE'' )'
GO
EXEC X_SET_PROP 'DICTIONARY_POST_HIST', 'SELECT_RECORDS_METHOD_EDIT', 'sa_child_table_alias_post(m.nLink, m.cAlias, ''DICTIONARY_POST_LIST_PKG'',''CODE'' )'
GO
EXEC X_SET_PROP 'DICTIONARY_POST_HIST', 'OPEN_CODE', 'link'
GO
EXEC X_SET_PROP 'DICTIONARY_POST_HIST', 'CAPTION', 'История должности'
GO
EXEC X_SET_PROP 'DICTIONARY_POST_HIST', 'MSG_SEL_ONE', ''
GO
EXEC X_SET_PROP 'DICTIONARY_POST_HIST', 'SERVER_TABLE_NAME', ''
GO
EXEC X_SET_PROP 'DICTIONARY_POST_HIST', 'PREPARE_NEW_RECORD', 'x_new_diction_record(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_MARKER', 'VISIBLE', '25'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_MARKER', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_MARKER', 'ROWSOURCE', 'CHECKED'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_MARKER', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_MARKER', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_MARKER', 'ASPTYPE', 'checkbox'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_MARKER', 'FIELD_DATA', 'checked'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_CODE_PKG', 'TITLE', 'Код ПКГ'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_CODE_PKG', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("SA_PKG_POST",oForm.pageframe1.page1.BSpisok.bgrid1.RecordSource,"LINK_PKG, CODE_PKG, NAME_PKG", "LINK_PKG, CODE_PKG, NAME_PKG", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_CODE_PKG', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_CODE_PKG', 'CONTROLSOURCE', 'm.cAlias + ".code_PKG"'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_CODE_PKG', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_CODE_PKG', 'OPERATE_METHOD', 'IIF(NVL(EVALUATE(m.cAliasOperate+''.LINK''),0)>0,x_edit_rec(''DICTIONARY_POST'',EVALUATE(m.cAliasOperate+''.LINK'')),"")'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_CODE_PKG', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_CODE_PKG', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_CODE_PKG', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".code_PKG"'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_CODE_PKG', 'CONTROL_NAME_EDIT', 'Atextbox01'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_NAME_PKG', 'TITLE', 'Наименование ПКГ'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_NAME_PKG', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("SA_PKG_POST",oForm.oformRefresh.pageframe1.page1.BSpisok.bgrid1.RecordSource,"LINK_PKG, CODE_PKG, NAME_PKG", "LINK_PKG, CODE_PKG, NAME_PKG", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_NAME_PKG', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_NAME_PKG', 'CONTROLSOURCE', 'm.cAlias + ".NAME_PKG"'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_NAME_PKG', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_NAME_PKG', 'OPERATE_METHOD', 'IIF(NVL(EVALUATE(m.cAliasOperate+''.LINK''),0)>0,x_edit_rec(''DICTIONARY_POST'',EVALUATE(m.cAliasOperate+''.LINK'')),"")'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_NAME_PKG', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_NAME_PKG', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_NAME_PKG', 'SHORT_CODE_OBJ', 'NAME_PKG'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_NAME_PKG', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_PKG"'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_NAME_PKG', 'CONTROL_NAME_EDIT', 'Atextbox02'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_DATE_BEGIN', 'TITLE', 'Начало периода'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_DATE_BEGIN', 'EDIT_OBJECT_METHOD', 'ALIB_GET_DATE(oForm,oForm.pageframe1.page1.BSpisok.bgrid1.column4.text1)'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_DATE_BEGIN', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_DATE_BEGIN', 'CONTROLSOURCE', 'm.cAlias + ".date_begin"'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_DATE_BEGIN', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_DATE_BEGIN', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_DATE_BEGIN', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_DATE_BEGIN', 'SHORT_CODE_OBJ', 'date_begin'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_DATE_BEGIN', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".date_begin"'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_DATE_END', 'TITLE', 'Конец периода'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_DATE_END', 'EDIT_OBJECT_METHOD', 'ALIB_GET_DATE(oForm,oForm.pageframe1.page1.BSpisok.bgrid1.column5.text1)'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_DATE_END', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_DATE_END', 'CONTROLSOURCE', 'm.cAlias + ".date_end"'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_DATE_END', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_DATE_END', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_DATE_END', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_DATE_END', 'SHORT_CODE_OBJ', 'date_end'
GO
EXEC X_SET_PROP 'DICT_POST_LIST_DATE_END', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".date_end"'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'DICTIONARY_POST', 'Дело-КС', 5,0
GO
EXEC DBO.W_SPERM_WRITE 'DICTIONARY_POST', 'Кадры-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'DICTIONARY_POST', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'DICTIONARY_POST', 'Смета-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'DICTIONARY_POST', 'Главный бухгалтер', 63,0
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Справочник должностей"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '4187')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DICTIONARY_POST')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '4187'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '4467'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, '4467', 'Справочник должностей', @ORD, NULL, 1, @LINK_SELF, 'DICTIONARY', @OBJECT, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Должности"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_DICTIONARY_FOLDER')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DICTIONARY_POST')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_DICTIONARY_FOLDER'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_DICTIONARY_SUBDIVISION'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'KADR_DICTIONARY_SUBDIVISION', 'Должности', @ORD, NULL, 1, @LINK_SELF, 'DICTIONARY', @OBJECT, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Справочник должностей"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SMETA_KADRY_DICT')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DICTIONARY_POST')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SMETA_KADRY_DICT'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SMETA_DICTIONARY_POST'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'SMETA_DICTIONARY_POST', 'Справочник должностей', @ORD, NULL, 1, @LINK_SELF, 'DICTIONARY', @OBJECT, @LINK_VAR, 3
GO


GO
/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Выплаты и иные вознаграждения по инвалидам I, II или III группы"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'SQL_REP_SAL_ESN_PFR_INV')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SALARY_ESN')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'QUERY_SQL')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SALARY_ESN'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'NV_REP_SAL_ESN_PFR_INV'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'NV_REP_SAL_ESN_PFR_INV', 'Выплаты и иные вознаграждения по инвалидам I, II или III группы', @ORD, NULL, 1, @LINK_SELF, 'REPORT', @OBJECT, @LINK_VAR, 3
GO


GO
/****** Объект: Начало периода******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'PKG_POST_DATE_BEGIN')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'PKG_POST_DATE_BEGIN')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'PKG_POST_DATE_BEGIN')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'PKG_POST_DATE_BEGIN')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'PKG_POST_DATE_BEGIN'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'PKG_POST_DATE_BEGIN')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PKG_POST_DATE_BEGIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PKG_POST_DATE_BEGIN', 'Начало периода', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_LIST_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PKG_POST_DATE_BEGIN', NAME = 'Начало периода', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_LIST_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PKG_POST_DATE_BEGIN'
GO
EXEC X_SET_PROP 'PKG_POST_DATE_BEGIN', 'TITLE', 'Начало периода'
GO
EXEC X_SET_PROP 'PKG_POST_DATE_BEGIN', 'EDIT_OBJECT_METHOD', 'ALIB_GET_DATE(oForm,oForm.pageframe1.page1.BSpisok.bgrid1.column4.text1)'
GO
EXEC X_SET_PROP 'PKG_POST_DATE_BEGIN', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PKG_POST_DATE_BEGIN', 'CONTROLSOURCE', 'm.cAlias + ".date_begin"'
GO
EXEC X_SET_PROP 'PKG_POST_date_BEGIN', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PKG_POST_date_BEGIN', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PKG_POST_date_BEGIN', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'PKG_POST_date_BEGIN', 'SHORT_CODE_OBJ', 'date_begin'
GO
EXEC X_SET_PROP 'PKG_POST_date_BEGIN', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".date_begin"'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/



/****** Объект: Конец периода******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'PKG_POST_date_END')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'PKG_POST_date_END')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'PKG_POST_date_END')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'PKG_POST_date_END')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'PKG_POST_date_END'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'PKG_POST_date_END')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PKG_POST_date_END')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PKG_POST_date_END', 'Конец периода', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_LIST_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PKG_POST_date_END', NAME = 'Конец периода', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_LIST_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PKG_POST_date_END'
GO
EXEC X_SET_PROP 'PKG_POST_date_END', 'TITLE', 'Конец периода'
GO
EXEC X_SET_PROP 'PKG_POST_date_END', 'EDIT_OBJECT_METHOD', 'ALIB_GET_DATE(oForm,oForm.pageframe1.page1.BSpisok.bgrid1.column5.text1)'
GO
EXEC X_SET_PROP 'PKG_POST_date_END', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PKG_POST_date_END', 'CONTROLSOURCE', 'm.cAlias + ".date_end"'
GO
EXEC X_SET_PROP 'PKG_POST_date_END', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PKG_POST_date_END', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PKG_POST_date_END', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'PKG_POST_date_END', 'SHORT_CODE_OBJ', 'date_end'
GO
EXEC X_SET_PROP 'PKG_POST_date_END', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".date_end"'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
/****** Объект: Тип корректировки******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_TYPE_KOR')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORTS_ATR_TYPE_KOR')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORTS_ATR_TYPE_KOR')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORTS_ATR_TYPE_KOR')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_TYPE_KOR'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_TYPE_KOR')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORTS_ATR_TYPE_KOR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORTS_ATR_TYPE_KOR', 'Тип корректировки', 54, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORTS_ATR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_ATRIBUT'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORTS_ATR_TYPE_KOR', NAME = 'Тип корректировки', ORDERS = '54', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORTS_ATR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_ATRIBUT'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORTS_ATR_TYPE_KOR'
GO
EXEC X_SET_PROP 'REPORTS_ATR_TYPE_KOR', 'NAME', 'Тип корректировки'
GO
EXEC X_SET_PROP 'REPORTS_ATR_TYPE_KOR', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("RN_VIEW_TYPE_KOR",oForm.ALIAS_ATR, "ALLTRIM(code)", "REPORTS_ATR_TYPE_KOR", "", "", "", .T., 0, oForm, oObj)'
GO
EXEC X_SET_PROP 'REPORTS_ATR_TYPE_KOR', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORTS_ATR_TYPE_KOR', 'CONTROL_TYPE', '1'
GO
EXEC X_SET_PROP 'REPORTS_ATR_TYPE_KOR', 'SHORT_NAME', 'Тип корректировки'
GO
EXEC X_SET_PROP 'REPORTS_ATR_TYPE_KOR', 'CHECK_WHEN', 'ALIB_NEED_SPR (oObj)'
GO
EXEC X_SET_PROP 'REPORTS_ATR_TYPE_KOR', 'MAXWIDTH', '11'
GO
EXEC X_SET_PROP 'REPORTS_ATR_TYPE_KOR', 'DICTIONARY', 'RN_VIEW_TYPE_KOR'
GO
EXEC X_SET_PROP 'REPORTS_ATR_TYPE_KOR', 'DICTIONARY_COLUMNS_LIST', 'REPORTS_ATR_TYPE_KOR'
GO
EXEC X_SET_PROP 'REPORTS_ATR_TYPE_KOR', 'DICTIONARY_FIELDS_LIST', 'CODE'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'REPORTS_ATR_TYPE_KOR', 'Свод-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'REPORTS_ATR_TYPE_KOR', 'Зарплата-КС', 63,0
GO


GO
/****** Объект: Справочник  Типов корректировок******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'RN_VIEW_TYPE_KOR')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'RN_VIEW_TYPE_KOR')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'RN_VIEW_TYPE_KOR')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'RN_VIEW_TYPE_KOR')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'RN_VIEW_TYPE_KOR'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'RN_VIEW_TYPE_KOR')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RN_VIEW_TYPE_KOR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RN_VIEW_TYPE_KOR', 'Справочник типов корректировок', 111, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_DICTIONARY'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RN_VIEW_TYPE_KOR', NAME = 'Справочник типов корректировок', ORDERS = '122', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_DICTIONARY'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='RN_VIEW_TYPE_KOR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RN_VIEW_TYPE_KOR_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RN_VIEW_TYPE_KOR_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='RN_VIEW_TYPE_KOR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RN_VIEW_TYPE_KOR_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RN_VIEW_TYPE_KOR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RN_VIEW_TYPE_KOR_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RN_VIEW_TYPE_KOR_TYPE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RN_VIEW_TYPE_KOR_TYPE', 'Тип', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='RN_VIEW_TYPE_KOR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RN_VIEW_TYPE_KOR_TYPE', NAME = 'Тип', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RN_VIEW_TYPE_KOR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RN_VIEW_TYPE_KOR_TYPE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RN_VIEW_TYPE_KOR_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RN_VIEW_TYPE_KOR_NAME', 'Комментарий', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='RN_VIEW_TYPE_KOR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RN_VIEW_TYPE_KOR_NAME', NAME = 'Комментарий', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RN_VIEW_TYPE_KOR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RN_VIEW_TYPE_KOR_NAME'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR', 'TITLE', 'Справочник типов корректировок'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR', 'INIT_OBJECT_METHOD', 'x_spisok(''RN_VIEW_TYPE_KOR'')'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''RN_VIEW_TYPE_KOR'')'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR', 'OPEN_CODE', 'CODE'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR', 'SERVER_TABLE_NAME', 'RN_VIEW_TYPE_KOR'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR', 'HELP_TOPIC', 'Справочник типов корректировок'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR', 'OPERATION_MASK', '31'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''RN_VIEW_TYPE_KOR'''
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_MARKER', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_MARKER', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_MARKER', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_MARKER', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_MARKER', 'ASPTYPE', 'checkbox'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_MARKER', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_TYPE', 'TITLE', 'Тип'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_TYPE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_TYPE', 'CONTROLSOURCE', 'm.cAlias + ".code"'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_TYPE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_TYPE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".code"'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_TYPE', 'CONTROL_NAME_EDIT', 'ATxt1'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_TYPE', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_TYPE', 'ATTRIBUTES', 'style="Z-INDEX: 102; LEFT: 200px; POSITION: absolute; TOP: 16px""  Width="100px"'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_TYPE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_NAME', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_NAME', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_NAME', 'CONTROL_NAME_EDIT', 'ATxt2'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_NAME', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_NAME', 'ATTRIBUTES', 'style="Z-INDEX: 102; LEFT: 200px; POSITION: absolute; TOP: 46px""  Width="550px"'
GO
EXEC X_SET_PROP 'RN_VIEW_TYPE_KOR_NAME', 'FIELD_DATA', 'NAME'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'RN_VIEW_TYPE_KOR', 'Свод-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'RN_VIEW_TYPE_KOR', 'Зарплата-КС', 63,0
GO


GO
/****** Объект: ПКГ должностей******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SA_PKG_POST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'SA_PKG_POST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'SA_PKG_POST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'SA_PKG_POST')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SA_PKG_POST'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SA_PKG_POST')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_PKG_POST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_PKG_POST', 'ПКГ должностей', 25, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICT_SAL_KADR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_PKG_POST', NAME = 'ПКГ должностей', ORDERS = '25', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICT_SAL_KADR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='SA_PKG_POST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PKG_POST_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PKG_POST_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PKG_POST_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PKG_POST_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PKG_POST_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PKG_POST_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PKG_POST_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PKG_POST_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PKG_POST_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PKG_POST_NAME', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PKG_POST_NAME', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PKG_POST_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PKG_POST_OKLAD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PKG_POST_OKLAD', 'Оклад', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PKG_POST_OKLAD', NAME = 'Оклад', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PKG_POST_OKLAD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_PKG_LIST_POST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_PKG_LIST_POST', 'Должности группы', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_PKG_LIST_POST', NAME = 'Должности группы', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='SA_PKG_LIST_POST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PKG_OKLAD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PKG_OKLAD', 'Справочник базовых окладов', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PKG_OKLAD', NAME = 'Справочник базовых окладов', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='PKG_OKLAD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PKG_OKLAD_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PKG_OKLAD_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='PKG_OKLAD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PKG_OKLAD_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='PKG_OKLAD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PKG_OKLAD_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PKG_OKLAD_DATE_BEGIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PKG_OKLAD_DATE_BEGIN', 'Дата ввода', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='PKG_OKLAD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PKG_OKLAD_DATE_BEGIN', NAME = 'Дата ввода', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='PKG_OKLAD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PKG_OKLAD_DATE_BEGIN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PKG_OKLAD_SUMMA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PKG_OKLAD_SUMMA', 'Сумма', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='PKG_OKLAD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PKG_OKLAD_SUMMA', NAME = 'Сумма', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='PKG_OKLAD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PKG_OKLAD_SUMMA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PKG_OKLAD_MARKER_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PKG_OKLAD_MARKER_1', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_LIST_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PKG_OKLAD_MARKER_1', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_LIST_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PKG_OKLAD_MARKER_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PKG_POST_CODE_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PKG_POST_CODE_1', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_LIST_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PKG_POST_CODE_1', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_LIST_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PKG_POST_CODE_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PKG_POST_NAME_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PKG_POST_NAME_1', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_LIST_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PKG_POST_NAME_1', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_LIST_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PKG_POST_NAME_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PKG_POST_DATE_BEGIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PKG_POST_DATE_BEGIN', 'Начало периода', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_LIST_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PKG_POST_DATE_BEGIN', NAME = 'Начало периода', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_LIST_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PKG_POST_DATE_BEGIN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PKG_POST_date_END')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PKG_POST_date_END', 'Конец периода', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_LIST_POST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PKG_POST_date_END', NAME = 'Конец периода', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PKG_LIST_POST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PKG_POST_date_END'
GO
EXEC X_SET_PROP 'SA_PKG_POST', 'TITLE', 'Профессионально-квалификационные группы должностей'
GO
EXEC X_SET_PROP 'SA_PKG_POST', 'INIT_OBJECT_METHOD', 'X_SPISOK("SA_PKG_POST")'
GO
EXEC X_SET_PROP 'SA_PKG_POST', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "SA_PKG_POST", "SA_PKG_POST_DELETE", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'SA_PKG_POST', 'SAVE_OBJECT_METHOD', 'pkg_save(oForm)'
GO
EXEC X_SET_PROP 'SA_PKG_POST', 'EDIT_OBJECT_METHOD', 'SALARY_BROW(''pkg_post'')'
GO
EXEC X_SET_PROP 'SA_PKG_POST', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''SA_PKG_POST'')'
GO
EXEC X_SET_PROP 'SA_PKG_POST', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS(''SA_PKG_POST'')'
GO
EXEC X_SET_PROP 'SA_PKG_POST', 'OPEN_CODE', 'code'
GO
EXEC X_SET_PROP 'SA_PKG_POST', 'MSG_SEL_ONE', 'IIF(ISNULL(SHORT_NAME),'''', SHORT_NAME) + [-] + IIF(ISNULL(NAME), '''', NAME)'
GO
EXEC X_SET_PROP 'SA_PKG_POST', 'SERVER_TABLE_NAME', 'PKG_POST'
GO
EXEC X_SET_PROP 'SA_PKG_POST', 'HELP_TOPIC', 'ПКГ должностей'
GO
EXEC X_SET_PROP 'SA_PKG_POST', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'PKG_POST_CHECKED', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'PKG_POST_CHECKED', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'PKG_POST_CHECKED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'PKG_POST_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'PKG_POST_CODE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PKG_POST_CODE', 'CONTROLSOURCE', 'm.cAlias + ".code"'
GO
EXEC X_SET_PROP 'PKG_POST_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PKG_POST_CODE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PKG_POST_CODE', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'PKG_POST_CODE', 'SHORT_CODE_OBJ', 'name_short'
GO
EXEC X_SET_PROP 'PKG_POST_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".code"'
GO
EXEC X_SET_PROP 'PKG_POST_CODE', 'CONTROL_NAME_EDIT', 'Atextbox01'
GO
EXEC X_SET_PROP 'PKG_POST_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'PKG_POST_NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PKG_POST_NAME', 'CONTROLSOURCE', 'm.cAlias + ".NAME"'
GO
EXEC X_SET_PROP 'PKG_POST_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PKG_POST_NAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PKG_POST_NAME', 'STORAGE', 'ETS_HEAD'
GO
EXEC X_SET_PROP 'PKG_POST_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'PKG_POST_NAME', 'SHORT_CODE_OBJ', 'NAME'
GO
EXEC X_SET_PROP 'PKG_POST_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME"'
GO
EXEC X_SET_PROP 'PKG_POST_NAME', 'CONTROL_NAME_EDIT', 'Atextbox02'
GO
EXEC X_SET_PROP 'PKG_POST_OKLAD', 'TITLE', 'Базовый оклад'
GO
EXEC X_SET_PROP 'PKG_POST_OKLAD', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'PKG_POST_OKLAD', 'CONTROLSOURCE', 'm.cAlias + ".OKLAD"'
GO
EXEC X_SET_PROP 'PKG_POST_OKLAD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PKG_POST_OKLAD', 'TYPE_FIELD_DICT', 'numeric(18,2)'
GO
EXEC X_SET_PROP 'PKG_POST_OKLAD', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".OKLAD"'
GO
EXEC X_SET_PROP 'SA_PKG_LIST_POST', 'TITLE', 'Должности группы'
GO
EXEC X_SET_PROP 'SA_PKG_LIST_POST', 'INIT_OBJECT_METHOD', 'X_SPISOK("SA_PKG_LIST_POST")'
GO
EXEC X_SET_PROP 'SA_PKG_LIST_POST', 'INIT_OBJECT_PROG', 'A_SPISOK_MENU(oForm)
A_SPISOK_UPD (oForm, 0, .T.)'
GO
EXEC X_SET_PROP 'SA_PKG_LIST_POST', 'SELECT_RECORDS_METHOD', 'sa_child_table_alias(m.nLinkPKG, m.cAlias, ''SA_PKG_LIST_POST'',''CODE'' )'
GO
EXEC X_SET_PROP 'SA_PKG_LIST_POST', 'SELECT_RECORDS_METHOD_EDIT', 'sa_child_table_alias(m.nLinkPKG, m.cAlias, ''SA_PKG_LIST_POST'',''CODE'' )'
GO
EXEC X_SET_PROP 'SA_PKG_LIST_POST', 'OPEN_CODE', 'link'
GO
EXEC X_SET_PROP 'SA_PKG_LIST_POST', 'CAPTION', 'Тарифная сетка'
GO
EXEC X_SET_PROP 'SA_PKG_LIST_POST', 'MSG_SEL_ONE', ''
GO
EXEC X_SET_PROP 'SA_PKG_LIST_POST', 'SERVER_TABLE_NAME', ''
GO
EXEC X_SET_PROP 'SA_PKG_LIST_POST', 'PREPARE_NEW_RECORD', 'x_new_diction_record(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'PKG_OKLAD', 'TITLE', 'Справочник базовых окладов'
GO
EXEC X_SET_PROP 'PKG_OKLAD', 'INIT_OBJECT_METHOD', 'X_SPISOK("PKG_OKLAD")'
GO
EXEC X_SET_PROP 'PKG_OKLAD', 'INIT_OBJECT_PROG', 'A_SPISOK_MENU(oForm)
A_SPISOK_UPD (oForm, 0, .T.)'
GO
EXEC X_SET_PROP 'PKG_OKLAD', 'SELECT_RECORDS_METHOD', 'sa_child_table_alias(m.nLinkPKG, m.cAlias, ''PKG_OKLAD'',''DATE_BEGIN'' )'
GO
EXEC X_SET_PROP 'PKG_OKLAD', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS(''PKG_OKLAD'')'
GO
EXEC X_SET_PROP 'PKG_OKLAD', 'OPEN_CODE', 'link'
GO
EXEC X_SET_PROP 'PKG_OKLAD', 'CAPTION', 'Тарифная сетка'
GO
EXEC X_SET_PROP 'PKG_OKLAD', 'MSG_SEL_ONE', ''
GO
EXEC X_SET_PROP 'PKG_OKLAD', 'SERVER_TABLE_NAME', ''
GO
EXEC X_SET_PROP 'PKG_OKLAD', 'PREPARE_NEW_RECORD', 'x_new_diction_record(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'PKG_OKLAD_MARKER', 'VISIBLE', '25'
GO
EXEC X_SET_PROP 'PKG_OKLAD_MARKER', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'PKG_OKLAD_MARKER', 'ROWSOURCE', 'CHECKED'
GO
EXEC X_SET_PROP 'PKG_OKLAD_MARKER', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'PKG_OKLAD_MARKER', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'PKG_OKLAD_MARKER', 'ASPTYPE', 'checkbox'
GO
EXEC X_SET_PROP 'PKG_OKLAD_MARKER', 'FIELD_DATA', 'checked'
GO
EXEC X_SET_PROP 'PKG_OKLAD_DATE_BEGIN', 'TITLE', 'Дата ввода'
GO
EXEC X_SET_PROP 'PKG_OKLAD_DATE_BEGIN', 'EDIT_OBJECT_METHOD', 'ALIB_GET_DATE(oForm,oForm.pageframe1.page2.BSpisok.bgrid1.column2.text1)'
GO
EXEC X_SET_PROP 'PKG_OKLAD_DATE_BEGIN', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PKG_OKLAD_DATE_BEGIN', 'CONTROLSOURCE', 'm.cAlias + ".date_begin"'
GO
EXEC X_SET_PROP 'PKG_OKLAD_DATE_BEGIN', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PKG_OKLAD_DATE_BEGIN', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PKG_OKLAD_DATE_BEGIN', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'PKG_OKLAD_DATE_BEGIN', 'SHORT_CODE_OBJ', 'date_begin'
GO
EXEC X_SET_PROP 'PKG_OKLAD_DATE_BEGIN', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".date_begin"'
GO
EXEC X_SET_PROP 'PKG_OKLAD_SUMMA', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'PKG_OKLAD_SUMMA', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PKG_OKLAD_SUMMA', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'PKG_OKLAD_SUMMA', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PKG_OKLAD_SUMMA', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PKG_OKLAD_SUMMA', 'TYPE_FIELD_DICT', 'numeric(18,2)'
GO
EXEC X_SET_PROP 'PKG_OKLAD_SUMMA', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'PKG_OKLAD_SUMMA', 'ATTRIBUTES', ' style="Z-INDEX: 105; LEFT: 168px; POSITION: absolute; TOP: 64px"'
GO
EXEC X_SET_PROP 'PKG_OKLAD_MARKER_1', 'VISIBLE', '25'
GO
EXEC X_SET_PROP 'PKG_OKLAD_MARKER_1', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'PKG_OKLAD_MARKER_1', 'ROWSOURCE', 'CHECKED'
GO
EXEC X_SET_PROP 'PKG_OKLAD_MARKER_1', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'PKG_OKLAD_MARKER_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'PKG_OKLAD_MARKER_1', 'ASPTYPE', 'checkbox'
GO
EXEC X_SET_PROP 'PKG_OKLAD_MARKER_1', 'FIELD_DATA', 'checked'
GO
EXEC X_SET_PROP 'PKG_POST_CODE_1', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'PKG_POST_CODE_1', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_POST",oForm.pageframe1.page1.BSpisok.bgrid1.RecordSource,"LINK, CODE, NAME", "LINK, CODE, NAME", "", "", "link_pkg is null", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'PKG_POST_CODE_1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PKG_POST_CODE_1', 'CONTROLSOURCE', 'm.cAlias + ".code"'
GO
EXEC X_SET_PROP 'PKG_POST_CODE_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PKG_POST_CODE_1', 'OPERATE_METHOD', 'IIF(NVL(EVALUATE(m.cAliasOperate+''.LINK''),0)>0,x_edit_rec(''DICTIONARY_POST'',EVALUATE(m.cAliasOperate+''.LINK'')),"")'
GO
EXEC X_SET_PROP 'PKG_POST_CODE_1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PKG_POST_CODE_1', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'PKG_POST_CODE_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".code"'
GO
EXEC X_SET_PROP 'PKG_POST_CODE_1', 'CONTROL_NAME_EDIT', 'Atextbox01'
GO
EXEC X_SET_PROP 'PKG_POST_NAME_1', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'PKG_POST_NAME_1', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_POST",oForm.pageframe1.page1.BSpisok.bgrid1.RecordSource,"LINK, CODE, NAME", "LINK, CODE, NAME", "", "", "link_pkg is null", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'PKG_POST_NAME_1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PKG_POST_NAME_1', 'CONTROLSOURCE', 'm.cAlias + ".NAME"'
GO
EXEC X_SET_PROP 'PKG_POST_NAME_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PKG_POST_NAME_1', 'OPERATE_METHOD', 'IIF(NVL(EVALUATE(m.cAliasOperate+''.LINK''),0)>0,x_edit_rec(''DICTIONARY_POST'',EVALUATE(m.cAliasOperate+''.LINK'')),"")'
GO
EXEC X_SET_PROP 'PKG_POST_NAME_1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PKG_POST_NAME_1', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'PKG_POST_NAME_1', 'SHORT_CODE_OBJ', 'NAME'
GO
EXEC X_SET_PROP 'PKG_POST_NAME_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME"'
GO
EXEC X_SET_PROP 'PKG_POST_NAME_1', 'CONTROL_NAME_EDIT', 'Atextbox02'
GO
EXEC X_SET_PROP 'PKG_POST_DATE_BEGIN', 'TITLE', 'Начало периода'
GO
EXEC X_SET_PROP 'PKG_POST_DATE_BEGIN', 'EDIT_OBJECT_METHOD', 'ALIB_GET_DATE(oForm,oForm.pageframe1.page1.BSpisok.bgrid1.column4.text1)'
GO
EXEC X_SET_PROP 'PKG_POST_DATE_BEGIN', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PKG_POST_DATE_BEGIN', 'CONTROLSOURCE', 'm.cAlias + ".date_begin"'
GO
EXEC X_SET_PROP 'PKG_POST_DATE_BEGIN', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PKG_POST_DATE_BEGIN', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PKG_POST_DATE_BEGIN', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'PKG_POST_DATE_BEGIN', 'SHORT_CODE_OBJ', 'date_begin'
GO
EXEC X_SET_PROP 'PKG_POST_DATE_BEGIN', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".date_begin"'
GO
EXEC X_SET_PROP 'PKG_POST_date_END', 'TITLE', 'Конец периода'
GO
EXEC X_SET_PROP 'PKG_POST_date_END', 'EDIT_OBJECT_METHOD', 'ALIB_GET_DATE(oForm,oForm.pageframe1.page1.BSpisok.bgrid1.column5.text1)'
GO
EXEC X_SET_PROP 'PKG_POST_date_END', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PKG_POST_date_END', 'CONTROLSOURCE', 'm.cAlias + ".date_end"'
GO
EXEC X_SET_PROP 'PKG_POST_date_END', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PKG_POST_date_END', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PKG_POST_date_END', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'PKG_POST_date_END', 'SHORT_CODE_OBJ', 'date_end'
GO
EXEC X_SET_PROP 'PKG_POST_date_END', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".date_end"'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'SA_PKG_POST', 'Кадры-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SA_PKG_POST', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SA_PKG_POST', 'Свод-КС', 5,0
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "ПКГ должностей c базовыми окладами"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'NV_SAL_DICTIONS')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SA_PKG_POST')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'NV_SAL_DICTIONS'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'NV_SA_PKG_POST'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'NV_SA_PKG_POST', 'ПКГ должностей c базовыми окладами', @ORD, NULL, 1, @LINK_SELF, 'DICTIONARY', @OBJECT, @LINK_VAR, 3
GO


GO
EXEC X_SET_PROP 'COLUMN_CODE_KBK_FUR_T2_2', 'EDITABLE', '0'
GO
EXEC X_SET_PROP 'COLUMN_CODE_KBK_FUR_T2', 'EDITABLE', '0'
GO


GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DED_PR_DGH', 'VISIBLE', '5'
GO

GO
exec X_SET_OPTION 'FURLOUGH_OPT4','0','29.30'
GO

GO
DELETE FROM dbo.OBJECT_VAR_VALUES
WHERE 
	LINK_UP=(SELECT TOP 1 LINK FROM [dbo].[OBJECT_VAR] WHERE CODE = 'SYS_T9_REPORT')
	AND PROPERTY=(SELECT TOP 1 LINK FROM S_PROPERTY WHERE CODE='SQUERY_SQL') 
GO

INSERT INTO dbo.OBJECT_VAR_VALUES ([LINK_UP], [PROPERTY], [ORDERS], [VALUE])
SELECT 
	LINK_UP=(SELECT TOP 1 LINK FROM [dbo].[OBJECT_VAR] WHERE CODE = 'SYS_T9_REPORT')
	,PROPERTY=(SELECT TOP 1 LINK FROM S_PROPERTY WHERE CODE='SQUERY_SQL')
	,[ORDERS] = 1
	,[VALUE] = '
CREATE PROCEDURE #P_SQUERY
		@nNumber_ INT /*Одиночный/групповой*/,
		@nNumber001 INT /*Ссылка на документ (основная)*/,
		@nOption_ INT /*Вид документа*/,
		@varKScTableInto varchar(20) = ''''
AS
BEGIN

	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

	CREATE TABLE #T_RES (CHIEF varchar(254) /*Руководитель*/,
		DATE_BEGIN DATETIME /*Дата начала*/,
		DATE_DOC DATETIME /*паспорт (дата выдачи)*/,
		DATE_END DATETIME /*Дата окончания*/,
		DEP_ADR VARCHAR(1000) /*Адрес организации*/,
		dep_bank varchar(500) /*Банковские реквизиты организации*/,
		DOC_DATE DATETIME /*Дата приказа*/,
		DOC_NUM VARCHAR(30) /*Номер приказа*/,
		DURATION INT /*Продолжительность*/,
		FIO VARCHAR(254) /*ФИО (по документу)*/,
		fio_short VARCHAR(254) /*ФИО (по документу)*/,		
		INN VARCHAR(12) /*ИНН*/,
		KPP VARCHAR(9) /*КПП*/,
		LONGNAME VARCHAR(2000) /*Наименование*/,
		num_doc varchar(30) /*паспорт (серия и №)*/,
		OKPO VARCHAR(20) /*ОКПО*/,
		ORG VARCHAR(254) /*Организация назначения*/,
		ORGNAME VARCHAR(254) /*Краткое наименование*/,
		PASP_NUM VARCHAR(20) /*Номер паспорта*/,
		PAYER VARCHAR(254) /*За счет средств*/,
		PLACE VARCHAR(254) /*Место назначения*/,
		POST VARCHAR(254) /*Должность (по документу)*/,
		REASON VARCHAR(254) /*Основание*/,
		S_19380 INT /*Организация*/,
		S_35797 INT /*Приказ*/,
		S_35813 INT /*Приказ о направлении в командировку*/,
		SUBDIV VARCHAR(254) /*Подразделение (по документу)*/,
		TARGET VARCHAR(254) /*Цель*/,
		TARGET_DOP VARCHAR(254) /*Дополнение к цели*/,
		TN VARCHAR(15) /*Табельный номер (по документу)*/,
		UD_DATE DATETIME /*Командировочное удостоверение - дата*/,
		UD_NUM VARCHAR(15) /*Командировочное удостоверение - номер*/,
		WHOM_DOC VARCHAR(100) /*паспорт (кем выдан)*/,
		CLASS_CHIN VARCHAR(254),
		SQUERY int)

	INSERT #T_RES (S_19380, S_35797, S_35813, TN, SUBDIV, POST, ORG, PLACE, DATE_BEGIN, DATE_END, TARGET, TARGET_DOP, PAYER, REASON, UD_DATE, UD_NUM, PASP_NUM, FIO,fio_short,CLASS_CHIN, SQUERY) /*ФИО (по документу)*/
	SELECT DEP.LINK, ORD5.LINK, ITT.LINK, ITT.TAB_NUM, ITT.SUBDIV, ITT.POST, ITT.ORG, ITT.PLACE, ITT.DATE_BEGIN, ITT.DATE_END, ITT.TARGET, ITT.TARGET_DOP, ITT.PAYER, ITT.REASON, ITT.UDOST_DATE, ITT.UDOST_NUM, (SELECT TOP 1 P.DOC_NUM FROM EMPL INNER JOIN PERSON P ON EMPL.PERS_LINK = P.LINK  AND EMPL.LINK = ITT.EMPL_LINK), 
	ITT.FIO, 
	fio_short = LEFT(ITT.IM,1) + ''.'' + LEFT(ITT.OT,1) + ''. '' + ITT.FM, 
	'''', 6636
	FROM DICTIONARY_DEPARTMENT DEP, ORDERS ORD5, TRAVEL  ITT
	WHERE (ORD5.LINK=@nNumber001)
		AND ORD5.DEP_LINK = DEP.LINK
		AND ORD5.LINK = ITT.ORDER_LINK
		AND ORD5.TYPE IN (5, 105)

	UPDATE #T_RES
	SET	DURATION = DATEDIFF(D, DATE_BEGIN, DATE_END)+1 /*Продолжительность*/ FROM #T_RES T  WHERE SQUERY=6636

	UPDATE #T_RES
	SET	CHIEF = 	(SELECT TOP 1 RIGHT(RTRIM(FACE_NAME),4) + RTRIM(SUBSTRING(RTRIM(FACE_NAME),1,LEN(RTRIM(FACE_NAME))-4))
	FROM DICTIONARY_OTV_FACE DOTF, USER_INFO UI
WHERE DOTF.NAME=''РУКОВОДИТЕЛЬ'' AND DOTF.DEP_LINK = UI.DEP_LINK)
 /*Руководитель*/ FROM #T_RES T  WHERE SQUERY=6636

	UPDATE #T_RES
	SET	DEP_ADR = DBO.GetAddressByDepLink(S_19380,1) /*Адрес организации*/ FROM #T_RES T  WHERE SQUERY=6636

	UPDATE #T_RES
	SET	num_doc = (
SELECT  ''серия '' + LEFT(DOC_NUM,5) + '' № '' + RIGHT(DOC_NUM,6)
FROM PERSON
WHERE LINK = (SELECT PERS_LINK FROM EMPL WHERE LINK = (SELECT EMPL_LINK FROM ITEM_TRAVEL WHERE LINK = S_35813))
) /*паспорт (серия и №)*/ FROM #T_RES T  WHERE SQUERY=6636

	UPDATE #T_RES
	SET	WHOM_DOC = (
SELECT  DOC_WHOM
FROM PERSON
WHERE LINK = (SELECT PERS_LINK FROM EMPL WHERE LINK = (SELECT EMPL_LINK FROM ITEM_TRAVEL WHERE LINK = S_35813))
) /*паспорт (кем выдан)*/ FROM #T_RES T  WHERE SQUERY=6636

	UPDATE #T_RES
	SET	class_chin = (
			SELECT TOP 1 CH.CHIN_NAME 
			FROM TRAVEL N LEFT JOIN		 KU_EMPL_CHIN	CH		ON CH.EMPL_LINK = N.EMPL_LINK
			WHERE N.order_link = @nNumber001 and CH.DATE <= N.DATE 
			ORDER BY CH.DATE DESC)

	UPDATE #T_RES
	SET	DATE_DOC = (
SELECT  DOC_DATE
FROM PERSON
WHERE LINK = (SELECT PERS_LINK FROM EMPL WHERE LINK = (SELECT EMPL_LINK FROM ITEM_TRAVEL WHERE LINK = S_35813))
) /*паспорт (дата выдачи)*/ FROM #T_RES T  WHERE SQUERY=6636

	UPDATE #T_RES
	SET	dep_bank = (
SELECT CASE WHEN DA.TYPE = 1 THEN ''р/с '' + RTRIM(DA.CODE) + '' в '' + RTRIM(DA.BANK_NAME) + '', корсчет '' + RTRIM(B.KS) + '' БИК '' + RTRIM(B.BIK) ELSE DA.ANAME END
FROM DICTIONARY_ACCOUNTS DA LEFT JOIN BANKS B ON DA.REF_LINK_B = B.LINK
WHERE DA.LINK = (SELECT MAIN_LINK FROM DEPARTMENTS WHERE LINK = S_19380)
) /*Банковские реквизиты организации*/ FROM #T_RES T  WHERE SQUERY=6636

	UPDATE #T_RES
	SET	ORGNAME = (SELECT NAME FROM DICTIONARY_DEPARTMENT WHERE LINK=S_19380) /*Краткое наименование*/ FROM #T_RES T 

	UPDATE #T_RES
	SET	LONGNAME = (SELECT FULL_NAME FROM DICTIONARY_DEPARTMENT WHERE LINK=S_19380) /*Наименование*/ FROM #T_RES T 

	UPDATE #T_RES
	SET	OKPO = (SELECT OKPO FROM DICTIONARY_DEPARTMENT WHERE LINK=S_19380) /*ОКПО*/ FROM #T_RES T 

	UPDATE #T_RES
	SET	INN = (SELECT INN FROM DICTIONARY_DEPARTMENT WHERE LINK=S_19380) /*ИНН*/ FROM #T_RES T 

	UPDATE #T_RES
	SET	KPP = (SELECT KPP FROM DICTIONARY_DEPARTMENT WHERE LINK=S_19380) /*КПП*/ FROM #T_RES T 

	UPDATE #T_RES
	SET	DOC_DATE = (SELECT [DATE] FROM ORDERS WHERE LINK = S_35797) /*Дата приказа*/ FROM #T_RES T 

	UPDATE #T_RES
	SET	DOC_NUM = (SELECT NUMBER FROM ORDERS WHERE LINK = S_35797) /*Номер приказа*/ FROM #T_RES T 

	SELECT S_19380 AS S_19380 /*Организация*/,
		ORGNAME AS ORGNAME /*Краткое наименование*/,
		LONGNAME AS LONGNAME /*Наименование*/,
		OKPO AS OKPO /*ОКПО*/,
		S_35797 AS S_35797 /*Приказ*/,
		DOC_DATE AS DOC_DATE /*Дата приказа*/,
		DOC_NUM AS DOC_NUM /*Номер приказа*/,
		S_35813 AS S_35813 /*Приказ о направлении в командировку*/,
		FIO AS FIO /*ФИО (по документу)*/,
		fio_short,
		TN AS TN /*Табельный номер (по документу)*/,
		SUBDIV AS SUBDIV /*Подразделение (по документу)*/,
		POST AS POST /*Должность (по документу)*/,
		ORG AS ORG /*Организация назначения*/,
		PLACE AS PLACE /*Место назначения*/,
		DATE_BEGIN AS DATE_BEGIN /*Дата начала*/,
		DATE_END AS DATE_END /*Дата окончания*/,
		TARGET AS TARGET /*Цель*/,
		TARGET_DOP AS TARGET_DOP /*Дополнительная к цели*/,
		PAYER AS PAYER /*За счет средств*/,
		REASON AS REASON /*Основание*/,
		DURATION AS DURATION /*Продолжительность*/,
		CHIEF AS CHIEF /*Руководитель*/,
		UD_DATE AS UD_DATE /*Командировочное удостоверение - дата*/,
		UD_NUM AS UD_NUM /*Командировочное удостоверение - номер*/,
		PASP_NUM AS PASP_NUM /*Номер паспорта*/,
		DEP_ADR AS DEP_ADR /*Адрес организации*/,
		num_doc AS num_doc /*паспорт (серия и №)*/,
		WHOM_DOC AS WHOM_DOC /*паспорт (кем выдан)*/,
		DATE_DOC AS DATE_DOC /*паспорт (дата выдачи)*/,
		INN AS INN /*ИНН*/,
		KPP AS KPP /*КПП*/,
		dep_bank AS dep_bank /*Банковские реквизиты организации*/,
		CLASS_CHIN AS CLASS_CHIN
	INTO #T_RES2
	FROM #T_RES T
	GROUP BY S_19380, ORGNAME, LONGNAME, OKPO, S_35797, DOC_DATE, DOC_NUM, S_35813, FIO, fio_short, TN, SUBDIV, POST, ORG, PLACE, DATE_BEGIN, DATE_END, TARGET, TARGET_DOP, PAYER, REASON, DURATION, CHIEF, UD_DATE, UD_NUM, PASP_NUM, DEP_ADR, num_doc, WHOM_DOC, DATE_DOC, INN, KPP, dep_bank,CLASS_CHIN


	
SELECT * FROM #T_RES2 
	WHERE (1 > 0)

	DROP TABLE #T_RES

	SET TRANSACTION ISOLATION LEVEL READ COMMITTED

END
'
GO


GO
-- Отчет "Выплаты и иные вознаграждения по инвалидам I, II или III группы"
-- Сгенерировано скриптом scriptObjectVar 'SQL_REP_SAL_ESN_PFR_INV'

/*** Сам отчет ***/

if object_id('tempdb..#UPD_object_var') is not null
	drop table #UPD_object_var

CREATE TABLE #UPD_object_var (link_navigator int)

INSERT INTO #UPD_object_var (link_navigator)
SELECT  SN.LINK
FROM S_NAVIGATOR SN,OBJECT_VAR OV
WHERE SN.LINK_VAR = OV.LINK AND OV.CODE= 'SQL_REP_SAL_ESN_PFR_INV'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'SQL_REP_SAL_ESN_PFR_INV'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'Выплаты и иные вознаграждения по инвалидам I, II или III группы',401, 
	(Select link from object_var where code = 'SQL_REPORT_CATALOG_SALARY'),
	'SQL_REP_SAL_ESN_PFR_INV',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_PFR_INV') 
	FROM S_NAVIGATOR S INNER JOIN #UPD_object_var U on S.LINK = U.link_navigator
GO

if object_id('tempdb..#UPD_object_var') is not null
	drop table #UPD_object_var
GO
/*** Свойства отчета ***/
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV') and  PROPERTY = (Select LINK from s_property where code = 'CHECK_VALUE_IN_TABLE')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV'),
	PROPERTY= (Select LINK from s_property where code = 'CHECK_VALUE_IN_TABLE'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_ADDSELECT')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADDSELECT'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_AFTER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_AFTER'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_BEFORE')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= '	EXEC dbo.RSA_RSV_1_14_PFR_INV
		@cYear1 		/* Год */,
		@nQuarter1 	/* Квартал */,
		7 , 1 
'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_FOOTER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_FOOTER'),
	VALUE= '="Исполнитель                               " & User_FIO
                                 подпись'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_HEADER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_HEADER'),
	VALUE= '=User_Name'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_PROCEDURE')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#SQL_REP_SAL_ESN_PFR_INV'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_REPMAKER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPMAKER'),
	VALUE= 'KIRREPMAKER.XLS'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_REPORT')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.T.,"SS_REP_14_PFR_INV.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_REPORT_PATH')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT_PATH'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_SQL')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #SQL_REP_SAL_ESN_PFR_INV
	@cYear1 VARCHAR(4)	/* Год */,
	@nQuarter1 int	/* Квартал */
AS
BEGIN

	EXEC dbo.RSA_RSV_1_14_PFR_INV
		@cYear1 		/* Год */,
		@nQuarter1 	/* Квартал */,
		7 , 1 


END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_TOP')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_TOP'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV') and  PROPERTY = (Select LINK from s_property where code = 'EOD_PROTOCOL')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV'),
	PROPERTY= (Select LINK from s_property where code = 'EOD_PROTOCOL'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV') and  PROPERTY = (Select LINK from s_property where code = 'AFTER_REPORT_PROG')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV'),
	PROPERTY= (Select LINK from s_property where code = 'AFTER_REPORT_PROG'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_ADD_MODULE')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_PFR_INV'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADD_MODULE'),
	VALUE= 'KirRepCommon.bas'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_PFR_INV_GR1' 
		INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
		Select (Select link from s_objects where code = 'QUERY_NASTRS'),
		'Группа настроек',1, 
		(Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV'),
		'SQL_REP_SAL_ESN_PFR_INV_GR1',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_PFR_INV_N1' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_YEARBOX'),
					'Год',2, 
					(Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_GR1'),
					'SQL_REP_SAL_ESN_PFR_INV_N1',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1'),
							(Select link from s_property where code = 'FORMAT'),
							'9999'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'MASKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							'Отчётный год'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Текущий год,Расчетный год'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@cYear1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'VARCHAR(4)'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'2011'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N1'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_PFR_INV_N2' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_QUARTERBOX'),
					'Квартал',3, 
					(Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_GR1'),
					'SQL_REP_SAL_ESN_PFR_INV_N2',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'QUARTERBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							'Отчётный квартал'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Текущий квартал,Расчетный квартал'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nQuarter1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'IV квартал'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_PFR_INV_N2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO






/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Выплаты и иные вознаграждения по инвалидам I, II или III группы"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'SQL_REP_SAL_ESN_PFR_INV')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SALARY_ESN')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'QUERY_SQL')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SALARY_ESN'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'NV_REP_SAL_ESN_PFR_INV'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'NV_REP_SAL_ESN_PFR_INV', 'Выплаты и иные вознаграждения по инвалидам I, II или III группы', @ORD, NULL, 1, @LINK_SELF, 'REPORT', @OBJECT, @LINK_VAR, 3
GO


GO
-- Отчет "Реестр отчислений в фонды"
-- Сгенерировано скриптом scriptObjectVar 'SQL_REP_SAL_ESN_SVOD1'

/*** Сам отчет ***/

if object_id('tempdb..#UPD_object_var') is not null
	drop table #UPD_object_var

CREATE TABLE #UPD_object_var (link_navigator int)

INSERT INTO #UPD_object_var (link_navigator)
SELECT  SN.LINK
FROM S_NAVIGATOR SN,OBJECT_VAR OV
WHERE SN.LINK_VAR = OV.LINK AND OV.CODE= 'SQL_REP_SAL_ESN_SVOD1'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'Реестр отчислений в фонды',401, 
	(Select link from object_var where code = 'SQL_REPORT_CATALOG_SALARY'),
	'SQL_REP_SAL_ESN_SVOD1',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1') 
	FROM S_NAVIGATOR S INNER JOIN #UPD_object_var U on S.LINK = U.link_navigator
GO

if object_id('tempdb..#UPD_object_var') is not null
	drop table #UPD_object_var
GO
/*** Свойства отчета ***/
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'INIT_OBJECT_METHOD')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'INIT_OBJECT_METHOD'),
	VALUE= 'm_print_query(nLink_Var)'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'VISIBLE')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'VISIBLE'),
	VALUE= '0'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'CHECK_VALUE_IN_TABLE')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'CHECK_VALUE_IN_TABLE'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'AFTER_CHANGE_PROG_NASTR')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'AFTER_CHANGE_PROG_NASTR'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'BEFORE_CHANGE_PROG_NASTR')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'BEFORE_CHANGE_PROG_NASTR'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'NASTR_XL_CENTER_HEADER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_CENTER_HEADER'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'NASTR_XL_DATETIME')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_DATETIME'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'NASTR_XL_FOOTER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_FOOTER'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'NASTR_XL_FREEZEPANES')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_FREEZEPANES'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'NASTR_XL_LEFT_HEADER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_LEFT_HEADER'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'NASTR_XL_PAGES')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_PAGES'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'NASTR_XL_RIGHT_HEADER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_RIGHT_HEADER'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_ADDFROM')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADDFROM'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_ADDINTO')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADDINTO'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_ADDSELECT')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADDSELECT'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_ADDWHERE')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADDWHERE'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_AFTER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_AFTER'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_BEFORE')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= '	EXEC KIR_EXEC_SALARY_ESN_REPORT1
		@dDateB1						/* Начало периода */,
		@dDateE1						/* Конец периода */,
		@nCheck1						/* Мужчины до 1952 г. р., женщины до 1956 */,
		@nCheck2						/* Мужчины до 1952 г. р., женщины до 1956 */,
		@nCheck3						/* 1967 г.р. и моложе */,
		@nOption1						/* Сортировать по */,
		@nCheck4 						/* Детализировать по подразделениям */,
		@nCheck5 						/* Детализировать по сотрудникам */,
		@nCheck6 						/* Детализировать по источникам */,
		@nCheck7						/* Учитывать расчёты по договорам ГПХ */,
		@nCombo1						/* Вывод данных */,
		@cVal1, @nOtborLink1			/* Отбор сотрудников */,
		@cVal2, @nOtborLink2			/* Отбор подразделений */,
		@cVal3, @nOtborLink3			/* Отбор источников финансирования */

		'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_DATETIME')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_DATETIME'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_DISTINCT')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_DISTINCT'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_FOOTER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_FOOTER'),
	VALUE= '="Исполнитель                               " & User_FIO
                                 подпись'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_FREEZEPANES')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_FREEZEPANES'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_HEADER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_HEADER'),
	VALUE= '=User_Name'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_PAGES')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PAGES'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_PROCEDURE')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#SQL_REP_SAL_ESN_SVOD1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_REPMAKER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPMAKER'),
	VALUE= 'KirRepMakerMultiSheet.XLS'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_REPORT')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.T.,"REP_SAL_ESN1.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_REPORT_PATH')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT_PATH'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_SQL')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #SQL_REP_SAL_ESN_SVOD1
	@dDateB1 datetime	/* Начало периода */,
	@dDateE1 datetime	/* Конец периода */,
	@nCheck1 int	/* Мужчины до 1952 г. р., женщины до 1956 */,
	@nCheck2 int	/* Мужчины 1953 - 1966 г. р., женщины 1957 - 1966 г. р. */,
	@nCheck3 int	/* 1967 г.р. и моложе */,
	@nOption1 int	/* Сортировать по */,
	@nCheck4 int	/* Детализировать по подразделениям */,
	@nCheck5 int	/* Детализировать по сотрудникам */,
	@nCheck6 int	/* Детализировать по источникам */,
	@nCheck7 int	/* Учитывать расчёты по договорам ГПХ */,
	@nCombo1 int	/* Вывод данных */,
	@nFilterLink int	/* Фильтр */
AS
BEGIN
	DECLARE @cVal1 char(1), @nOtborLink1 int	/* Отбор сотрудников */
	SELECT @nOtborLink1 = (SELECT LINK FROM OBJECT_VAR WHERE LINK_SELF=@nFilterLink AND OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE=''OTBOR_QUERY_SQL_EMPL''))
	SELECT @cVal1 = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE LINK_UP=@nOtborLink1 AND PROPERTY=(SELECT LINK FROM S_PROPERTY WHERE CODE=''QUERY_OTBOR_CHECK''))
	DECLARE @cVal2 char(1), @nOtborLink2 int	/* Отбор подразделений */
	SELECT @nOtborLink2 = (SELECT LINK FROM OBJECT_VAR WHERE LINK_SELF=@nFilterLink AND OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE=''OTBOR_QUERY_SQL_SUBDIV''))
	SELECT @cVal2 = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE LINK_UP=@nOtborLink2 AND PROPERTY=(SELECT LINK FROM S_PROPERTY WHERE CODE=''QUERY_OTBOR_CHECK''))
	DECLARE @cVal3 char(1), @nOtborLink3 int	/* Отбор источников финансирования */
	SELECT @nOtborLink3 = (SELECT LINK FROM OBJECT_VAR WHERE LINK_SELF=@nFilterLink AND OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE=''OTBOR_QUERY_SQL_SAL_SFIN''))
	SELECT @cVal3 = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE LINK_UP=@nOtborLink3 AND PROPERTY=(SELECT LINK FROM S_PROPERTY WHERE CODE=''QUERY_OTBOR_CHECK''))

	EXEC KIR_EXEC_SALARY_ESN_REPORT1
		@dDateB1						/* Начало периода */,
		@dDateE1						/* Конец периода */,
		@nCheck1						/* Мужчины до 1952 г. р., женщины до 1956 */,
		@nCheck2						/* Мужчины до 1952 г. р., женщины до 1956 */,
		@nCheck3						/* 1967 г.р. и моложе */,
		@nOption1						/* Сортировать по */,
		@nCheck4 						/* Детализировать по подразделениям */,
		@nCheck5 						/* Детализировать по сотрудникам */,
		@nCheck6 						/* Детализировать по источникам */,
		@nCheck7						/* Учитывать расчёты по договорам ГПХ */,
		@nCombo1						/* Вывод данных */,
		@cVal1, @nOtborLink1			/* Отбор сотрудников */,
		@cVal2, @nOtborLink2			/* Отбор подразделений */,
		@cVal3, @nOtborLink3			/* Отбор источников финансирования */

		

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_SYSTEM')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SYSTEM'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_TOP')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_TOP'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_TOTAL')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_TOTAL'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_TOTALCOL')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_TOTALCOL'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_TOTALROW')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_TOTALROW'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_AP_LIST')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_AP_LIST'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'EOD_PROTOCOL')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'EOD_PROTOCOL'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'AFTER_REPORT_PROG')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'AFTER_REPORT_PROG'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_ADD_MODULE')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADD_MODULE'),
	VALUE= 'SAL_ESN_SVOD1.bas'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1') and  PROPERTY = (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SAL_ESN_SVOD1'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1_FILTER' 
		INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
		Select (Select link from s_objects where code = 'QUERY_FILTER'),
		'Стандартный фильтр для запроса',0, 
		(Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1'),
		'SQL_REP_SAL_ESN_SVOD1_FILTER',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1_OTBOR1' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'OTBOR_QUERY_SQL_EMPL'),
					'Отбор сотрудников',1, 
					(Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_FILTER'),
					'SQL_REP_SAL_ESN_SVOD1_OTBOR1',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR1'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_CHECK') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR1'),
							(Select link from s_property where code = 'QUERY_OTBOR_CHECK'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR1'),
							(Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE'),
							'DICT_EMPLOYERS01'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_FIELD') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR1'),
							(Select link from s_property where code = 'QUERY_OTBOR_FIELD'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_PARENT_CODE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR1'),
							(Select link from s_property where code = 'QUERY_OTBOR_PARENT_CODE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR1'),
							(Select link from s_property where code = 'QUERY_OTBOR_VALUE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE2') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR1'),
							(Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE2'),
							'DICTIONARY_SUBDIVISION01'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1_OTBOR2' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'OTBOR_QUERY_SQL_SUBDIV'),
					'Отбор подразделений',2, 
					(Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_FILTER'),
					'SQL_REP_SAL_ESN_SVOD1_OTBOR2',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR2'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_CHECK') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR2'),
							(Select link from s_property where code = 'QUERY_OTBOR_CHECK'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR2'),
							(Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE'),
							'DICTIONARY_SUBDIVISION01'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_FIELD') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR2'),
							(Select link from s_property where code = 'QUERY_OTBOR_FIELD'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_PARENT_CODE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR2'),
							(Select link from s_property where code = 'QUERY_OTBOR_PARENT_CODE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR2'),
							(Select link from s_property where code = 'QUERY_OTBOR_VALUE'),
							''
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1_OTBOR3' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'OTBOR_QUERY_SQL_SAL_SFIN'),
					'Отбор источников финансирования',3, 
					(Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_FILTER'),
					'SQL_REP_SAL_ESN_SVOD1_OTBOR3',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR3'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_CHECK') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR3'),
							(Select link from s_property where code = 'QUERY_OTBOR_CHECK'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR3'),
							(Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE'),
							'SALARY_SRC_FIN'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_FIELD') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR3'),
							(Select link from s_property where code = 'QUERY_OTBOR_FIELD'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_PARENT_CODE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR3'),
							(Select link from s_property where code = 'QUERY_OTBOR_PARENT_CODE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_OTBOR3'),
							(Select link from s_property where code = 'QUERY_OTBOR_VALUE'),
							''
						
GO
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1_NA_GR2' 
		INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
		Select (Select link from s_objects where code = 'QUERY_NASTRS'),
		'Служащие',5, 
		(Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1'),
		'SQL_REP_SAL_ESN_SVOD1_NA_GR2',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1_NASTR4' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Мужчины до 1952 г. р., женщины до 1956',8, 
					(Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NA_GR2'),
					'SQL_REP_SAL_ESN_SVOD1_NASTR4',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Мужчины до 1952 г. р., женщины до 1956'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'CHECKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Выкл.,Вкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Вкл.'

						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR4'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1_NASTR5' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Мужчины 1953 - 1966 г. р., женщины 1957 - 1966 г. р.',9, 
					(Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NA_GR2'),
					'SQL_REP_SAL_ESN_SVOD1_NASTR5',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Мужчины 1953 - 1966 г. р., женщины 1957 - 1966 г. р.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'CHECKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'2'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Выкл.,Вкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck2'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Вкл.'

						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR5'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1_NASTR6' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'1967 г.р. и моложе',10, 
					(Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NA_GR2'),
					'SQL_REP_SAL_ESN_SVOD1_NASTR6',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'1967 г.р. и моложе'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'CHECKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'3'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Выкл.,Вкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck3'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Вкл.'

						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR6'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1_NASTR_GR' 
		INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
		Select (Select link from s_objects where code = 'QUERY_NASTRS'),
		'Группа настроек',4, 
		(Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1'),
		'SQL_REP_SAL_ESN_SVOD1_NASTR_GR',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1_NASTR1' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_DATEBOX_PB'),
					'Начало периода',6, 
					(Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR_GR'),
					'SQL_REP_SAL_ESN_SVOD1_NASTR1',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Начало периода'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'DATEBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Текущяя дата,Расчетная дата,Начало расч. периода,Конец расч. периода,Начало года,Конец года,Начало расч. месяца,Конец расч. месяца'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@dDateB1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'datetime'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Начало расч. периода'

						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR1'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1_NASTR2' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_DATEBOX_PE'),
					'Конец периода',7, 
					(Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR_GR'),
					'SQL_REP_SAL_ESN_SVOD1_NASTR2',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Конец периода'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'DATEBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Текущяя дата,Расчетная дата,Начало расч. периода,Конец расч. периода,Начало года,Конец года,Начало расч. месяца,Конец расч. месяца'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@dDateE1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'datetime'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Конец расч. периода'

						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1_NASTR3' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_OPTIONGROUP'),
					'Сортировать по',11, 
					(Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR_GR'),
					'SQL_REP_SAL_ESN_SVOD1_NASTR3',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Сортировать по'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'OPTIONGROUP'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'размеру дохода,табельному номеру,фамилии'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nOption1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'размеру дохода'

						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR3'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1_NASTR7' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Детализировать по подразделениям',12, 
					(Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR_GR'),
					'SQL_REP_SAL_ESN_SVOD1_NASTR7',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Детализировать по подразделениям'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'CHECKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							'Детализировать по подразделениям'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'4'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Выкл.,Вкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck4'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Выкл.'

						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR7'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1_NASTR8' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Детализировать по сотрудникам',13, 
					(Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR_GR'),
					'SQL_REP_SAL_ESN_SVOD1_NASTR8',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Детализировать по сотрудникам'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'CHECKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							'Детализировать по сотрудникам'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'5'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Выкл.,Вкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck5'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Вкл.'

GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR8'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1_NASTR9' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Детализировать по источникам',14, 
					(Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR_GR'),
					'SQL_REP_SAL_ESN_SVOD1_NASTR9',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Детализировать по источникам'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'CHECKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							'Детализировать по источникам'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'6'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Выкл.,Вкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck6'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Выкл.'

						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR9'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1_NASTR10' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Учитывать расчёты по договорам ГПХ',15, 
					(Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR_GR'),
					'SQL_REP_SAL_ESN_SVOD1_NASTR10',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Учитывать расчёты по договорам ГПХ'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'CHECKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'7'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Выкл.,Вкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck7'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Выкл.'
						

						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR10'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SAL_ESN_SVOD1_NASTR11' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_COMBOBOX'),
					'Вывод данных',16, 
					(Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR_GR'),
					'SQL_REP_SAL_ESN_SVOD1_NASTR11',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Вывод данных'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'COMBOBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							'Вывод данных по страховым взносам\Доп. тарифам'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'по страховым взносам,по Доп. тарифам'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCombo1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'по страховым взносам'
						
						
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SAL_ESN_SVOD1_NASTR11'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO


GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (июл  3 2014 11:51:50:803AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0503074G (Отчет о расходах и числ работников гос. органов субъектов РФ (годовая))
-- Дата ввода : 20101231
-- Дата окончания действия :
-- Версия : 2014-07-03 11:51:50.803
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = '0503074G' AND [START_DATE] = '20101231'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-07-03 11:51:50.803',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + '0503074G',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = '0503074G'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20101231')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SMETA'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Отчет о расходах и числ работников гос. органов субъектов РФ (годовая)',@vcNEW_FORM_CODE,@dNEW_START_DATE,1,1,1,1,18186,'RA_EXPORT_FORM_0503074#RA_IMPORT_FORM_0503074',0,0,'19000101',NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, 'svodprint_14_ask()','Sv_0503074G_20101231.bas','','KirRepMakerMultiSheet.xls','Sv_0503074G_20101231.xlt','',NULL,'RA_EXPORT_FORM_0503074#RA_IMPORT_FORM_0503074',0,NULL,NULL,'FORM14_EDIT#26#1','014       ','',NULL,NULL,'|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Таблица', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Утверждено',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Фактически',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Таблица', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Численность', @iLINK_FORM,2
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Утверждено',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Фактически',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Среднесписочная численность',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Численность', @iLINK_FORM,2, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Справка1', @iLINK_FORM,3
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Фактически',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Справка1', @iLINK_FORM,3, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Справка2', @iLINK_FORM,4
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,100,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,0,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'На отчетную дату',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В среднем',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Справка2', @iLINK_FORM,4, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (3,1,1,1)
INSERT #R VALUES (4,1,2,1)
INSERT #R VALUES (5,1,3,1)
INSERT #R VALUES (28,1,32,1)
INSERT #R VALUES (2,1,24,1)
INSERT #R VALUES (6,1,25,1)
INSERT #R VALUES (7,1,4,1)
INSERT #R VALUES (8,1,5,1)
INSERT #R VALUES (9,1,6,1)
INSERT #R VALUES (10,1,7,1)
INSERT #R VALUES (11,1,8,1)
INSERT #R VALUES (12,1,26,1)
INSERT #R VALUES (13,1,9,1)
INSERT #R VALUES (14,1,10,1)
INSERT #R VALUES (15,1,11,1)
INSERT #R VALUES (16,1,27,1)
INSERT #R VALUES (17,1,12,1)
INSERT #R VALUES (18,1,13,1)
INSERT #R VALUES (19,1,14,1)
INSERT #R VALUES (20,1,15,1)
INSERT #R VALUES (21,1,16,1)
INSERT #R VALUES (22,1,30,1)
INSERT #R VALUES (23,1,31,1)
INSERT #R VALUES (24,1,17,1)
INSERT #R VALUES (25,1,28,1)
INSERT #R VALUES (26,1,18,1)
INSERT #R VALUES (27,1,19,1)
INSERT #R VALUES (29,1,29,1)
INSERT #R VALUES (30,1,20,1)
INSERT #R VALUES (31,1,21,1)
INSERT #R VALUES (32,1,22,1)
INSERT #R VALUES (33,1,33,1)
INSERT #R VALUES (1,2,1,1)
INSERT #R VALUES (2,2,2,1)
INSERT #R VALUES (3,2,3,1)
INSERT #R VALUES (4,2,23,1)
INSERT #R VALUES (5,2,8,1)
INSERT #R VALUES (6,2,5,1)
INSERT #R VALUES (7,2,6,1)
INSERT #R VALUES (8,2,7,1)
INSERT #R VALUES (9,2,12,1)
INSERT #R VALUES (10,2,9,1)
INSERT #R VALUES (11,2,10,1)
INSERT #R VALUES (12,2,11,1)
INSERT #R VALUES (13,2,17,1)
INSERT #R VALUES (14,2,13,1)
INSERT #R VALUES (15,2,14,1)
INSERT #R VALUES (16,2,15,1)
INSERT #R VALUES (17,2,16,1)
INSERT #R VALUES (18,2,22,1)
INSERT #R VALUES (19,2,18,1)
INSERT #R VALUES (20,2,19,1)
INSERT #R VALUES (21,2,20,1)
INSERT #R VALUES (22,2,21,1)
INSERT #R VALUES (23,2,23,1)
INSERT #R VALUES (24,2,24,1)
INSERT #R VALUES (25,2,25,1)
INSERT #R VALUES (26,2,26,1)
INSERT #R VALUES (1,3,1,1)
INSERT #R VALUES (2,3,20,1)
INSERT #R VALUES (3,3,5,1)
INSERT #R VALUES (4,3,2,1)
INSERT #R VALUES (5,3,3,1)
INSERT #R VALUES (6,3,4,1)
INSERT #R VALUES (7,3,9,1)
INSERT #R VALUES (8,3,6,1)
INSERT #R VALUES (9,3,7,1)
INSERT #R VALUES (10,3,8,1)
INSERT #R VALUES (11,3,14,1)
INSERT #R VALUES (12,3,10,1)
INSERT #R VALUES (13,3,11,1)
INSERT #R VALUES (14,3,12,1)
INSERT #R VALUES (15,3,13,1)
INSERT #R VALUES (16,3,19,1)
INSERT #R VALUES (17,3,15,1)
INSERT #R VALUES (18,3,16,1)
INSERT #R VALUES (19,3,17,1)
INSERT #R VALUES (20,3,18,1)
INSERT #R VALUES (1,4,1,1)
INSERT #R VALUES (2,4,2,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 80
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,2,1,'Заработная плата лиц, замещающих государственные должности, всего  (сумма строк 011+012+013)                                                                                                                                                              ')
INSERT #F VALUES (1,3,1,'в т.ч.:денежное вознаграждение (денежное содержание, заработная плата судей)                                                                                                                                                                              ')
INSERT #F VALUES (1,4,1,'ежемесячное (ежеквартальное) денежное поощрение                                                                                                                                                                                                           ')
INSERT #F VALUES (1,5,1,'другие выплаты , предусмотренные действующим законодательством                                                                                                                                                                                            ')
INSERT #F VALUES (1,6,1,'Заработная плата  лиц, замещающих должности государственной гражданской службы, всего (сумма строк 021+023+025)                                                                                                                                           ')
INSERT #F VALUES (1,7,1,'в т.ч.:оклад денежного содержания                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,8,1,'из него  оклад по занимаемой должности                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,9,1,'дополнительные выплаты                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,10,1,'из них:  ежемесячное денежное поощрение                                                                                                                                                                                                                   ')
INSERT #F VALUES (1,11,1,'другие выплаты , предусмотренные действующим законодательством                                                                                                                                                                                            ')
INSERT #F VALUES (1,12,1,'Заработная плата лиц, замещающих отдельные должности государственной гражданской службы, 1) всего                               (сумма строк 031+032+033)                                                                                                 ')
INSERT #F VALUES (1,13,1,'в том числе: единое денежное вознаграждение                                                                                                                                                                                                               ')
INSERT #F VALUES (1,14,1,'ежемесячное денежное поощрение и премии                                                                                                                                                                                                                   ')
INSERT #F VALUES (1,15,1,'другие выплаты , предусмотренные действующим законодательством                                                                                                                                                                                            ')
INSERT #F VALUES (1,16,1,'Заработная плата лиц, замещающих  должности  иного вида федеральной государственной службы, 2) всего                     (сумма строк 041+042)                                                                                                            ')
INSERT #F VALUES (1,17,1,'в том числе: оклад денежного содержания                                                                                                                                                                                                                   ')
INSERT #F VALUES (1,18,1,'дополнительные выплаты                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,19,1,'из них ежемесячное денежное поощрение                                                                                                                                                                                                                     ')
INSERT #F VALUES (1,20,1,'Заработная плата лиц, замещающих должности, не являющиеся должностями государственной гражданской службы                                                                                                                                                  ')
INSERT #F VALUES (1,21,1,'Заработная плата работников государственного органа, переведенных на новые системы оплаты труда 3)                                                                                                                                                        ')
INSERT #F VALUES (1,22,1,'Итого расходов на заработную плату работников государственного органа (сумма строк 010+020+030+040+050+060)                                                                                                                                               ')
INSERT #F VALUES (1,23,1,'Прочие выплаты  работникам   государственного органа                                                                                                                                                                                                      ')
INSERT #F VALUES (1,24,1,'из них: компенсации работникам за использование личных легковых автомобилей для служебных целей                                                                                                                                                           ')
INSERT #F VALUES (1,25,1,'суточные при служебных командировках - всего  (сумма строк 083+084)                                                                                                                                                                                       ')
INSERT #F VALUES (1,26,1,'в том числе: на территории Российской Федерации                                                                                                                                                                                                           ')
INSERT #F VALUES (1,27,1,'на территории иностранных государств                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,28,1,'Другие расходы  на содержание   государственного органа                                                                                                                                                                                                   ')
INSERT #F VALUES (1,29,1,'в том числе: на служебные командировки (оплата проезда и проживания) - всего (сумма строк 092+093)                                                                                                                                                        ')
INSERT #F VALUES (1,30,1,'из них: на территории Российской Федерации                                                                                                                                                                                                                ')
INSERT #F VALUES (1,31,1,'на территории иностранных государств                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,32,1,'на содержание служебных легковых автомобилей                                                                                                                                                                                                              ')
INSERT #F VALUES (1,33,1,'Итого расходов  на содержание  государственного органа (сумма строк 070+080+090)                                                                                                                                                                          ')
INSERT #F VALUES (1,2,2,'010                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,3,2,'011                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,4,2,'012')
INSERT #F VALUES (1,5,2,'013                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,6,2,'020                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,7,2,'021')
INSERT #F VALUES (1,8,2,'022                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,9,2,'023')
INSERT #F VALUES (1,10,2,'024                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,11,2,'025                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,12,2,'030                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,13,2,'031                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,14,2,'032                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,15,2,'033                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,16,2,'040                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,17,2,'041                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,18,2,'042')
INSERT #F VALUES (1,19,2,'043                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,20,2,'050                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,21,2,'060                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,22,2,'070                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,23,2,'080                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,24,2,'081                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,25,2,'082                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,26,2,'083                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,27,2,'084                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,28,2,'090                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,29,2,'091                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,30,2,'092                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,31,2,'093                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,32,2,'094                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,33,2,'100                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,2,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,3,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,4,3,'ЗАПРЕТ()                                                                                                                                                                                                                                                  ')
INSERT #F VALUES (1,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,7,3,'ЗАПРЕТ()                                                                                                                                                                                                                                                  ')
INSERT #F VALUES (1,8,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,9,3,'ЗАПРЕТ()                                                                                                                                                                                                                                                  ')
INSERT #F VALUES (1,10,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,11,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,12,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,13,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,14,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,15,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,17,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,18,3,'ЗАПРЕТ()                                                                                                                                                                                                                                                  ')
INSERT #F VALUES (1,19,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,20,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,21,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,24,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,25,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,26,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,27,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,29,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,30,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,31,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,32,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,33,3,'ИТОГ_Ф14("070+080+090")')
INSERT #F VALUES (1,2,4,'ИТОГ_Ф14("011+012+013")')
INSERT #F VALUES (1,3,4,'14_УСТАНОВКА()+14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,4,4,'14_ФАКТ_РАСХОД(К.СТР.)                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,5,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,6,4,'ИТОГ_Ф14("021+023+025")')
INSERT #F VALUES (1,7,4,'14_ФАКТ_РАСХОД(К.СТР.)                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,8,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,9,4,'14_ФАКТ_РАСХОД(К.СТР.)                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,10,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,11,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,12,4,'ИТОГ_Ф14("031+032+033")')
INSERT #F VALUES (1,13,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,14,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,15,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,16,4,'ИТОГ_Ф14("041+042")')
INSERT #F VALUES (1,17,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,18,4,'14_ФАКТ_РАСХОД(К.СТР.)                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,19,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,20,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,21,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,22,4,'ИТОГ_Ф14("010+020+030+040+050+060")')
INSERT #F VALUES (1,23,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,24,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,25,4,'ИТОГ_Ф14("083+084")')
INSERT #F VALUES (1,26,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,27,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,28,4,'14_ФАКТ_РАСХОД("092") + 14_ФАКТ_РАСХОД("094")')
INSERT #F VALUES (1,29,4,'ИТОГ_Ф14("092+093")')
INSERT #F VALUES (1,30,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,31,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,32,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,33,4,'ИТОГ_Ф14("070+080+090")')
INSERT #F VALUES (2,1,1,'Государственные  должности                                                                                                                                                                                                                                ')
INSERT #F VALUES (2,2,1,'Должности государственной гражданской службы                                                                                                                                                                                                              ')
INSERT #F VALUES (2,3,1,'Отдельные должности государственной гражданской   службы 2)                                                                                                                                                                                               ')
INSERT #F VALUES (2,4,1,'Итого  должностей государственной гражданской службы (сумма строк 210+220)                                                                                                                                                                                ')
INSERT #F VALUES (2,5,1,'в том числе по категориям: руководители  (сумма строк 241+242+243)                                                                                                                                                                                        ')
INSERT #F VALUES (2,6,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (2,7,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,8,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,9,1,'помощники (советники) (сумма строк 251+252+253)                                                                                                                                                                                                           ')
INSERT #F VALUES (2,10,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (2,11,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,12,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,13,1,'специалисты  (сумма строк 261+262+263+264)                                                                                                                                                                                                                ')
INSERT #F VALUES (2,14,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (2,15,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,16,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,17,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,18,1,'Обеспечивающие специалисты (сумма строк 271+272+273+274)                                                                                                                                                                                                  ')
INSERT #F VALUES (2,19,1,'из них по группам: главные                                                                                                                                                                                                                                ')
INSERT #F VALUES (2,20,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,21,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,22,1,'младшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,23,1,'Должности иного вида федеральной государственной службы 3)                                                                                                                                                                                                ')
INSERT #F VALUES (2,24,1,'Должности, не являющиеся должностями государственной гражданской службы                                                                                                                                                                                   ')
INSERT #F VALUES (2,25,1,'Должности работников государственного органа, переведенных на новые системы оплаты труда 4)                                                                                                                                                               ')
INSERT #F VALUES (2,26,1,'Всего должностей работнриков (сумма строк 200+230+280+290+300)                                                                                                                                                                                            ')
INSERT #F VALUES (2,1,2,'200                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,2,2,'210                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,3,2,'220                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,4,2,'230                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,5,2,'240                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,6,2,'241                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,7,2,'242')
INSERT #F VALUES (2,8,2,'243')
INSERT #F VALUES (2,9,2,'250                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,10,2,'251                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,11,2,'252')
INSERT #F VALUES (2,12,2,'253')
INSERT #F VALUES (2,13,2,'260                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,14,2,'261                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,15,2,'262')
INSERT #F VALUES (2,16,2,'263')
INSERT #F VALUES (2,17,2,'264')
INSERT #F VALUES (2,18,2,'270')
INSERT #F VALUES (2,19,2,'271                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,20,2,'272')
INSERT #F VALUES (2,21,2,'273')
INSERT #F VALUES (2,22,2,'274')
INSERT #F VALUES (2,23,2,'280                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,24,2,'290                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,25,2,'300                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,26,2,'310                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,1,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,2,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,3,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,4,3,'ИТОГ_Ф14("210+220")')
INSERT #F VALUES (2,5,3,'ИТОГ_Ф14("241+242+243")')
INSERT #F VALUES (2,6,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,7,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,8,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,9,3,'ИТОГ_Ф14("251+252+253")')
INSERT #F VALUES (2,10,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,11,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,12,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,13,3,'ИТОГ_Ф14("261+262+263+264")')
INSERT #F VALUES (2,14,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,15,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,16,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,17,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,18,3,'ИТОГ_Ф14("271+272+273+274")                                                                                                                                                                                                                               ')
INSERT #F VALUES (2,19,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,20,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,21,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,22,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,23,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,24,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,25,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,26,3,'ИТОГ_Ф14("200+230+280+290+300")')
INSERT #F VALUES (2,1,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,2,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,3,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,4,4,'ИТОГ_Ф14("210+220")')
INSERT #F VALUES (2,5,4,'ИТОГ_Ф14("241+242+243")')
INSERT #F VALUES (2,6,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,7,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,8,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,9,4,'ИТОГ_Ф14("251+252+253")')
INSERT #F VALUES (2,10,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,11,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,12,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,13,4,'ИТОГ_Ф14("261+262+263+264")')
INSERT #F VALUES (2,14,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,15,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,16,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,17,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,18,4,'ИТОГ_Ф14("271+272+273+274")                                                                                                                                                                                                                               ')
INSERT #F VALUES (2,19,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,20,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,21,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,22,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,23,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,24,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,25,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,26,4,'ИТОГ_Ф14("200+230+280+290+300")')
INSERT #F VALUES (2,1,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,2,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,3,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,4,5,'ИТОГ_Ф14("210+220")')
INSERT #F VALUES (2,5,5,'ИТОГ_Ф14("241+242+243")')
INSERT #F VALUES (2,6,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,7,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,8,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,9,5,'ИТОГ_Ф14("251+252+253")')
INSERT #F VALUES (2,10,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,11,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,12,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,13,5,'ИТОГ_Ф14("261+262+263+264")')
INSERT #F VALUES (2,14,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,15,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,16,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,17,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,18,5,'ИТОГ_Ф14("271+272+273+274")                                                                                                                                                                                                                               ')
INSERT #F VALUES (2,19,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,20,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,21,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,22,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,23,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,24,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,25,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,26,5,'ИТОГ_Ф14("200+230+280+290+300")')
INSERT #F VALUES (3,1,1,'Количество государственных органов                                                                                                                                                                                                                        ')
INSERT #F VALUES (3,2,1,'Расходы на выплату денежного содержания, учтенного в строках 020 и 030 всего  (сумма строк 410+420+430+440)                                                                                                                                               ')
INSERT #F VALUES (3,3,1,'в том числе по категориям: руководители  (сумма строк 411+412+413)                                                                                                                                                                                        ')
INSERT #F VALUES (3,4,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (3,5,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,6,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,7,1,'помощники (советники) сумма строк (421+422+423)                                                                                                                                                                                                           ')
INSERT #F VALUES (3,8,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (3,9,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,10,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,11,1,'специалисты  (сумма строк 431+432+433+434)                                                                                                                                                                                                                ')
INSERT #F VALUES (3,12,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (3,13,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,14,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,15,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,16,1,'обеспечивающие специалисты (сумма строк 441+442+443+444)                                                                                                                                                                                                  ')
INSERT #F VALUES (3,17,1,'из них по группам: главные                                                                                                                                                                                                                                ')
INSERT #F VALUES (3,18,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,19,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,20,1,'младшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,1,2,'320                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,2,2,'400                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,3,2,'410                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,4,2,'411                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,5,2,'412                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,6,2,'413                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,7,2,'420                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,8,2,'421                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,9,2,'422                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,10,2,'423                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,11,2,'430                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,12,2,'431                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,13,2,'432                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,14,2,'433                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,15,2,'434                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,16,2,'440                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,17,2,'441                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,18,2,'442                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,19,2,'443                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,20,2,'444                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,2,3,'ИТОГ_Ф14("410+420+430+440KBK")')
INSERT #F VALUES (3,3,3,'ИТОГ_Ф14("411+412+413")')
INSERT #F VALUES (3,4,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,5,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,6,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,7,3,'ИТОГ_Ф14("421+422+423")')
INSERT #F VALUES (3,8,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,9,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,10,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,11,3,'ИТОГ_Ф14("431+432+433+434")')
INSERT #F VALUES (3,12,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,13,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,14,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,15,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,16,3,'ИТОГ_Ф14("441+442+443+444")')
INSERT #F VALUES (3,17,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,18,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,19,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,20,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (4,1,1,'Служебные легковые автомобили, состоящие на балансе государственного органа                                                                                                                                                                               ')
INSERT #F VALUES (4,2,1,'Служебные легковые автомобили, арендованные у других организаций по договорам найма                                                                                                                                                                       ')
INSERT #F VALUES (4,1,2,'450                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,2,2,'460                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,1,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (4,2,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (4,1,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (4,2,4,'14_ФАКТ_РАСХОД(К.СТР.)')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 322
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,1,0,0,0,'020-(021-023-025) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(2,NULL,0,NULL,2,1,0,0,0,'030-(031+032+033) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(3,NULL,0,NULL,3,1,0,0,0,'040-(041+042) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(4,NULL,0,NULL,4,7,0,0,0,'070-(010+020+030+040+050+060) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(5,NULL,0,NULL,5,1,0,0,0,'082-(083+084) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(6,NULL,0,NULL,6,3,8,0,0,'091-(092+093) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(7,NULL,0,NULL,7,1,0,0,0,'100-(070+080+090) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(8,NULL,0,NULL,8,7,0,0,0,'230-(210+220) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(9,NULL,0,NULL,9,1,0,0,0,'240-(241+242+243) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(10,NULL,0,NULL,10,1,0,0,0,'250-(251+252+253) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(11,NULL,0,NULL,11,1,0,0,0,'260-(261+262+263+264) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(12,NULL,0,NULL,12,5,0,0,0,'270-(271+272+273+274) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(13,NULL,0,NULL,13,7,0,0,0,'310-(200+230+280+290+300) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(14,NULL,0,NULL,14,1,0,0,0,'400-(410+420+430+440) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(15,NULL,0,NULL,15,5,0,0,0,'410-(411+412+413) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(16,NULL,0,NULL,16,1,0,0,0,'420-(421+422+423) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(17,NULL,0,NULL,17,1,0,0,0,'430-(431+432+433+434) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(18,NULL,0,NULL,18,5,0,0,0,'440-(441+442+443+444) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(19,NULL,0,NULL,19,7,0,0,0,'070Гр3>=070Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(20,NULL,0,NULL,20,7,0,0,0,'080Гр3>=080Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(21,NULL,0,NULL,21,7,0,0,0,'100Гр3>=100Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(22,NULL,0,NULL,22,1,0,0,0,'080>=081+082 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(23,NULL,0,NULL,23,7,0,0,0,'200Гр3>=200Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(24,NULL,0,NULL,24,7,0,0,0,'210Гр3>=210Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(25,NULL,0,NULL,25,7,0,0,0,'220Гр3>=220Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(26,NULL,0,NULL,26,7,0,0,0,'230Гр3>=230Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(27,NULL,0,NULL,27,1,0,0,0,'240Гр3>=240Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(28,NULL,0,NULL,28,1,0,0,0,'241Гр3>=241Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(29,NULL,0,NULL,29,1,0,0,0,'242Гр3>=242Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(30,NULL,0,NULL,30,1,0,0,0,'243Гр3>=243Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(31,NULL,0,NULL,31,1,0,0,0,'250Гр3>=250Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(32,NULL,0,NULL,32,1,0,0,0,'251Гр3>=251Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(33,NULL,0,NULL,33,1,0,0,0,'252Гр3>=252Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(34,NULL,0,NULL,34,1,0,0,0,'253Гр3>=253Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(35,NULL,0,NULL,35,1,0,0,0,'260Гр3>=260Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(36,NULL,0,NULL,36,1,0,0,0,'261Гр3>=261Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(37,NULL,0,NULL,37,1,0,0,0,'262Гр3>=262Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(38,NULL,0,NULL,38,1,0,0,0,'263Гр3>=263Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(39,NULL,0,NULL,39,1,0,0,0,'264Гр3>=264Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(40,NULL,0,NULL,40,1,0,0,0,'270Гр3>=270Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(41,NULL,0,NULL,41,5,0,0,0,'271Гр3>=271Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(42,NULL,0,NULL,42,1,0,0,0,'272Гр3>=272Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(43,NULL,0,NULL,43,1,0,0,0,'273Гр3>=273Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(44,NULL,0,NULL,44,1,0,0,0,'230-(240+250+260+270) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(45,NULL,0,NULL,45,1,0,0,0,'010-(011+012+013) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(46,NULL,0,NULL,46,1,0,0,0,'021Гр4>=021Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(47,NULL,0,NULL,47,1,0,0,0,'023Гр4>=024Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(48,NULL,0,NULL,48,1,0,0,0,'042Гр4>=043Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(49,NULL,0,NULL,49,1,0,0,0,'080Гр4>=081Гр4+082Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(50,NULL,0,NULL,50,1,0,0,0,'090Гр4>=091Гр4+094Гр4+095Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(51,NULL,0,NULL,51,1,0,0,0,'090Гр3>=090Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(52,NULL,0,NULL,52,1,0,0,0,'274Гр3>=274Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(53,NULL,0,NULL,53,7,0,0,0,'280Гр3>=280Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(54,NULL,0,NULL,54,7,0,0,0,'290Гр3>=290Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(55,NULL,0,NULL,55,7,0,0,0,'300Гр3>=300Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(56,NULL,0,NULL,56,7,0,0,0,'310Гр3>=310Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(57,NULL,0,NULL,57,5,0,0,0,'400Гр3 =020Гр4-025Гр4+030Гр4-033Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(58,NULL,0,NULL,58,3,0,0,0,'100>=070 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(59,NULL,0,NULL,59,3,0,0,0,'Укажите расходы по строке 010 или 200 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(60,NULL,0,NULL,60,3,0,0,0,'Укажите расходы по строке 020 или 210 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(61,NULL,0,NULL,61,3,0,0,0,'Укажите данные по строке 030 или 220 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(62,NULL,0,NULL,62,3,0,0,0,'Укажите данные по строке 040 или 280 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(63,NULL,0,NULL,63,3,0,0,0,'Укажите данные по строке 050 или 290 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(64,NULL,0,NULL,64,3,0,0,0,'Укажите данные по строке 060 или 300 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(65,NULL,0,NULL,65,3,0,0,0,'Укажите данные по строке 070 или 310 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(66,NULL,0,NULL,66,1,0,0,0,'Укажите данные по строке 230 или 400 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(67,NULL,0,NULL,67,1,0,0,0,'Укажите данные по строке 240 или 410 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(68,NULL,0,NULL,68,1,0,0,0,'Укажите данные по строке 241 или 411 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(69,NULL,0,NULL,69,1,0,0,0,'Укажите данные по строке 242 или 412 =  0',0,0,1,'20100121','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(70,NULL,0,NULL,70,1,0,0,0,'Укажите данные по строке 243 или 413 =  0',0,0,1,'20100121','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(71,NULL,0,NULL,71,1,0,0,0,'Укажите данные по строке 250 или 420 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(72,NULL,0,NULL,72,1,0,0,0,'Укажите данные по строке 251 или 421 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(73,NULL,0,NULL,73,1,0,0,0,'Укажите данные по строке 252 или 422 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(74,NULL,0,NULL,74,1,0,0,0,'Укажите данные по строке 253 или 423 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(75,NULL,0,NULL,75,1,0,0,0,'Укажите данные по строке 260 или 430 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(76,NULL,0,NULL,76,1,0,0,0,'Укажите данные по строке 261 или 431 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(77,NULL,0,NULL,77,1,0,0,0,'Укажите данные по строке 262 или 432 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(78,NULL,0,NULL,78,1,0,0,0,'Укажите данные по строке 263 или 433 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(79,NULL,0,NULL,79,1,0,0,0,'Укажите данные по строке 264 или 434 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(80,NULL,0,NULL,80,1,0,0,0,'Укажите данные по строке 270 или 440 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(81,NULL,0,NULL,81,1,0,0,0,'Укажите данные по строке 271 или 441 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(82,NULL,0,NULL,82,1,0,0,0,'Укажите данные по строке 272 или 442 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(83,NULL,0,NULL,83,1,0,0,0,'Укажите данные по строке 273 или 443 =  0',0,0,1,'20100211','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(84,NULL,0,NULL,84,1,0,0,0,'Укажите данные по строке 274 или 444 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(85,NULL,0,NULL,85,1,0,0,0,'Укажите данные по строке 94 или 450 или 460 =  0',0,0,1,'20110112','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(86,NULL,0,NULL,86,7,0,0,0,'Средняя заработная плата лиц, замещающих  государственные должности =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(87,NULL,0,NULL,87,7,0,0,0,'Средняя заработная плата лиц, замещающие должности государственной гражданской службы =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(88,NULL,0,NULL,88,7,0,0,0,'Сред. заработн. плата лиц, замещающих отдельные должности гос. гражд. службы =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(89,NULL,0,NULL,89,7,0,0,0,'Сред. заработн. плата лиц, замещающих  должности иного вида фед. гос. службы =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(90,NULL,0,NULL,90,7,0,0,0,'Сред. заработн. плата работников государственного органа, замещающих  должности, не являющиеся  должн. гос. гражд. службы =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(91,NULL,0,NULL,91,7,0,0,0,'Сред. заработн. плата работников гос. органа, оплата труда которых производится на основе ETC =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(92,NULL,0,NULL,92,3,0,0,0,'Укажите данные по строке 320 или 310 =  0',0,0,1,'20120131','','','','0503074G','20101231','','=',9,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 92
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%020%=%021%+%023%+%025%'',''4'')','020-(021-023-025)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%030%=%031%+%032%+%033%'',''4'')','030-(031+032+033)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%040%=%041%+%042%'',''4'')','040-(041+042)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%070%=%010%+%020%+%030%+%040%+%050%+%060%'',''4'')','070-(010+020+030+040+050+060)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(4,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%082%=%083%+%084%'',''4'')','082-(083+084)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(5,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%091%=%092%+%093%'',''4'')','091-(092+093)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%100%=%070%+%080%+%090%'',''*'')','100-(070+080+090)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%230%=%210%+%220%'' ,''*'')','230-(210+220)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(8,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%240%=%241%+%242%+%243%'' ,''*'')','240-(241+242+243)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(9,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%250%=%251%+%252%+%253%'' ,''*'')','250-(251+252+253)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(10,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%260%=%261%+%262%+%263%+%264%'' ,''*'')','260-(261+262+263+264)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(11,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%270%=%271%+%272%+%273%+%274%'' ,''*'')','270-(271+272+273+274)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(12,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%310%=%200%+%230%+%280%+%290%+%300%'' ,''*'')','310-(200+230+280+290+300)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(13,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%400%=%410%+%420%+%430%+%440%'' ,''*'')','400-(410+420+430+440)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(14,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%410%=%411%+%412%+%413%'',''*'')','410-(411+412+413)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(15,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%420%=%421%+%422%+%423%'',''*'')','420-(421+422+423)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(16,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%430%=%431%+%432%+%433%+%434%'',''*'')','430-(431+432+433+434)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(17,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%440%=%441%+%442%+%443%+%444%'',''*'')','440-(441+442+443+444)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(18,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%070Гр3%>=%070Гр4% '','''')','070Гр3>=070Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(19,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%080Гр3%>=%080Гр4%'','''')','080Гр3>=080Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(20,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%100Гр3%>=%100Гр4%'','''')','100Гр3>=100Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(21,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%080%>=%081%+%082% '',''*'')','080>=081+082','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(22,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%200Гр3%>=%200Гр4%'','''')','200Гр3>=200Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(23,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%210Гр3%>=%210Гр4%'','''')','210Гр3>=210Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(24,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%220Гр3%>=%220Гр4%'','''')','220Гр3>=220Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(25,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%230Гр3%>=%230Гр4%'','''')','230Гр3>=230Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(26,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%240Гр3%>=%240Гр4%'','''')','240Гр3>=240Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(27,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%241Гр3%>=%241Гр4%'','''')','241Гр3>=241Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(28,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%242Гр3%>=%242Гр4%'','''')','242Гр3>=242Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(29,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%243Гр3%>=%243Гр4%'','''')','243Гр3>=243Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(30,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%250Гр3%>=%250Гр4%'','''')','250Гр3>=250Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(31,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%251Гр3%>=%251Гр4%'','''')','251Гр3>=251Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(32,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%252Гр3%>=%252Гр4%'','''')','252Гр3>=252Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(33,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%253Гр3%>=%253Гр4%'','''')','253Гр3>=253Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(34,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%260Гр3%>=%260Гр4%'','''')','260Гр3>=260Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(35,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%261Гр3%>=%261Гр4%'','''')','261Гр3>=261Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(36,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%262Гр3%>=%262Гр4%'','''')','262Гр3>=262Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(37,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%263Гр3%>=%263Гр4%'','''')','263Гр3>=263Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(38,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%264Гр3%>=%264Гр4%'','''')','264Гр3>=264Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(39,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%270Гр3%>=%270Гр4%'','''')','270Гр3>=270Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(40,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%271Гр3%>=%271Гр4%'','''')','271Гр3>=271Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(41,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%272Гр3%>=%272Гр4%'','''')','272Гр3>=272Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(42,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%273Гр3%>=%273Гр4%'','''')','273Гр3>=273Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(43,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%230%=%240%+%250%+%260%+%270%'',''*'')','230-(240+250+260+270)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(44,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%010%=%011%+%012%+%013%'',''*'')','010-(011+012+013)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(45,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%021Гр4%>=%022Гр4%'','''')','021Гр4>=021Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(46,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%023Гр4%>=%024Гр4%'','''')','023Гр4>=024Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(47,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%042Гр4%>=%043Гр4%'','''')','042Гр4>=043Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(48,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%080Гр4%>=%081Гр4%+%082Гр4%'','''')','080Гр4>=081Гр4+082Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(49,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%090Гр4%>=%091Гр4%+%094Гр4%+%095Гр4%'','''')','090Гр4>=091Гр4+094Гр4+095Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(50,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%090Гр3%>=%090Гр4%'','''')','090Гр3>=090Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(51,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%274Гр3%>=%274Гр4%'','''')','274Гр3>=274Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(52,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%280Гр3%>=%280Гр4%'','''')','280Гр3>=280Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(53,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%290Гр3%>=%290Гр4%'','''')','290Гр3>=290Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(54,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%300Гр3%>=%300Гр4%'','''')','300Гр3>=300Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(55,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%310Гр3%>=%310Гр4%'','''')','310Гр3>=310Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(56,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%400Гр3%=%020Гр4%-%025Гр4%+%030Гр4%-%033Гр4%'' ,'''')','400Гр3 =020Гр4-025Гр4+030Гр4-033Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(57,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%100%>=%070%'',''*'')','100>=070','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(58,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %010Гр4%=0 AND %200Гр5%=0 OR %010Гр4%>0 AND %200Гр5%>0 then 1 else 0 end'',''*#Укажите расходы по строке 010 или 200'')','Укажите расходы по строке 010 или 200','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(59,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %020Гр4%=0 AND %210Гр5%=0 OR %020Гр4%>0 AND %210Гр5%>0 then 1 else 0 end'',''*#Укажите расходы по строке 020 или 210'')','Укажите расходы по строке 020 или 210','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(60,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %030Гр4%=0 AND %220Гр5%=0 OR %030Гр4%>0 AND %220Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 030 или 220'')','Укажите данные по строке 030 или 220','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(61,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %040Гр4%=0 AND %280Гр5%=0 OR %040Гр4%>0 AND %280Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 040 или 280'')','Укажите данные по строке 040 или 280','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(62,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %050Гр4%=0 AND %290Гр5%=0 OR %050Гр4%>0 AND %290Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 050 или 290'')','Укажите данные по строке 050 или 290','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(63,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %060Гр4%=0 AND %300Гр5%=0 OR %060Гр4%>0 AND %300Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 060 или 300'')','Укажите данные по строке 060 или 300','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(64,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(65,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %070Гр4%=0 AND %310Гр5%=0 OR %070Гр4%>0 AND %310Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 070 или 310'')','Укажите данные по строке 070 или 310','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(65,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %230Гр5%=0 AND %400Гр3%=0 OR %230Гр5%>0 AND %400Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 230 или 400'')','Укажите данные по строке 230 или 400','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(66,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %240Гр5%=0 AND %410Гр3%=0 OR %240Гр5%>0 AND %410Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 240 или 410'')','Укажите данные по строке 240 или 410','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(67,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(68,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %241Гр5%=0 AND %411Гр3%=0 OR %241Гр5%>0 AND %411Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 241 или 411'')','Укажите данные по строке 241 или 411','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(68,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(69,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %242Гр5%=0 AND %412Гр3%=0 OR %242Гр5%>0 AND %412Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 242 или 412'')','Укажите данные по строке 242 или 412','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(69,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(70,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %243Гр5%=0 AND %413Гр3%=0 OR %243Гр5%>0 AND %413Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 243 или 413'')','Укажите данные по строке 243 или 413','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(70,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(71,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %250Гр5%=0 AND %420Гр3%=0 OR %250Гр5%>0 AND %420Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 250 или 420'')','Укажите данные по строке 250 или 420','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(71,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %251Гр5%=0 AND %421Гр3%=0 OR %251Гр5%>0 AND %421Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 251 или 421'')','Укажите данные по строке 251 или 421','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(72,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %252Гр5%=0 AND %422Гр3%=0 OR %252Гр5%>0 AND %422Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 252 или 422'')','Укажите данные по строке 252 или 422','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(73,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(74,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %253Гр5%=0 AND %423Гр3%=0 OR %253Гр5%>0 AND %423Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 253 или 423'')','Укажите данные по строке 253 или 423','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(74,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(75,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %260Гр5%=0 AND %430Гр3%=0 OR %260Гр5%>0 AND %430Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 260 или 430'')','Укажите данные по строке 260 или 430','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(75,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %261Гр5%=0 AND %431Гр3%=0 OR %261Гр5%>0 AND %431Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 261 или 431'')','Укажите данные по строке 261 или 431','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(76,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %262Гр5%=0 AND %432Гр3%=0 OR %262Гр5%>0 AND %432Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 262 или 432'')','Укажите данные по строке 262 или 432','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(77,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %263Гр5%=0 AND %433Гр3%=0 OR %263Гр5%>0 AND %433Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 263 или 433'')','Укажите данные по строке 263 или 433','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(78,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %264Гр5%=0 AND %434Гр3%=0 OR %264Гр5%>0 AND %434Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 264 или 434'')','Укажите данные по строке 264 или 434','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(79,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %270Гр5%=0 AND %440Гр3%=0 OR %270Гр5%>0 AND %440Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 270 или 440'')','Укажите данные по строке 270 или 440','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(80,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %271Гр5%=0 AND %441Гр3%=0 OR %271Гр5%>0 AND %441Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 271 или 441'')','Укажите данные по строке 271 или 441','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(81,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(82,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %272Гр5%=0 AND %442Гр3%=0 OR %272Гр5%>0 AND %442Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 272 или 442'')','Укажите данные по строке 272 или 442','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(82,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(83,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %273Гр5%=0 AND %443Гр3%=0 OR %273Гр5%>0 AND %443Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 273 или 443'')','Укажите данные по строке 273 или 443','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(83,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(84,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %274Гр5%=0 AND %444Гр3%=0 OR %274Гр5%>0 AND %444Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 274 или 444'')','Укажите данные по строке 274 или 444','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(84,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(85,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when (%094Гр4%>0 AND %450Гр4%>0 OR %094Гр4%>0 AND %460Гр4%>0) OR (%094Гр4%=0 AND %450Гр4%=0 AND %460Гр4%=0) then 1 else 0 end'',''*#Укажите данные по строке 094 или 450 или 460'')','Укажите данные по строке 94 или 450 или 460','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(85,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(86,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещ. гос. долж.=%%010Гр4%/%200Гр5%/%MONTH%'','''')','Средняя заработная плата лиц, замещающих  государственные должности','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(86,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(87,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещ. долж. гос. гражданской службы=%%020Гр4%/%210Гр5%/%MONTH%'','''')','Средняя заработная плата лиц, замещающие должности государственной гражданской службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(87,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(88,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещающих отдельные должности =%%030Гр4%/%220Гр5%/%MONTH%'','''')','Сред. заработн. плата лиц, замещающих отдельные должности гос. гражд. службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(88,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещающих  должности иного вида фед. гос. службы=%%040Гр4%/%280Гр5%/%MONTH%'','''')','Сред. заработн. плата лиц, замещающих  должности иного вида фед. гос. службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(89,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата работников государственного органа, замещающих  должности, не являющиеся  должн. гос. гражд. службы=%%050Гр4%/%290Гр5%/%MONTH%'','''')','Сред. заработн. плата работников государственного органа, замещающих  должности, не являющиеся  должн. гос. гражд. службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(90,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата работников гос. органа, оплата труда которых производится на основе ETC=%%060Гр4%/%300Гр5%/%MONTH%'','''')','Сред. заработн. плата работников гос. органа, оплата труда которых производится на основе ETC','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(91,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(92,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %320Гр3%=0 AND %310Гр3%=0 OR %320Гр3%>0 AND %310Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 310 или 320'')','Укажите данные по строке 320 или 310','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(92,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 184
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '5         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'5','Годовые формы',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '8         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'8','14-ые формы',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '999999    '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'999999','формы отчетности',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2014-07-03 11:51:50.803',121) WHERE [LINK_FORM]=@iLINK_FORM

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
ELSE BEGIN
	DECLARE @vcMessage VARCHAR(8000)
	SELECT @vcMessage = [CURRENT_DATE] FROM #tabStop
	IF @vcMessage = '2014-07-03 11:51:50.803'
	BEGIN
		SELECT @vcMessage = 'Форма 0503074G с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0503074G с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-07-03 11:51:50.803. Обновление отклонено.'
	END

	 IF OBJECT_ID('tempdb..#tabUpdateMessages') IS NOT NULL
	 BEGIN
		 INSERT #tabUpdateMessages([TXT]) VALUES (@vcMessage)
	 END
	 SELECT @vcMessage
END
GO

-- Загрузить подсказку.
DECLARE @iLINK_FORM INT
SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo
if object_id('tempdb..#F1') is NOT NULL drop table #r_files
create table #F1 (ID int, Name varchar(254), Path varchar(254), CreateDate datetime, FileSize int)
if object_id('tempdb..#F2') is NOT NULL drop table #r_fileparts
create table #F2 (File_ID int, Orders int, Body varchar(8000))
insert #F1 (ID, Name, Path, CreateDate, FileSize) values(115,'СПРАВКА ПО РАСЧЁТУ 14 ФОРМЫ.MHT', 'D:\TEST', convert(datetime, '2011-02-22 08:31:00.000', 121), 109829)
insert #F2 (File_ID, Orders, Body) values(115,1, 'MIME-Version: 1.0
Content-Type: multipart/related; boundary="----=_NextPart_01CBD26A.F54A6190"

Данный документ является веб-страницей в одном файле, также называемой файлом веб-архива. Если вы видите это сообщение, значит, данный обозреватель или редактор не поддерживает файлы веб-архива. Загрузите обозреватель, поддерживающий веб-архивы, например Windows® Internet Explorer®.

------=_NextPart_01CBD26A.F54A6190
Content-Location: file:///C:/90708BCB/file4923.htm
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html; charset="us-ascii"

<html xmlns:v=3D"urn:schemas-microsoft-com:vml"
xmlns:o=3D"urn:schemas-microsoft-com:office:office"
xmlns:w=3D"urn:schemas-microsoft-com:office:word"
xmlns:m=3D"http://schemas.microsoft.com/office/2004/12/omml"
xmlns=3D"http://www.w3.org/TR/REC-html40">

<head>
<meta http-equiv=3DContent-Type content=3D"text/html; charset=3Dus-ascii">
<meta name=3DProgId content=3DWord.Document>
<meta name=3DGenerator content=3D"Microsoft Word 12">
<meta name=3DOriginator content=3D"Microsoft Word 12">
<link rel=3DFile-List href=3D"file4923.files/filelist.xml">
<!--[if gte mso 9]><xml>
 <o:DocumentProperties>
  <o:Author>&#1048;&#1075;&#1085;&#1072;&#1090;&#1100;&#1077;&#1074;</o:Aut=
hor>
  <o:Template>Normal</o:Template>
  <o:LastAuthor>&#1048;&#1075;&#1085;&#1072;&#1090;&#1100;&#1077;&#1074;</o=
:LastAuthor>
  <o:Revision>1</o:Revision>
  <o:TotalTime>1</o:TotalTime>
  <o:Created>2011-02-22T05:30:00Z</o:Created>
  <o:LastSaved>2011-02-22T05:31:00Z</o:LastSaved>
  <o:Pages>4</o:Pages>
  <o:Words>1312</o:Words>
  <o:Characters>7481</o:Characters>
  <o:Company>&#1054;&#1054;&#1054; &#1050;&#1077;&#1081;&#1089;&#1080;&#108=
9;&#1090;&#1077;&#1084;&#1089;</o:Company>
  <o:Lines>62</o:Lines>
  <o:Paragraphs>17</o:Paragraphs>
  <o:CharactersWithSpaces>8776</o:CharactersWithSpaces>
  <o:Version>12.00</o:Version>
 </o:DocumentProperties>
</xml><![endif]-->
<link rel=3DthemeData href=3D"file4923.files/themedata.thmx">
<link rel=3DcolorSchemeMapping href=3D"file4923.files/colorschememapping.xm=
l">
<!--[if gte mso 9]><xml>
 <w:WordDocument>
  <w:SpellingState>Clean</w:SpellingState>
  <w:GrammarState>Clean</w:GrammarState>
  <w:TrackMoves>false</w:TrackMoves>
  <w:TrackFormatting/>
  <w:PunctuationKerning/>
  <w:ValidateAgainstSchemas/>
  <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid>
  <w:IgnoreMixedContent>false</w:IgnoreMixedContent>
  <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText>
  <w:DoNotPromoteQF/>
  <w:LidThemeOther>RU</w:LidThemeOther>
  <w:LidThemeAsian>X-NONE</w:LidThemeAsian>
  <w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript>
  <w:Compatibility>
   <w:BreakWrappedTables/>
   <w:SnapToGridInCell/>
   <w:WrapTextWithPunct/>
   <w:UseAsianBreakRules/>
   <w:DontGrowAutofit/>
   <w:SplitPgBreakAndParaMark/>
   <w:DontVertAlignCellWithSp/>
   <w:DontBreakConstrainedForcedTables/>
   <w:DontVertAlignInTxbx/>
   <w:Word11KerningPairs/>
   <w:CachedColBalance/>
  </w:Compatibility>
  <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>
  <m:mathPr>
   <m:mathFont m:val=3D"Cambria Math"/>
   <m:brkBin m:val=3D"before"/>
   <m:brkBinSub m:val=3D"&#45;-"/>
   <m:smallFrac m:val=3D"off"/>
   <m:dispDef/>
   <m:lMargin m:val=3D"0"/>
   <m:rMargin m:val=3D"0"/>
   <m:defJc m:val=3D"centerGroup"/>
   <m:wrapIndent m:val=3D"1440"/>
   <m:intLim m:val=3D"subSup"/>
   <m:naryLim m:val=3D"undOvr"/>
  </m:mathPr></w:WordDocument>
</xml><![endif]--><!--[if gte mso 9]><xml>
 <w:LatentStyles DefLockedState=3D"false" DefUnhideWhenUsed=3D"true"
  DefSemiHidden=3D"true" DefQFormat=3D"false" DefPriority=3D"99"
  LatentStyleCount=3D"267">
  <w:LsdException Locked=3D"false" Priority=3D"0" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Normal"/>
  <w:LsdException Locked=3D"false" Priority=3D"9" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"heading 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"9" QFormat=3D"true" Name=3D"=
heading 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"9" QFormat=3D"true" Name=3D"=
heading 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"9" QFormat=3D"true" Name=3D"=
heading 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"9" QFormat=3D"true" Name=3D"=
heading 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"9" QFormat=3D"true" Name=3D"=
heading 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"9" QFormat=3D"true" Name=3D"=
heading 7"/>
  <w:LsdException Locked=3D"false" Priority=3D"9" QFormat=3D"true" Name=3D"=
heading 8"/>
  <w:LsdException Locked=3D"false" Priority=3D"9" QFormat=3D"true" Name=3D"=
heading 9"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" Name=3D"toc 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" Name=3D"toc 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" Name=3D"toc 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" Name=3D"toc 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" Name=3D"toc 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" Name=3D"toc 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" Name=3D"toc 7"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" Name=3D"toc 8"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" Name=3D"toc 9"/>
  <w:LsdException Locked=3D"false" Priority=3D"35" QFormat=3D"true" Name=3D=
"caption"/>
  <w:LsdException Locked=3D"false" Priority=3D"10" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Title"/>
  <w:LsdException Locked=3D"false" Priority=3D"1" Name=3D"Default Paragraph=
 Font"/>
  <w:LsdException Locked=3D"false" Priority=3D"11" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Subtitle"/>
  <w:LsdException Locked=3D"false" Priority=3D"22" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Strong"/>
  <w:LsdException Locked=3D"false" Priority=3D"20" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Emphasis"/>
  <w:LsdException Locked=3D"false" Priority=3D"59" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Table Grid"/>
  <w:LsdException Locked=3D"false" UnhideWhenUsed=3D"false" Name=3D"Placeho=
lder Text"/>
  <w:LsdException Locked=3D"false" Priority=3D"1" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"No Spacing"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Shading"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light List"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Grid"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 1"/>
  <w:LsdException Locked=3D"')

insert #F2 (File_ID, Orders, Body) values(115,2, 'false" Priority=3D"68" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Dark List"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Shading"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful List"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Grid"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Shading Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light List Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Grid Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 1 Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 2 Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 1 Accent 1"/>
  <w:LsdException Locked=3D"false" UnhideWhenUsed=3D"false" Name=3D"Revisio=
n"/>
  <w:LsdException Locked=3D"false" Priority=3D"34" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"List Paragraph"/>
  <w:LsdException Locked=3D"false" Priority=3D"29" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Quote"/>
  <w:LsdException Locked=3D"false" Priority=3D"30" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Intense Quote"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 2 Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 1 Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 2 Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 3 Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Dark List Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Shading Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful List Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Grid Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Shading Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light List Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Grid Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 1 Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 2 Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 1 Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 2 Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 1 Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 2 Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 3 Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Dark List Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Shading Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful List Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Grid Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Shading Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light List Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Grid Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 1 Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 2 Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 1 Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 2 Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 1 Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 2 Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 3 Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Dark List Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Shading Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful List Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Grid Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Shading Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light List Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Grid Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 1 Accent 4"/>
  <w:Lsd')

insert #F2 (File_ID, Orders, Body) values(115,3, 'Exception Locked=3D"false" Priority=3D"64" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 2 Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 1 Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 2 Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 1 Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 2 Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 3 Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Dark List Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Shading Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful List Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Grid Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Shading Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light List Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Grid Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 1 Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 2 Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 1 Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 2 Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 1 Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 2 Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 3 Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Dark List Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Shading Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful List Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Grid Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Shading Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light List Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Grid Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 1 Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 2 Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 1 Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 2 Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 1 Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 2 Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 3 Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Dark List Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Shading Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful List Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Grid Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"19" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Subtle Emphasis"/>
  <w:LsdException Locked=3D"false" Priority=3D"21" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Intense Emphasis"/>
  <w:LsdException Locked=3D"false" Priority=3D"31" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Subtle Reference"/>
  <w:LsdException Locked=3D"false" Priority=3D"32" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Intense Reference"/>
  <w:LsdException Locked=3D"false" Priority=3D"33" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Book Title"/>
  <w:LsdException Locked=3D"false" Priority=3D"37" Name=3D"Bibliography"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" QFormat=3D"true" Name=3D=
"TOC Heading"/>
 </w:LatentStyles>
</xml><![endif]-->
<style>
<!--
 /* Font Definitions */
 @font-face
	{font-family:Wingdings;
	panose-1:5 0 0 0 0 0 0 0 0 0;
	mso-font-charset:2;
	mso-generic-font-family:auto;
	mso-font-pitch:variable;
	mso-font-signature:0 268435456 0 0 -2147483648 0;}
@font-face
	{font-family:"Cambria Math";
	panose-1:2 4 5 3 5 4 6 3 2 4;
	mso-font-charset:204;
	mso-generic-font-family:roman;
	mso-font-pitch:variable;
	mso-font-signature:-1610611985 1107304683 0 0 415 0;}
 /* Style Definitions */
 p.MsoNormal, li.MsoNormal, div.MsoNormal
	{mso-style-unhide:no;
	mso-style-qformat:yes;
	mso-style-parent:"";
	margin:0cm;
	margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:12.0pt;
	font-family:"Times New Roman","serif";
	mso-fareast-font-family:"Times New Roman";}
span.SpellE
	{mso-style-name:"";
	mso-spl-e:yes;}
span.GramE
	{mso-style-name:"";
	mso-gram-e:yes;}
.MsoChpDefault
	{mso-style-type:export-only;
	mso-default-props:yes;
	mso-ascii-font-family:Calibri;
	mso-ascii-theme-font:minor-latin;
	mso-fareast-font-family:Calibri;
	mso-fareast-theme-font:minor-latin;
	mso-hansi-font-family:Calibri;
	mso-hansi-theme-font:minor-latin;
	mso-bidi-font-family:"Times New Roman";
	mso-bidi-theme-font:minor-bidi;
	mso-fareast-language:EN-US;}
.MsoPapDefault
	{mso-style-type:export-only;
	margin-bottom:10.0pt;
	line-height:115%;}
@page WordSection1
	{size:595.3pt')

insert #F2 (File_ID, Orders, Body) values(115,4, ' 841.9pt;
	margin:2.0cm 42.5pt 2.0cm 3.0cm;
	mso-header-margin:35.4pt;
	mso-footer-margin:35.4pt;
	mso-paper-source:0;}
div.WordSection1
	{page:WordSection1;}
 /* List Definitions */
 @list l0
	{mso-list-id:1615401855;
	mso-list-type:hybrid;
	mso-list-template-ids:1609475116 68747265 68747267 68747269 68747265 68747=
267 68747269 68747265 68747267 68747269;}
@list l0:level1
	{mso-level-number-format:bullet;
	mso-level-text:\F0B7;
	mso-level-tab-stop:none;
	mso-level-number-position:left;
	margin-left:54.0pt;
	text-indent:-18.0pt;
	font-family:Symbol;}
ol
	{margin-bottom:0cm;}
ul
	{margin-bottom:0cm;}
-->
</style>
<!--[if gte mso 10]>
<style>
 /* Style Definitions */
 table.MsoNormalTable
	{mso-style-name:"\041E\0431\044B\0447\043D\0430\044F \0442\0430\0431\043B\=
0438\0446\0430";
	mso-tstyle-rowband-size:0;
	mso-tstyle-colband-size:0;
	mso-style-noshow:yes;
	mso-style-priority:99;
	mso-style-qformat:yes;
	mso-style-parent:"";
	mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
	mso-para-margin-top:0cm;
	mso-para-margin-right:0cm;
	mso-para-margin-bottom:10.0pt;
	mso-para-margin-left:0cm;
	line-height:115%;
	mso-pagination:widow-orphan;
	font-size:11.0pt;
	font-family:"Calibri","sans-serif";
	mso-ascii-font-family:Calibri;
	mso-ascii-theme-font:minor-latin;
	mso-hansi-font-family:Calibri;
	mso-hansi-theme-font:minor-latin;
	mso-bidi-font-family:"Times New Roman";
	mso-bidi-theme-font:minor-bidi;
	mso-fareast-language:EN-US;}
</style>
<![endif]--><!--[if gte mso 9]><xml>
 <o:shapedefaults v:ext=3D"edit" spidmax=3D"2050"/>
</xml><![endif]--><!--[if gte mso 9]><xml>
 <o:shapelayout v:ext=3D"edit">
  <o:idmap v:ext=3D"edit" data=3D"1"/>
 </o:shapelayout></xml><![endif]-->
</head>

<body lang=3DRU style=3D''tab-interval:35.4pt''>

<div class=3DWordSection1>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1044;=
&#1083;&#1103;
&#1072;&#1074;&#1090;&#1086;&#1084;&#1072;&#1090;&#1080;&#1095;&#1077;&#108=
9;&#1082;&#1086;&#1075;&#1086;
&#1088;&#1072;&#1089;&#1095;&#1077;&#1090;&#1072; &#1089;&#1091;&#1084;&#10=
84;
&#1092;&#1086;&#1088;&#1084;&#1099; 14 (0503074)
&#1087;&#1088;&#1077;&#1076;&#1074;&#1072;&#1088;&#1080;&#1090;&#1077;&#108=
3;&#1100;&#1085;&#1086;
&#1085;&#1077;&#1086;&#1073;&#1093;&#1086;&#1076;&#1080;&#1084;&#1086; &#10=
87;&#1088;&#1086;&#1074;&#1077;&#1088;&#1080;&#1090;&#1100;
&#1085;&#1072;&#1089;&#1090;&#1088;&#1086;&#1081;&#1082;&#1091;
&#1089;&#1083;&#1077;&#1076;&#1091;&#1102;&#1097;&#1080;&#1093;
&#1089;&#1087;&#1088;&#1072;&#1074;&#1086;&#1095;&#1085;&#1080;&#1082;&#108=
6;&#1074;:</p>

<p class=3DMsoNormal style=3D''margin-left:54.0pt;text-indent:-18.0pt;mso-li=
st:l0 level1 lfo1;
tab-stops:95.65pt''><![if !supportLists]><span style=3D''font-family:Symbol;
mso-fareast-font-family:Symbol;mso-bidi-font-family:Symbol''><span
style=3D''mso-list:Ignore''>&middot;<span style=3D''font:7.0pt "Times New Roma=
n"''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span></span></span><![endif]>&#1074; &#1079;&#1072;&#1076;&#1072;&#1095;&=
#1077;
&laquo;&#1047;&#1072;&#1088;&#1087;&#1083;&#1072;&#1090;&#1072;-&#1050;&#10=
57;&raquo;
&#1074;
&#1089;&#1087;&#1088;&#1072;&#1074;&#1086;&#1095;&#1085;&#1080;&#1082;&#107=
7;
&laquo;&#1042;&#1080;&#1076;&#1099; &#1085;&#1072;&#1095;&#1080;&#1089;&#10=
83;&#1077;&#1085;&#1080;&#1081;&raquo;
&#1085;&#1077;&#1086;&#1073;&#1093;&#1086;&#1076;&#1080;&#1084;&#1086;
&#1087;&#1088;&#1086;&#1074;&#1077;&#1088;&#1080;&#1090;&#1100;
&#1085;&#1072;&#1089;&#1090;&#1088;&#1086;&#1081;&#1082;&#1091;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1072;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;;</p>

<p class=3DMsoNormal style=3D''margin-left:54.0pt;text-indent:-18.0pt;mso-li=
st:l0 level1 lfo1;
tab-stops:95.65pt''><![if !supportLists]><span style=3D''font-family:Symbol;
mso-fareast-font-family:Symbol;mso-bidi-font-family:Symbol''><span
style=3D''mso-list:Ignore''>&middot;<span style=3D''font:7.0pt "Times New Roma=
n"''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span></span></span><![endif]><span class=3DGramE>&#1074;
&#1079;&#1072;&#1076;&#1072;&#1095;&#1077;
&laquo;&#1047;&#1072;&#1088;&#1087;&#1083;&#1072;&#1090;&#1072;-&#1050;&#10=
57;&raquo;
&#1080;&#1083;&#1080;
&laquo;&#1050;&#1072;&#1076;&#1088;&#1099;-&#1050;&#1057;&raquo; &#1074;
&#1089;&#1087;&#1088;&#1072;&#1074;&#1086;&#1095;&#1085;&#1080;&#1082;&#107=
7;
&laquo;&#1064;&#1090;&#1072;&#1090;&#1085;&#1086;&#1077;
&#1088;&#1072;&#1089;&#1087;&#1080;&#1089;&#1072;&#1085;&#1080;&#1077;&raqu=
o;
&#1085;&#1077;&#1086;&#1073;&#1093;&#1086;&#1076;&#1080;&#1084;&#1086;
&#1087;&#1088;&#1086;&#1074;&#1077;&#1088;&#1080;&#1090;&#1100; &#1074;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1072;&#1093;
&laquo;&#1080;&#1089;&#1090;&#1086;&#1088;&#1080;&#1080;&raquo;
&#1088;&#1077;&#1082;&#1074;&#1080;&#1079;&#1080;&#1090;&#1099;
&laquo;&#1058;&#1080;&#1087;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;&raquo;, &la=
quo;&#1050;&#1072;&#1090;&#1077;&#1075;&#1086;&#1088;&#1080;&#1103;
<span class=3DSpellE>&#1075;&#1086;&#1089;</span>.
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;&raquo; &#10=
80;
&laquo;&#1043;&#1088;&#1091;&#1087;&#1087;&#1072; <span class=3DSpellE>&#10=
75;&#1086;&#1089;</span>.
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;&raquo;.</sp=
an></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1057;=
&#1091;&#1084;&#1084;&#1099;
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103; &#10=
89;
&#1085;&#1072;&#1095;&#1072;&#1083;&#1086; &#1075;&#1086;&#1076;&#1072;
&#1087;&#1086; &#1084;&#1077;&#1089;&#1103;&#1094;, &#1103;&#1074;&#1083;&#=
1103;&#1102;&#1097;&#1080;&#1081;&#1089;&#1103;
&#1087;&#1086;&#1089;&#1083;&#1077;&#1076;&#1085;&#1080;&#1084; &#1074;
&#1086;&#1090;&#1095;&#1105;&#1090;&#1085;&#1086;&#1084; <span class=3DGram=
E>&#1087;&#1077;&#1088;&#1080;&#1086;&#1076;&#1077;</span>
<b style=3D''mso-bidi-font-weight:normal''>&#1087;&#1086; &#1050;&#1041;&#105=
0;
&#1089; &#1042;&#1056; (&#1074;&#1080;&#1076;
&#1088;&#1072;&#1089;&#1093;&#1086;&#1076;&#1072;) =3D &#8216;012&#8217;</b=
>.</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>011</b>'' --&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1074;&#1086;&#1079;&#1085;&#1072;&#1075;&#1088;&#1072;&#1078;&#1076;&#107=
7;&#1085;&#1080;&#1077;
(&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1089;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;,
&#1079;&#1072;&#1088;&#1072;&#1073;&#1086;&#1090;&#1085;&#1072;&#1103;
&#1087;&#1083;&#1072;&#1090;&#1072; &#1089;&#1091;&#1076;&#1077;&#1081;)</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1089;=
&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&laquo;&#1043;&#1086;&#1089;&#1091;&#1076;&#1072')

insert #F2 (File_ID, Orders, Body) values(115,5, ';&#1088;&#1089;&#1090;&#107=
4;&#1077;&#1085;&#1085;&#1072;&#1103;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1100;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo;
&#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#10=
84;
&#1089; &#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>1.&#1076;&#1086;&#1083;&#1078;&#1085;&#10=
86;&#1089;&#1090;&#1085;&#1086;&#1081;
&#1086;&#1082;&#1083;&#1072;&#1076;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>2.&#1086;&#1082;&#1083;&#1072;&#1076;
&#1079;&#1072; &#1082;&#1083;&#1072;&#1089;&#1089;&#1085;&#1099;&#1081;
&#1095;&#1080;&#1085;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>3.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1074;&#1099;&#1089;&#1083;&#1091;&#1075;&#1091;
&#1083;&#1077;&#1090; &#1085;&#1072;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>4.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1086;&#1089;&#1086;&#1073;&#1099;&#1077;
&#1091;&#1089;&#1083;&#1086;&#1074;&#1080;&#1103;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>5.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1088;&#1072;&#1073;&#1086;&#1090;&#1091; &#1089;&#1086;
&#1089;&#1074;&#1077;&#1076;&#1077;&#1085;&#1080;&#1103;&#1084;&#1080;,
&#1089;&#1086;&#1089;&#1090;&#1072;&#1074;&#1083;&#1103;&#1102;&#1097;&#108=
0;&#1084;&#1080;
<span class=3DSpellE>&#1075;&#1086;&#1089;</span>.
&#1090;&#1072;&#1081;&#1085;&#1091;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>6.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1091;&#1095;&#1077;&#1085;&#1091;&#1102;
&#1089;&#1090;&#1077;&#1087;&#1077;&#1085;<span class=3DGramE>&#1100;(</spa=
n>&#1079;&#1074;&#1072;&#1085;&#1080;&#1077;)</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>7.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1087;&#1086;&#1095;&#1077;&#1090;&#1085;&#1086;&#1077;
&#1079;&#1074;&#1072;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>8.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1089;&#1083;&#1086;&#1078;&#1085;&#1086;&#1089;&#1090;&#11=
00;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>9.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072;
&#1085;&#1072;&#1087;&#1088;&#1103;&#1078;&#1077;&#1085;&#1085;&#1086;&#108=
9;&#1090;&#1100;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>10.&#1085;&#1072;&#1076;&#1073;&#1072;&#1=
074;&#1082;&#1072;
&#1079;&#1072; &#1074;&#1099;&#1089;&#1086;&#1082;&#1080;&#1077; &#1076;&#1=
086;&#1089;&#1090;&#1080;&#1078;&#1077;&#1085;&#1080;&#1103;
&#1074; &#1090;&#1088;&#1091;&#1076;&#1077; &#1080;
&#1089;&#1087;&#1077;&#1094;<span class=3DGramE>.&#1088;</span>&#1077;&#107=
8;&#1080;&#1084;
&#1088;&#1072;&#1073;&#1086;&#1090;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>012</b>'' -- &#1077;&#1078;&#1077;&#1084;&#1077;&#1089;&#1103;&#1095=
;&#1085;&#1086;&#1077;
(&#1077;&#1078;&#1077;&#1082;&#1074;&#1072;&#1088;&#1090;&#1072;&#1083;&#11=
00;&#1085;&#1086;&#1077;)
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077; &#1087;&#1086;&#10=
86;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1089;=
&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&laquo;&#1043;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#107=
4;&#1077;&#1085;&#1085;&#1072;&#1103;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1100;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo;
&#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#10=
84;
&#1089; &#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')

insert #F2 (File_ID, Orders, Body) values(115,6, '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>11.&#1077;&#1078;&#1077;&#1084;&#1077;&#1=
089;&#1103;&#1095;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1087;&#1086;&#1086;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>12.&#1087;&#1088;&#1077;&#1084;&#1080;&#1=
080;
&#1079;&#1072;
&#1074;&#1099;&#1087;&#1086;&#1083;&#1085;&#1077;&#1085;&#1080;&#1077;
&#1086;&#1089;&#1086;&#1073;&#1086; &#1074;&#1072;&#1078;&#1085;&#1099;&#10=
93;
&#1080; &#1089;&#1083;&#1086;&#1078;&#1085;&#1099;&#1093;
&#1079;&#1072;&#1076;&#1072;&#1085;&#1080;&#1081;<span style=3D''mso-tab-cou=
nt:
2''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=
&nbsp;&nbsp;&nbsp;&nbsp; </span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>013</b>'' -- &#1077;&#1078;&#1077;&#1084;&#1077;&#1089;&#1103;&#1095=
;&#1085;&#1086;&#1077;
(&#1077;&#1078;&#1077;&#1082;&#1074;&#1072;&#1088;&#1090;&#1072;&#1083;&#11=
00;&#1085;&#1086;&#1077;)
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077; &#1087;&#1086;&#10=
86;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1089;=
&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&laquo;&#1043;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#107=
4;&#1077;&#1085;&#1085;&#1072;&#1103;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1100;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077; &#1088;&#1072;&#1074;&#=
1085;&#1086;&#1084;&#1091;
&laquo;212&raquo; &#1087;&#1086;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#1084; &#1089;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>13.&#1084;&#1072;&#1090;&#1077;&#1088;&#1=
080;&#1072;&#1083;&#1100;&#1085;&#1072;&#1103;
&#1087;&#1086;&#1084;&#1086;&#1097;&#1100;,
&#1074;&#1099;&#1087;&#1083;&#1072;&#1095;&#1080;&#1074;&#1072;&#1077;&#108=
4;&#1072;&#1103;
&#1079;&#1072; &#1089;&#1095;&#1105;&#1090; &#1060;&#1054;&#1058;
&#1043;&#1057;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>14.&#1077;&#1076;&#1080;&#1085;&#1086;&#1=
074;&#1088;&#1077;&#1084;&#1077;&#1085;&#1085;&#1072;&#1103;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1072; &#1087;&#1088;&#1080;
&#1087;&#1088;&#1077;&#1076;&#1086;&#1089;&#1090;&#1072;&#1074;&#1083;&#107=
7;&#1085;&#1080;&#1080;
&#1077;&#1078;&#1077;&#1075;&#1086;&#1076;&#1085;&#1086;&#1075;&#1086;
&#1086;&#1087;&#1083;&#1072;&#1095;&#1080;&#1074;&#1072;&#1077;&#1084;&#108=
6;&#1075;&#1086;
&#1086;&#1090;&#1087;&#1091;&#1089;&#1082;&#1072;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>15.&#1076;&#1088;&#1091;&#1075;&#1080;&#1=
077;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1099; &#1074;
&#1095;&#1072;&#1089;&#1090;&#1080; &#1074;&#1099;&#1087;&#1083;&#1072;&#10=
90;
&#1087;&#1086; &#1080;&#1090;&#1086;&#1075;&#1072;&#1084; &#1088;&#1072;&#1=
073;&#1086;&#1090;&#1099;<span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp; </span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:2''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>021</b>'' --&#1086;&#1082;&#1083;&#1072;&#1076;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1075;&#1086;
&#1089;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1103;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1089;=
&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&laquo;&#1044;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1100; &#10=
75;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#1077;&#=
1085;&#1085;&#1086;&#1081;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1; &#1089;&#1083;&#1091;&#1078;&#1073;&#1099;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo; &#1087;=
&#1086;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#1084; &#1089;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>1.&#1076;&#1086;&#1083;&#1078;&#1085;&#10=
86;&#1089;&#1090;&#1085;&#1086;&#1081;
&#1086;&#1082;&#1083;&#1072;&#1076;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>2.&#1086;&#1082;&#1083;&#1072;&#1076;
&#1079;&#1072; &#1082;&#1')

insert #F2 (File_ID, Orders, Body) values(115,7, '083;&#1072;&#1089;&#1089;&#1085;&#1099;&#1081;
&#1095;&#1080;&#1085;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>022</b>'' -- &#1086;&#1082;&#1083;&#1072;&#1076; &#1087;&#1086;
&#1079;&#1072;&#1085;&#1080;&#1084;&#1072;&#1077;&#1084;&#1086;&#1081;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1089;=
&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&laquo;&#1044;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1100; &#10=
75;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#1077;&#=
1085;&#1085;&#1086;&#1081;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1; &#1089;&#1083;&#1091;&#1078;&#1073;&#1099;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo; &#1087;=
&#1086;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#1084; &#1089;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>1.&#1076;&#1086;&#1083;&#1078;&#1085;&#10=
86;&#1089;&#1090;&#1085;&#1086;&#1081;
&#1086;&#1082;&#1083;&#1072;&#1076;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp; </span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>023</b>'' -- &#1076;&#1086;&#1087;&#1086;&#1083;&#1085;&#1080;&#1090=
;&#1077;&#1083;&#1100;&#1085;&#1099;&#1077;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1089;=
&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&laquo;&#1044;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1100; &#10=
75;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#1077;&#=
1085;&#1085;&#1086;&#1081;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1; &#1089;&#1083;&#1091;&#1078;&#1073;&#1099;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo; &#1087;=
&#1086;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#1084; &#1089;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>3.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1074;&#1099;&#1089;&#1083;&#1091;&#1075;&#1091;
&#1083;&#1077;&#1090; &#1085;&#1072;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>4.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1086;&#1089;&#1086;&#1073;&#1099;&#1077;
&#1091;&#1089;&#1083;&#1086;&#1074;&#1080;&#1103;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>5.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1088;&#1072;&#1073;&#1086;&#1090;&#1091; &#1089;&#1086;
&#1089;&#1074;&#1077;&#1076;&#1077;&#1085;&#1080;&#1103;&#1084;&#1080;,
&#1089;&#1086;&#1089;&#1090;&#1072;&#1074;&#1083;&#1103;&#1102;&#1097;&#108=
0;&#1084;&#1080;
<span class=3DSpellE>&#1075;&#1086;&#1089;</span>.
&#1090;&#1072;&#1081;&#1085;&#1091;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>10.&#1085;&#1072;&#1076;&#1073;&#1072;&#1=
074;&#1082;&#1072;
&#1079;&#1072; &#1074;&#1099;&#1089;&#1086;&#1082;&#1080;&#1077;
&#1076;&#1086;&#1089;&#1090;&#1080;&#1078;&#1077;&#1085;&#1080;&#1103; &#10=
74;
&#1090;&#1088;&#1091;&#1076;&#1077; &#1080; &#1089;&#1087;&#1077;&#1094;<sp=
an
class=3DGramE>.&#1088;</span>&#1077;&#1078;&#1080;&#1084;
&#1088;&#1072;&#1073;&#1086;&#1090;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>11.&#1077;&#1078;&#1077;&#1084;&#1077;&#1=
089;&#1103;&#1095;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1087;&#1086;&#1086;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>12.&#1087;&#1088;&#1077;&#1084;&#1080;&#1=
080;
&#1079;&#1072;
&#1074;&#1099;&#1087;&#1086;&#1083;&#1085;&#1077;&#1085;&#1080;&#1077;
&#1086;&#1089;&#1086;&#1073;&#1086; &#1074;&#1072;&#1078;&#1085;&#1099;&#10=
93;
&#1080; &#1089;&#1083;&#1086;&#1078;&#1085;&#1099;&#1093; &#1079;&#1072;&#1=
076;&#1072;&#1085;&#1080;&#1081;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nb')

insert #F2 (File_ID, Orders, Body) values(115,8, 'sp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>13.&#1084;&#1072;&#1090;&#1077;&#1088;&#1=
080;&#1072;&#1083;&#1100;&#1085;&#1072;&#1103;
&#1087;&#1086;&#1084;&#1086;&#1097;&#1100;,
&#1074;&#1099;&#1087;&#1083;&#1072;&#1095;&#1080;&#1074;&#1072;&#1077;&#108=
4;&#1072;&#1103;
&#1079;&#1072; &#1089;&#1095;&#1105;&#1090; &#1060;&#1054;&#1058;
&#1043;&#1057;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>14.&#1077;&#1076;&#1080;&#1085;&#1086;&#1=
074;&#1088;&#1077;&#1084;&#1077;&#1085;&#1085;&#1072;&#1103;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1072; &#1087;&#1088;&#1080;
&#1087;&#1088;&#1077;&#1076;&#1086;&#1089;&#1090;&#1072;&#1074;&#1083;&#107=
7;&#1085;&#1080;&#1080;
&#1077;&#1078;&#1077;&#1075;&#1086;&#1076;&#1085;&#1086;&#1075;&#1086;
&#1086;&#1087;&#1083;&#1072;&#1095;&#1080;&#1074;&#1072;&#1077;&#1084;&#108=
6;&#1075;&#1086;
&#1086;&#1090;&#1087;&#1091;&#1089;&#1082;&#1072;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>024</b>'' -- &#1077;&#1078;&#1077;&#1084;&#1077;&#1089;&#1103;&#1095=
;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1087;&#1086;&#1086;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1089;=
&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&laquo;&#1044;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1100; &#10=
75;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#1077;&#=
1085;&#1085;&#1086;&#1081;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1; &#1089;&#1083;&#1091;&#1078;&#1073;&#1099;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo; &#1087;=
&#1086;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#1084; &#1089;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>11.&#1077;&#1078;&#1077;&#1084;&#1077;&#1=
089;&#1103;&#1095;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1087;&#1086;&#1086;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>025</b>'' -- &#1076;&#1088;&#1091;&#1075;&#1080;&#1077;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1099;<span class=3DGramE> ,</sp=
an>
&#1087;&#1088;&#1077;&#1076;&#1091;&#1089;&#1084;&#1086;&#1090;&#1088;&#107=
7;&#1085;&#1085;&#1099;&#1077;
&#1076;&#1077;&#1081;&#1089;&#1090;&#1074;&#1091;&#1102;&#1097;&#1080;&#108=
4;
&#1079;&#1072;&#1082;&#1086;&#1085;&#1086;&#1076;&#1072;&#1090;&#1077;&#108=
3;&#1100;&#1089;&#1090;&#1074;&#1086;&#1084;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1089;=
&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072; &#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#10=
89;&#1090;&#1080;
&laquo;&#1044;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1100; &#10=
75;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#1077;&#=
1085;&#1085;&#1086;&#1081;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1; &#1089;&#1083;&#1091;&#1078;&#1073;&#1099;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo; &#1087;=
&#1086;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#1084; &#1089;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>6.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1091;&#1095;&#1077;&#1085;&#1091;&#1102;
&#1089;&#1090;&#1077;&#1087;&#1077;&#1085;<span class=3DGramE>&#1100;(</spa=
n>&#1079;&#1074;&#1072;&#1085;&#1080;&#1077;)</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>7.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1087;&#1086;&#1095;&#1077;&#1090;&#1085;&#1086;&#1077;
&#1079;&#1074;&#1072;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>8.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1089;&#1083;&#1086;&#1078;&#1085;&#1086;&#1089;&#1090;&#11=
00;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>9.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1085;&#1072;&#1087;&#1088;&#1103;&#1078;&#1077;&#1085;&#10=
85;&#1086;&#1089;&#1090;&#1100;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>15.&#1076;&#1088;&#1091;&#1075;&#1080;&#1=
077;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1099; &#1074;
&#1095;&#1072;&#1089;&#1090;&#1080; &#1074;&#1099;&#1087;&#1083;&#1072;&#10=
90;
&#1087;&#1086; &#1080;&#10')

insert #F2 (File_ID, Orders, Body) values(115,9, '90;&#1086;&#1075;&#1072;&#1084; &#1088;&#1072;&#1=
073;&#1086;&#1090;&#1099;<span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>031</b>'' -- &#1077;&#1076;&#1080;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1074;&#1086;&#1079;&#1085;&#1072;&#1075;&#1088;&#1072;&#1078;&#1076;&#107=
7;&#1085;&#1080;&#1077;
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&laquo;&#1054;&#1090;&#1076;&#1077;&#1083;&#1100;&#1085;&#1099;&#1077;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1075;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#107=
7;&#1085;&#1085;&#1086;&#1081;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099; &#1089;
&#1045;&#1076;&#1080;&#1085;&#1099;&#1084;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1099;&#1084;
&#1074;&#1086;&#1079;&#1085;&#1072;&#1075;&#1088;&#1072;&#1078;&#1076;&#107=
7;&#1085;&#1080;&#1077;&#1084;
&#1080;&#1083;&#1080; &#1086;&#1089;&#1086;&#1073;&#1099;&#1084;
&#1087;&#1086;&#1088;&#1103;&#1076;&#1082;&#1086;&#1084;
&#1086;&#1087;&#1083;&#1072;&#1090;&#1099;
&#1090;&#1088;&#1091;&#1076;&#1072;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077; &#1088;&#1072;&#1074;&#=
1085;&#1086;&#1084;&#1091;
&laquo;212&raquo; &#1087;&#1086;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#1084; &#1089;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>1.&#1076;&#1086;&#1083;&#1078;&#1085;&#10=
86;&#1089;&#1090;&#1085;&#1086;&#1081;
&#1086;&#1082;&#1083;&#1072;&#1076;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>2.&#1086;&#1082;&#1083;&#1072;&#1076;
&#1079;&#1072; &#1082;&#1083;&#1072;&#1089;&#1089;&#1085;&#1099;&#1081;
&#1095;&#1080;&#1085;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>3.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1074;&#1099;&#1089;&#1083;&#1091;&#1075;&#1091;
&#1083;&#1077;&#1090; &#1085;&#1072;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>4.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1086;&#1089;&#1086;&#1073;&#1099;&#1077;
&#1091;&#1089;&#1083;&#1086;&#1074;&#1080;&#1103;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>5.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1088;&#1072;&#1073;&#1086;&#1090;&#1091; &#1089;&#1086;
&#1089;&#1074;&#1077;&#1076;&#1077;&#1085;&#1080;&#1103;&#1084;&#1080;,
&#1089;&#1086;&#1089;&#1090;&#1072;&#1074;&#1083;&#1103;&#1102;&#1097;&#108=
0;&#1084;&#1080;
<span class=3DSpellE>&#1075;&#1086;&#1089;</span>.
&#1090;&#1072;&#1081;&#1085;&#1091;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>6.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1091;&#1095;&#1077;&#1085;&#1091;&#1102;
&#1089;&#1090;&#1077;&#1087;&#1077;&#1085;<span class=3DGramE>&#1100;(</spa=
n>&#1079;&#1074;&#1072;&#1085;&#1080;&#1077;)</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>7.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1087;&#1086;&#1095;&#1077;&#1090;&#1085;&#1086;&#1077;
&#1079;&#1074;&#1072;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>8.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1089;&#1083;&#1086;&#1078;&#1085;&#1086;&#1089;&#1090;&#11=
00;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>9.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072;
&#1085;&#1072;&#1087;&#1088;&#1103;&#1078;&#1077;&#1085;&#1085;&#1086;&#108=
9;&#1090;&#1100;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>10.&#1085;&#1072;&#1076;&#1073;&#1072;&#1=
074;&#1082;&#1072;
&#1079;&#1072; &#1074;&#1099;&#1089;&#1086;&#1082;&#1080;&#1077;
&#1076;&#1086;&#1089;&#1090;&#1080;&#1078;&#1077;&#1085;&#1080;&#1103; &#10=
74;
&#1090;&#1088;&#1091;&#1076;&#1077; &#1080; &#1089;&#1087;&#1077;&#1094;<sp=
an
class=3DGramE>.&#1088;</span>&#1077;&#1078;&#1080;&#1084;
&#1088;&#1072;&#1073;&#1086;&#1090;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =')

insert #F2 (File_ID, Orders, Body) values(115,10, '3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>032</b>'' -- &#1077;&#1078;&#1077;&#1084;&#1077;&#1089;&#1103;&#1095=
;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1087;&#1086;&#1086;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077; &#1080;
&#1087;&#1088;&#1077;&#1084;&#1080;&#1080; &#1089;&#1086;&#1073;&#1080;&#10=
88;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &laquo;&#10=
54;&#1090;&#1076;&#1077;&#1083;&#1100;&#1085;&#1099;&#1077;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1075;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#107=
7;&#1085;&#1085;&#1086;&#1081;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099; &#1089;
&#1045;&#1076;&#1080;&#1085;&#1099;&#1084;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1099;&#1084;
&#1074;&#1086;&#1079;&#1085;&#1072;&#1075;&#1088;&#1072;&#1078;&#1076;&#107=
7;&#1085;&#1080;&#1077;&#1084;
&#1080;&#1083;&#1080; &#1086;&#1089;&#1086;&#1073;&#1099;&#1084;
&#1087;&#1086;&#1088;&#1103;&#1076;&#1082;&#1086;&#1084;
&#1086;&#1087;&#1083;&#1072;&#1090;&#1099; &#1090;&#1088;&#1091;&#1076;&#10=
72;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo;
&#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#10=
84;
&#1089; &#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>11.&#1077;&#1078;&#1077;&#1084;&#1077;&#1=
089;&#1103;&#1095;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1087;&#1086;&#1086;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>12.&#1087;&#1088;&#1077;&#1084;&#1080;&#1=
080;
&#1079;&#1072;
&#1074;&#1099;&#1087;&#1086;&#1083;&#1085;&#1077;&#1085;&#1080;&#1077;
&#1086;&#1089;&#1086;&#1073;&#1086; &#1074;&#1072;&#1078;&#1085;&#1099;&#10=
93;
&#1080; &#1089;&#1083;&#1086;&#1078;&#1085;&#1099;&#1093;
&#1079;&#1072;&#1076;&#1072;&#1085;&#1080;&#1081;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>033</b>'' -- &#1076;&#1088;&#1091;&#1075;&#1080;&#1077;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1099;<span class=3DGramE> ,</sp=
an>
&#1087;&#1088;&#1077;&#1076;&#1091;&#1089;&#1084;&#1086;&#1090;&#1088;&#107=
7;&#1085;&#1085;&#1099;&#1077;
&#1076;&#1077;&#1081;&#1089;&#1090;&#1074;&#1091;&#1102;&#1097;&#1080;&#108=
4;
&#1079;&#1072;&#1082;&#1086;&#1085;&#1086;&#1076;&#1072;&#1090;&#1077;&#108=
3;&#1100;&#1089;&#1090;&#1074;&#1086;&#1084;
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &laquo;&#10=
54;&#1090;&#1076;&#1077;&#1083;&#1100;&#1085;&#1099;&#1077;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1075;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#107=
7;&#1085;&#1085;&#1086;&#1081;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099; &#1089;
&#1045;&#1076;&#1080;&#1085;&#1099;&#1084;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1099;&#1084;
&#1074;&#1086;&#1079;&#1085;&#1072;&#1075;&#1088;&#1072;&#1078;&#1076;&#107=
7;&#1085;&#1080;&#1077;&#1084;
&#1080;&#1083;&#1080; &#1086;&#1089;&#1086;&#1073;&#1099;&#1084;
&#1087;&#1086;&#1088;&#1103;&#1076;&#1082;&#1086;&#1084;
&#1086;&#1087;&#1083;&#1072;&#1090;&#1099;
&#1090;&#1088;&#1091;&#1076;&#1072;&raquo;, &#1085;&#1072;&#1095;&#1080;&#1=
089;&#1083;&#1077;&#1085;&#1085;&#1099;&#1077;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo;
&#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#10=
84;
&#1089; &#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>13.&#1084;&#1072;&#1090;&#1077;&#1088;&#1=
080;&#1072;&#1083;&#1100;&#1085;&#1072;&#1103;
&#1087;&#1086;&#1084;&#1086;&#1097;&#1100;,
&#1074;&#1099;&#1087;&#1083;&#1072;&#1095;&#1080;&#1074;&#1072;&#1077;&#108=
4;&#1072;&#1103;
&#1079;&#1072; &#1089;&#1095;&#1105;&#1090; &#1060;&#1054;&#1058; &#1043;&#=
1057;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>14.&#1077;&#1076;&#1080;&#1085;&#1086;&#1=
074;&#1088;&#1077;&#1084;&#1077;&#1085;&#1085;&#1072;&#1103;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1072; &#1087;&#1088;&#1080;
&#1087;&#1088;&#1077;&#1076;&#1086;&#1089;&#1090;&#1072;&#1074;&#1083;&#107=
7;&#1085;&#1080;&#1080;
&#1077;&#1078;&#1077;&#1075;&#1086;&#1076;&#1085;&#1086;&#1075;&#1086;
&#1086;&#1087;&#1083;&#1072;&#1095;&#1080;&#1074;&#1072;&#1077;&#1084;&#108=
6;&#1075;&#1086;
&#1086;&#1090;&#1087;&#1091;&#1089;&#1082;&#1072;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>15.&#1076;&#1088;&#1091;&#1075;&#1080;&#1=
077;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1099; &#1074;
&#1095;&#1072;&#1089;&#1090;&#1080; &#1074;&#1099;&#1087;&#1083;&#1072;&#10=
90;
&#1087;&#1086; &#1080;&#1090;&#1086;&#1075;&#1072;&#1084; &#1088;&#1072;&#1=
073;&#1086;&#1090;&#1099;<span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>041</b>'' -- &#1086;&#1082;&#1083;&#1')

insert #F2 (File_ID, Orders, Body) values(115,11, '072;&#1076;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1075;&#1086;
&#1089;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1103; &#10=
89;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &laquo;&#10=
44;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1080;&#1085;&#1086;&#1075;&#1086; &#1074;&#1080;&#1076;&#1072;
&#1092;&#1077;&#1076;&#1077;&#1088;&#1072;&#1083;&#1100;&#1085;&#1086;&#108=
1;
&#1075;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#107=
7;&#1085;&#1085;&#1086;&#1081;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;
(&#1074;&#1086;&#1080;&#1085;&#1089;&#1082;&#1080;&#1077;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &#1080;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1087;&#1088;&#1072;&#1074;&#1086;&#1086;&#1093;&#1088;&#1072;&#1085;&#108=
0;&#1090;&#1077;&#1083;&#1100;&#1085;&#1086;&#1081;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;)&raquo;, &#1085;&#1072;&#1095;&#=
1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#1077;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo;
&#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#10=
84;
&#1089; &#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>1.&#1076;&#1086;&#1083;&#1078;&#1085;&#10=
86;&#1089;&#1090;&#1085;&#1086;&#1081;
&#1086;&#1082;&#1083;&#1072;&#1076;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>2.&#1086;&#1082;&#1083;&#1072;&#1076;
&#1079;&#1072; &#1082;&#1083;&#1072;&#1089;&#1089;&#1085;&#1099;&#1081;
&#1095;&#1080;&#1085;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>042</b>'' -- &#1076;&#1086;&#1087;&#1086;&#1083;&#1085;&#1080;&#1090=
;&#1077;&#1083;&#1100;&#1085;&#1099;&#1077;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1099;<span
style=3D''mso-spacerun:yes''>&nbsp; </span>&#1089;&#1086;&#1073;&#1080;&#1088=
;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &laquo;&#10=
44;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1080;&#1085;&#1086;&#1075;&#1086; &#1074;&#1080;&#1076;&#1072;
&#1092;&#1077;&#1076;&#1077;&#1088;&#1072;&#1083;&#1100;&#1085;&#1086;&#108=
1;
&#1075;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#107=
7;&#1085;&#1085;&#1086;&#1081;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;
(&#1074;&#1086;&#1080;&#1085;&#1089;&#1082;&#1080;&#1077;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &#1080; &#1=
076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1087;&#1088;&#1072;&#1074;&#1086;&#1086;&#1093;&#1088;&#1072;&#1085;&#108=
0;&#1090;&#1077;&#1083;&#1100;&#1085;&#1086;&#1081;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;)&raquo;, &#1085;&#1072;&#1095;&#=
1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#1077;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo;
&#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#10=
84;
&#1089; &#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>3.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1074;&#1099;&#1089;&#1083;&#1091;&#1075;&#1091;
&#1083;&#1077;&#1090; &#1085;&#1072;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>4.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1086;&#1089;&#1086;&#1073;&#1099;&#1077;
&#1091;&#1089;&#1083;&#1086;&#1074;&#1080;&#1103;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>5.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1088;&#1072;&#1073;&#1086;&#1090;&#1091; &#1089;&#1086;
&#1089;&#1074;&#1077;&#1076;&#1077;&#1085;&#1080;&#1103;&#1084;&#1080;,
&#1089;&#1086;&#1089;&#1090;&#1072;&#1074;&#1083;&#1103;&#1102;&#1097;&#108=
0;&#1084;&#1080;
<span class=3DSpellE>&#1075;&#1086;&#1089;</span>.
&#1090;&#1072;&#1081;&#1085;&#1091;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>6.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1091;&#1095;&#1077;&#1085;&#1091;&#1102;
&#1089;&#1090;&#1077;&#1087;&#1077;&#1085;<span class=3DGramE>&#1100;(</spa=
n>&#1079;&#1074;&#1072;&#1085;&#1080;&#1077;)</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>7.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1087;&#1086;&#1095;&#1077;&#1090;&#1085;&#1086;&#1077;
&#1079;&#1074;&#1072;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>8.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#10')

insert #F2 (File_ID, Orders, Body) values(115,12, '72; &#1089;&#1083;&#1086;&#1078;&#1085;&#1086;&#1089;&#1090;&#11=
00;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>9.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1085;&#1072;&#1087;&#1088;&#1103;&#1078;&#1077;&#1085;&#10=
85;&#1086;&#1089;&#1090;&#1100;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>10.&#1085;&#1072;&#1076;&#1073;&#1072;&#1=
074;&#1082;&#1072;
&#1079;&#1072; &#1074;&#1099;&#1089;&#1086;&#1082;&#1080;&#1077;
&#1076;&#1086;&#1089;&#1090;&#1080;&#1078;&#1077;&#1085;&#1080;&#1103; &#10=
74;
&#1090;&#1088;&#1091;&#1076;&#1077; &#1080; &#1089;&#1087;&#1077;&#1094;<sp=
an
class=3DGramE>.&#1088;</span>&#1077;&#1078;&#1080;&#1084;
&#1088;&#1072;&#1073;&#1086;&#1090;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>11.&#1077;&#1078;&#1077;&#1084;&#1077;&#1=
089;&#1103;&#1095;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1087;&#1086;&#1086;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>12.&#1087;&#1088;&#1077;&#1084;&#1080;&#1=
080;
&#1079;&#1072;
&#1074;&#1099;&#1087;&#1086;&#1083;&#1085;&#1077;&#1085;&#1080;&#1077;
&#1086;&#1089;&#1086;&#1073;&#1086; &#1074;&#1072;&#1078;&#1085;&#1099;&#10=
93;
&#1080; &#1089;&#1083;&#1086;&#1078;&#1085;&#1099;&#1093;
&#1079;&#1072;&#1076;&#1072;&#1085;&#1080;&#1081;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>13.&#1084;&#1072;&#1090;&#1077;&#1088;&#1=
080;&#1072;&#1083;&#1100;&#1085;&#1072;&#1103;
&#1087;&#1086;&#1084;&#1086;&#1097;&#1100;,
&#1074;&#1099;&#1087;&#1083;&#1072;&#1095;&#1080;&#1074;&#1072;&#1077;&#108=
4;&#1072;&#1103;
&#1079;&#1072; &#1089;&#1095;&#1105;&#1090; &#1060;&#1054;&#1058;
&#1043;&#1057;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>14.&#1077;&#1076;&#1080;&#1085;&#1086;&#1=
074;&#1088;&#1077;&#1084;&#1077;&#1085;&#1085;&#1072;&#1103;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1072; &#1087;&#1088;&#1080;
&#1087;&#1088;&#1077;&#1076;&#1086;&#1089;&#1090;&#1072;&#1074;&#1083;&#107=
7;&#1085;&#1080;&#1080;
&#1077;&#1078;&#1077;&#1075;&#1086;&#1076;&#1085;&#1086;&#1075;&#1086;
&#1086;&#1087;&#1083;&#1072;&#1095;&#1080;&#1074;&#1072;&#1077;&#1084;&#108=
6;&#1075;&#1086;
&#1086;&#1090;&#1087;&#1091;&#1089;&#1082;&#1072;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>15.&#1076;&#1088;&#1091;&#1075;&#1080;&#1=
077;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1099; &#1074;
&#1095;&#1072;&#1089;&#1090;&#1080; &#1074;&#1099;&#1087;&#1083;&#1072;&#10=
90;
&#1087;&#1086; &#1080;&#1090;&#1086;&#1075;&#1072;&#1084; &#1088;&#1072;&#1=
073;&#1086;&#1090;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>043</b>'' -- &#1077;&#1078;&#1077;&#1084;&#1077;&#1089;&#1103;&#1095=
;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1087;&#1086;&#1086;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077; &#1089;&#10=
86;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &laquo;&#10=
44;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1080;&#1085;&#1086;&#1075;&#1086; &#1074;&#1080;&#1076;&#1072;
&#1092;&#1077;&#1076;&#1077;&#1088;&#1072;&#1083;&#1100;&#1085;&#1086;&#108=
1;
&#1075;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#107=
7;&#1085;&#1085;&#1086;&#1081;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;
(&#1074;&#1086;&#1080;&#1085;&#1089;&#1082;&#1080;&#1077;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &#1080;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1087;&#1088;&#1072;&#1074;&#1086;&#1086;&#1093;&#1088;&#1072;&#1085;&#108=
0;&#1090;&#1077;&#1083;&#1100;&#1085;&#1086;&#1081;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;)&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo;
&#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#10=
84;
&#1089; &#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>11.&#1077;&#1078;&#1077;&#1084;&#1077;&#1=
089;&#1103;&#1095;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1087;&#1086;&#1086;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>050</b>'' -- &#1047;&#1072;&#1088;&#1072;&#1073;&#1086;&#1090;&#1085=
;&#1072;&#1103;
&#1087;&#1083;&#1072;&#1090;&#1072; &#1083;&#1080;&#1094;,
&#1079;&#1072;&#1084;&#1077;&#1097;&#1072;&#1102;&#1097;&#1080;&#1093; <span
class=3DGramE>&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#108=
0;,
&#1085;&#1077;
&#1103;&#1074;&#1083;&#1103;&#1102;&#1097;&#1080;&#1077;&#1089;&#1103;
')

insert #F2 (File_ID, Orders, Body) values(115,13, '&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1103;&#1084;&#108=
0;
&#1075;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#107=
7;&#1085;&#1085;&#1086;&#1081;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;</spa=
n>
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &#1089;
&laquo;&#1087;&#1091;&#1089;&#1090;&#1099;&#1084;&raquo;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo;
&#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#10=
84;
&#1089;&#1086; &#1074;&#1089;&#1077;&#1084;&#1080;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1072;&#1084;&#1080;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;, &#1082;&#1088;&#1086;&#1084;&#1077;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1072;
&laquo;&#1085;&#1077;&#1090;&raquo;. </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
class=3DGramE>&#1055;&#1086; &#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D=
 ''<b
style=3D''mso-bidi-font-weight:normal''>060</b>'' -- &#1047;&#1072;&#1088;&#10=
72;&#1073;&#1086;&#1090;&#1085;&#1072;&#1103;
&#1087;&#1083;&#1072;&#1090;&#1072; &#1088;&#1072;&#1073;&#1086;&#1090;&#10=
85;&#1080;&#1082;&#1086;&#1074;
&#1075;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#107=
7;&#1085;&#1085;&#1086;&#1075;&#1086;
&#1086;&#1088;&#1075;&#1072;&#1085;&#1072;,
&#1087;&#1077;&#1088;&#1077;&#1074;&#1077;&#1076;&#1077;&#1085;&#1085;&#109=
9;&#1093;
&#1085;&#1072; &#1085;&#1086;&#1074;&#1099;&#1077;
&#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1099;
&#1086;&#1087;&#1083;&#1072;&#1090;&#1099; &#1090;&#1088;&#1091;&#1076;&#10=
72;
3) &#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &laquo;&#10=
44;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1045;&#1076;&#1080;&#1085;&#1086;&#1081;
&#1090;&#1072;&#1088;&#1080;&#1092;&#1085;&#1086;&#1081;
&#1089;&#1077;&#1090;&#1082;&#1080;
&#1088;&#1072;&#1073;&#1086;&#1090;&#1085;&#1080;&#1082;&#1086;&#1074;
&#1073;&#1102;&#1076;&#1078;&#1077;&#1090;&#1085;&#1086;&#1081;
&#1089;&#1092;&#1077;&#1088;&#1099;
(&#1087;&#1077;&#1088;&#1089;&#1086;&#1085;&#1072;&#1083; &#1087;&#1086;
&#1086;&#1073;&#1089;&#1083;&#1091;&#1078;&#1080;&#1074;&#1072;&#1085;&#108=
0;&#1102;
&#1079;&#1076;&#1072;&#1085;&#1080;&#1081;,
&#1074;&#1086;&#1076;&#1080;&#1090;&#1077;&#1083;&#1080; &#1080;
&#1076;&#1088;.)&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo;
&#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#10=
84;
&#1089;&#1086; &#1074;&#1089;&#1077;&#1084;&#1080;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1072;&#1084;&#1080;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;, &#1082;&#1088;&#1086;&#1084;&#1077;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1072;
&laquo;&#1085;&#1077;&#1090;&raquo;. </span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>080</b>'' -- &#1055;&#1088;&#1086;&#1095;&#1080;&#1077;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1099;<span
style=3D''mso-spacerun:yes''>&nbsp;
</span>&#1088;&#1072;&#1073;&#1086;&#1090;&#1085;&#1080;&#1082;&#1072;&#108=
4;<span
style=3D''mso-spacerun:yes''>&nbsp;&nbsp;
</span>&#1075;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#107=
4;&#1077;&#1085;&#1085;&#1086;&#1075;&#1086;
&#1086;&#1088;&#1075;&#1072;&#1085;&#1072; &#1087;&#1086; 212
&#1069;&#1050;&#1056; &#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1=
094;&#1080;&#1103;&#1084;
&#1089;&#1086; &#1074;&#1089;&#1077;&#1084;&#1080;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1072;&#1084;&#1080;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;, &#1082;&#1088;&#1086;&#1084;&#1077;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1072;
&laquo;&#1085;&#1077;&#1090;&raquo; &#1087;&#1083;&#1102;&#1089;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1087;&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1072;&#1084; ''<b style=3D''mso-bidi-fon=
t-weight:
normal''>081</b>'' + ''<b style=3D''mso-bidi-font-weight:normal''>082</b>''. </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>081</b>'' &#8211; &#1089;&#1091;&#1084;&#1084;&#1072; &#1087;&#1086;
&#1087;&#1088;&#1086;&#1074;&#1086;&#1076;&#1082;&#1072;&#1084;:</p>

<p class=3DMsoNormal style=3D''text-indent:18.0pt;mso-layout-grid-align:none;
text-autospace:none''><span style=3D''font-size:10.0pt;font-family:"Courier N=
ew";
color:red;mso-no-proof:yes''><o:p>&nbsp;</o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:35.4pt;mso-layout-grid-align:none;
text-autospace:none''>&#1044;&#1090;.<span style=3D''font-size:10.0pt;font-fa=
mily:
"Courier New";color:red;mso-no-proof:yes''>''2.106.04''</span>, &#1050;&#1090;=
.<span
style=3D''font-size:10.0pt;font-family:"Courier New";color:red;mso-no-proof:=
yes''>''2.302.02''<o:p></o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:35.4pt;mso-layout-grid-align:none;
text-autospace:none''>&#1044;&#1090;.<span style=3D''font-size:10.0pt;font-fa=
mily:
"Courier New";color:red;mso-no-proof:yes''>''106.14,106.24,106.34,106.44''</sp=
an>,
&#1050;&#1090;.<span style=3D''font-size:10.0pt;font-family:"Courier New";
color:red;mso-no-proof:yes''>''1.302.12''</span><span style=3D''font-size:10.0p=
t;
font-family:"Courier New";color:gray;mso-no-proof:yes''><o:p></o:p></span></=
p>

<p class=3DMsoNormal style=3D''text-indent:35.4pt;mso-layout-grid-align:none;
text-autospace:none''>&#1044;&#1090;.<span style=3D''font-size:10.0pt;font-fa=
mily:
"Courier New";color:red;mso-no-proof:yes''>''401.01,401.20''</span>, &#1050;&#=
1090;.<span
style=3D''font-size:10.0pt;font-family:"Courier New";color:red;mso-no-proof:=
yes''>''302.07,302.09,302.06,302.25,302.26,302.34''<o:p></o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:35.4pt;mso-layout-grid-align:none;
text-autospace:none''><span style=3D''font-size:10.0pt;font-family')

insert #F2 (File_ID, Orders, Body) values(115,14, ':"Courier N=
ew";
color:gray;mso-no-proof:yes''><o:p>&nbsp;</o:p></span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>083</b>'' &#8211; &#1089;&#1091;&#1084;&#1084;&#1072; &#1087;&#1086;
&#1087;&#1088;&#1086;&#1074;&#1086;&#1076;&#1082;&#1072;&#1084;:</p>

<p class=3DMsoNormal style=3D''text-indent:35.4pt;mso-layout-grid-align:none;
text-autospace:none''><span style=3D''font-size:10.0pt;font-family:"Courier N=
ew";
color:gray;mso-no-proof:yes''><o:p>&nbsp;</o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:35.4pt;mso-layout-grid-align:none;
text-autospace:none''>&#1044;&#1090;.<span style=3D''font-size:10.0pt;font-fa=
mily:
"Courier New";color:red;mso-no-proof:yes''>''208.02,208.12''</span>, &#1050;&#=
1090;.<span
style=3D''font-size:10.0pt;font-family:"Courier New";color:red;mso-no-proof:=
yes''>''201.04,201.34,304.05,201.01,201.11,201.21''</span><span
style=3D''font-size:10.0pt;font-family:"Courier New";color:gray;mso-no-proof=
:yes''><o:p></o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:35.4pt;mso-layout-grid-align:none;
text-autospace:none''>&#1047;&#1072;
&#1084;&#1080;&#1085;&#1091;&#1089;&#1086;&#1084;: &#1044;&#1090;.<span
style=3D''font-size:10.0pt;font-family:"Courier New";color:red;mso-no-proof:=
yes''>''201.34,201.04''</span>,
&#1050;&#1090;.<span style=3D''font-size:10.0pt;font-family:"Courier New";
color:red;mso-no-proof:yes''>''208.02,208.12''<o:p></o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:35.4pt;mso-layout-grid-align:none;
text-autospace:none''><span style=3D''font-size:10.0pt;font-family:"Courier N=
ew";
color:gray;mso-no-proof:yes''><o:p>&nbsp;</o:p></span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>092</b>'' &#8211; &#1089;&#1091;&#1084;&#1084;&#1072; &#1087;&#1086;
&#1087;&#1088;&#1086;&#1074;&#1086;&#1076;&#1082;&#1072;&#1084;:</p>

<p class=3DMsoNormal style=3D''mso-layout-grid-align:none;text-autospace:non=
e''><span
style=3D''font-size:10.0pt;font-family:"Courier New";color:red;mso-no-proof:=
yes''><o:p>&nbsp;</o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:18.0pt;mso-layout-grid-align:none;
text-autospace:none''>&#1044;&#1090;.<span style=3D''font-size:10.0pt;font-fa=
mily:
"Courier New";color:red;mso-no-proof:yes''>''208.05,208.09,208.22,208.26''</sp=
an>,
&#1050;&#1090;.<span style=3D''font-size:10.0pt;font-family:"Courier New";
color:red;mso-no-proof:yes''>''201.04,201.34,304.05,201.01,201.11,201.21''<o:p=
></o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:18.0pt;mso-layout-grid-align:none;
text-autospace:none''>&#1047;&#1072; &#1084;&#1080;&#1085;&#1091;&#1089;&#10=
86;&#1084;:
&#1044;&#1090;.<span style=3D''font-size:10.0pt;font-family:"Courier New";
color:red;mso-no-proof:yes''>''201.34,201.04''</span>, &#1050;&#1090;.<span
style=3D''font-size:10.0pt;font-family:"Courier New";color:red;mso-no-proof:=
yes''>''208.05,208.09,208.22,208.26''<o:p></o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:18.0pt;mso-layout-grid-align:none;
text-autospace:none''><span style=3D''font-size:10.0pt;font-family:"Courier N=
ew";
color:gray;mso-no-proof:yes''><o:p>&nbsp;</o:p></span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>094</b>'' &#8211; &#1089;&#1091;&#1084;&#1084;&#1072; &#1087;&#1086;
&#1087;&#1088;&#1086;&#1074;&#1086;&#1076;&#1082;&#1072;&#1084;:</p>

<p class=3DMsoNormal style=3D''text-indent:18.0pt;mso-layout-grid-align:none;
text-autospace:none''><span style=3D''font-size:10.0pt;font-family:"Courier N=
ew";
color:gray;mso-no-proof:yes''><o:p>&nbsp;</o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:18.0pt;mso-layout-grid-align:none;
text-autospace:none''>&#1044;&#1090;.<span style=3D''font-size:10.0pt;font-fa=
mily:
"Courier New";color:red;mso-no-proof:yes''>''401.01,401.20''</span>, &#1050;&#=
1090;.<span
style=3D''font-size:10.0pt;font-family:"Courier New";color:red;mso-no-proof:=
yes''>''105.03,105.23,105.33,104.05,104.15,104.25,104.35,104.45''</span><span
style=3D''font-size:10.0pt;font-family:"Courier New";mso-no-proof:yes''> <span
style=3D''color:gray''><o:p></o:p></span></span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>450</b>''<span style=3D''mso-spacerun:yes''>&nbsp; </span>-
&#1082;&#1086;&#1083;&#1080;&#1095;&#1077;&#1089;&#1090;&#1074;&#1086;,
&#1082;&#1072;&#1082; &#1086;&#1089;&#1090;&#1072;&#1090;&#1086;&#1082;
&#1087;&#1086; &#1089;&#1095;&#1105;&#1090;&#1091;: <span style=3D''font-siz=
e:
10.0pt;font-family:"Courier New";color:red;mso-no-proof:yes''>''101.05,101.15=
,101.25,101.35,101.15''</span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1088;&#1086;&#1095;&#1080;&#1077;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1080;
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103; &#10=
74;
&#1089;&#1086;&#1086;&#1090;&#1074;&#1077;&#1090;&#1089;&#1090;&#1074;&#108=
0;&#1077;
&#1089;<span style=3D''mso-spacerun:yes''>&nbsp;
</span>&#1091;&#1089;&#1090;&#1072;&#1085;&#1086;&#1074;&#1083;&#1077;&#108=
5;&#1085;&#1099;&#1084;&#1080;
&#1088;&#1077;&#1082;&#1074;&#1080;&#1079;&#1080;&#1090;&#1072;&#1084;&#108=
0;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1096;&#1090;&#1072;&#1090;&#1085;&#1086;&#1075;&#1086;
&#1088;&#1072;&#1089;&#1087;&#1080;&#1089;&#1072;&#1085;&#1080;&#1103;
&#1085;&#1072; &#1082;&#1086;&#1085;&#1077;&#1094; &#1086;&#1090;&#1095;&#1=
105;&#1090;&#1085;&#1086;&#1075;&#1086;
&#1087;&#1077;&#1088;&#1080;&#1086;&#1076;&#1072;: &laquo;&#1058;&#1080;&#1=
087;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;&raquo;,
&laquo;&#1050;&#1072;&#1090;&#1077;&#1075;&#1086;&#1088;&#1080;&#1103; <span
class=3DSpellE>&#1075;&#1086;&#1089;</span>.
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;&raquo; &#10=
80;
&laquo;&#1043;&#1088;&#1091;&#1087;&#1087;&#1072; <span class=3DSpellE>&#10=
75;&#1086;&#1089;</span>.
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;&raquo;.</p>

<p class=3DMsoNormal><o:p>&nbsp;</o:p></p>

</div>

</body>

</html>

------=_NextPart_01CBD26A.F54A6190
Content-Location: file:///C:/90708BCB/file4923.files/themedata.thmx
Content-Transfer-Encoding: base64
Content-Type: application/vnd.ms-officetheme

UEsDBBQABgAIAAAAIQCCirwT+gAAABwCAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbKyRy2rDMBBF
94X+g9C22HK6KKXYzqJJd30s0g8Y5LEtao+ENAnJ33fsuFC6CC10IxBizpl7Va6P46AOGJPzVOlV
XmiFZH3jqKv0++4pu9cqMVADgyes9AmTXtfXV+XuFDApmaZU6Z45PBiTbI8jpNwHJHlpfRyB5Ro7
E8B+QIfmtijujPXESJzxxNB1+SoLRNegeoPILzCKx7Cg8Pv5DCSAmAtYq8czYVqi0hDC4CywRDAH
an7oM9+2zmLj7X4UaT6DF9jNBDO/XGD1P+ov5wZb2A+stkfp4lx/xCH9LdtSay6Tc/7Uu5AuGC6X
t7Rh5r+tPwEAAP//AwBQSwMEFAAGAAgAAAAhA')

insert #F2 (File_ID, Orders, Body) values(115,15, 'KXWp+fAAAAANgEAAAsAAABfcmVscy8ucmVsc4SP
z2rDMAyH74W9g9F9UdLDGCV2L6WQQy+jfQDhKH9oIhvbG+vbT8cGCrsIhKTv96k9/q6L+eGU5yAW
mqoGw+JDP8to4XY9v3+CyYWkpyUIW3hwhqN727VfvFDRozzNMRulSLYwlRIPiNlPvFKuQmTRyRDS
SkXbNGIkf6eRcV/XH5ieGeA2TNP1FlLXN2Cuj6jJ/7PDMMyeT8F/ryzlRQRuN5RMaeRioagv41O9
kKhlqtQe0LW4+db9AQAA//8DAFBLAwQUAAYACAAAACEAa3mWFoMAAACKAAAAHAAAAHRoZW1lL3Ro
ZW1lL3RoZW1lTWFuYWdlci54bWwMzE0KwyAQQOF9oXeQ2TdjuyhFYrLLrrv2AEOcGkHHoNKf29fl
44M3zt8U1ZtLDVksnAcNimXNLoi38Hwspxuo2kgcxSxs4ccV5ul4GMm0jRPfSchzUX0j1ZCFrbXd
INa1K9Uh7yzdXrkkaj2LR1fo0/cp4kXrKyYKAjj9AQAA//8DAFBLAwQUAAYACAAAACEAoLwYxrUG
AACDGwAAFgAAAHRoZW1lL3RoZW1lL3RoZW1lMS54bWzsWc9uG0UYvyPxDqO9t7ETO42jOFXs2A20
aaPYLepxvB7vTjO7s5oZJ/WtSo9IIERBHKgEXDggIFKLuLTv4D5DoAiK1Ffgm5ldeyfekKSNoILm
EHtnf9//P/PNeOXy3YihXSIk5XHdK18seYjEPu/TOKh7N7vtC0sekgrHfcx4TOreiEjv8uq776zg
ZRWSiCCgj+UyrnuhUsny3Jz0YRnLizwhMbwbcBFhBY8imOsLvAd8IzY3XyotzkWYxh6KcQRsx9+M
fxo/GR+gG4MB9Ym3mvFvMRASK6kXfCY6mjvJiL5+tj8+GD8dPx4fPLsH35/C58eGtr9T1hRyJJtM
oF3M6h6I7vO9LrmrPMSwVPCi7pXMnze3ujKHl1Mipo6hzdG1zV9KlxL0d+aNTBH0JkLL7Urt0vqE
vwEwNYtrtVrNVnnCzwCw74PlVpc8z0p7qdzIeOZA9uss72apWqq4+Bz/hRmda41Go1pLdbFMDch+
rczgl0qLlbV5B29AFl+dwVcaa83mooM3IItfnMG3L9UWKy7egEJG450ZtA5ou51yn0AGnG0UwpcA
vlRK4VMUZMMk27SIAY/VaXMvwne4aAOBJmRY0RipUUIG2IdEb+KoJyjWAvEywbk3dsmXM0taNpK+
oImqe+8nGIpmyu/lk+9fPnmEDvcfH+7/fHj//uH+j5aRQ7WB4yBP9eLbT/58eA/98eirFw8+K8bL
PP7XHz785emnxUAop6k6zz8/+O3xwfMvPvr9uwcF8DWBe3l4l0ZEoutkD23zCAwzXnE1Jz1xNopu
iGmeYi0OJI6xllLAv6VCB319hFkaHUePBnE9eEtAOykCXhnecRTuhGKoaIHkq2HkADc5Zw0uCr1w
VcvKubk7jINi4WKYx21jvFsku4ljJ76tYQJ9NUtLx/BmSBw1txiOFQ5ITBTS7/gOIQXW3abU8esm
9QWXfKDQbYoamBa6pEt7TjZNiTZoBHEZFdkM8XZ8s3kLNTgrsnqd7LpIqArMCpTvEua48QoeKhwV
seziiOUdfg2rsEjJzkj4eVxLKoh0QBhHrT6RsojmhgB7c0G/iqGDFYZ9k40iFykU3SnieQ1znkeu
851miKOkCNuhcZjHvid3IEUx2uKqCL7J3QrRzxAHHB8b7luUOOE+uRvcpIGj0jRB9Juh0LGE1u10
4IjGf9eOGYV+bHPg/NoxNMDnXz4syKw3tRGvwZ5UVAkbR9rvcbijTbfJRZ+++T13HQ/jLQJpPrvx
vG25b1uu959vucfV82kb7bS3QtvVc4Mdks3IHJ16Yh5QxjpqxMg1aYZmCftGvw2Lmo85UJLJiSoJ
4Wva5x1cILChQYKrD6gKOyFOYOAue5pJIFPWgUQJl3DwM8uFvDUehnZlj41VfaCw/UFitcn7dnlB
L2fnhgkbs/sE5rCaCVrQDE4rbOFSyhTMfhVhZa3UqaWVjWqm9TnSJiZDTGdNg8WJN2EgQTDGgJcX
4UivRcNBBTPS1363e3EWFhOF8wyRDHGfpDHSds/GqGyClOWKuTmA3CmIkT4EnuC1nLSaZvsa0k4T
pLy4yjHisui9TpSyDJ5GSdfxkXJkcb44WYz26l6tOl/1kI+TujeAMy58jRKIutQzIGYB3CX5Sti0
P7GYTZVPo1nLDHOLoAzXGNbvMwY7fSARUq1jGdrUMK/SFGCxlmT1n6+CW8/LAJvpr6DFwhIkw7+m
BfjRDS0ZDIiv8sHOrWjf2ce0lfKhIqIT9vdQjw3FNobw61QFe/pUwlWF6Qj6Ae7ZtLfNK7c5p0WX
v90yOLuOWRLitN3qEs0q2cJNHU90ME859cC2Qt2NcWc3xZT8OZmST+P/mSl6P4Gbg4W+joAPN78C
I12vdY8LFXLoQklI/baAQcL0DsgWuKuF15BUcP9sPgXZ1Z+25iwPU9ZwAFTbNECCwn6kQkHIFrQl
k30nMCune5dlyVJGJqNy6srEqt0ju4R1dQ9c1Hu7h0JIddNN0jZgcEfzz31OK6gX6CEnX29OD5ns
vbYG/unJxxYzGOX2YTPQZP6fqFiwq1p6Q57tvXlD9IvpmFXJqgKE5baCWlr2r6jCGbda27FmLJ6v
ZspBFGcthsXJQJTA/Q/S/2D/o8Jn9pcMvaF2+Tb0VgQ/RGhmkDaQ1Rfs4IF0g7SLPRic7KJNJs3K
ujYdnbTXss36nCfdidwjztaanSbeZ3T2ZDhzxTm1eJ7OTj3s+NquHetqiOzREoWlQXawMYExv4Ll
f6XivTsQ6HW47x8yJU0ywW9OAsPo2TF1AMVvJRrS1b8AAAD//wMAUEsDBBQABgAIAAAAIQAN0ZCf
tgAAABsBAAAnAAAAdGhlbWUvdGhlbWUvX3JlbHMvdGhlbWVNYW5hZ2VyLnhtbC5yZWxzhI9NCsIw
FIT3gncIb2/TuhCRJt2I0K3UA4TkNQ02PyRR7O0NriwILodhvplpu5edyRNjMt4xaKoaCDrplXGa
wW247I5AUhZOidk7ZLBggo5vN+0VZ5FLKE0mJFIoLjGYcg4nSpOc0IpU+YCuOKOPVuQio6ZByLvQ
SPd1faDxmwF8xSS9YhB71QAZllCa/7P9OBqJZy8fFl3+UUFz2YUFKKLGzOAjm6pMBMpburrE3wAA
AP//AwBQSwECLQAUAAYACAAAACEAgoq8E/oAAAAcAgAAEwAAAAAAAAAAAAAAAAAAAAAAW0NvbnRl
bnRfVHlwZXNdLnhtbFBLAQItABQABgAIAAAAIQCl1qfnwAAAADYBAAALAAAAAAAAAAAAAAAAACsB
AABfcmVscy8ucmVsc1BLAQItABQABgAIAAAAIQBreZYWgwAAAIoAAAAcAAAAAAAAAAAAAAAAABQC
AAB0aGVtZS90aGVtZS90aGVtZU1hbmFnZXIueG1sUEsBAi0AFAAGAAgAAAAhAKC8GMa1BgAAgxsA
ABYAAAAAAAAAAAAAAAAA0QIAAHRoZW1lL3RoZW1lL3RoZW1lMS54bWxQSwECLQAUAAYACAAAACEA
DdGQn7YAAAAbAQAAJwAAAAAAAAAAAAAAAAC6CQAAdGhlbWUvdGhlbWUvX3JlbHMvdGhlbWVNYW5h
Z2VyLnhtbC5yZWxzUEsFBgAAAAAFAAUAXQEAALUKAAAAAA==

------=_NextPart_01CBD26A.F54A6190
Content-Location: file:///C:/90708BCB/file4923.files/colorschememapping.xml
Content-Transfer-Encoding: quoted-printable
Content-Type: text/xml

<?xml version=3D"1.0" encoding=3D"UTF-8" standalone=3D"yes"?>
<a:clrMap xmlns:a=3D"http://schemas.openxmlformats.org/drawingml/2006/main"=
 bg1=3D"lt1" tx1=3D"dk1" bg2=3D"lt2" tx2=3D"dk2" accent1=3D"accent1" accent=
2=3D"accent2" accent3=3D"accent3" accent4=3D"accent4" accent5=3D"accent5" a=
ccent6=3D"accent6" hlink=3D"hlink" folHlink=3D"folHlink"/>
------=_NextPart_01CBD26A.F54A6190
Content-Location: file:///C:/90708BCB/file4923.files/filelist.xml
Content-Transfer-Encoding: quoted-printable
Content-Type: text/xml; charset="utf-8"

<xml xmlns:o=3D"urn:schemas-microsoft-com:office:office">
 <o:MainFile HRef=3D"../file4923.htm"/>
 <o:File HRef=3D"themedata.thmx"/>
 <o:File HRef=3D"colorschememapping.xml"/>
 <o:File HRef=3D"filelist.xml"/>
</xml>
------=_NextPart_01CBD26A.F54A6190--
')

IF (SELECT COUNT(*) FROM #F2) <> 15
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F2',0)
END
ELSE
	exec dbo.RO_IMPORT_FORM_HINT @iLINK_FORM
drop table #F1
drop table #F2


GO

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL DROP TABLE #tabInfo
SELECT * FROM #tabErrorLog

IF EXISTS(SELECT * FROM #tabErrorLog)
BEGIN
   ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
END

DROP TABLE #tabErrorLog
DROP TABLE #tabStop

COMMIT TRANSACTION -- Фиксация транзакции.
GO


GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (июл  3 2014 11:51:41:937AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0503074 (Отчет о расходах и числ работников гос. органов субъектов РФ (квартальная))
-- Дата ввода : 20110101
-- Дата окончания действия :
-- Версия : 2014-07-03 11:51:41.937
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = '0503074' AND [START_DATE] = '20110101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-07-03 11:51:41.937',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + '0503074',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = '0503074'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20110101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SMETA'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Отчет о расходах и числ работников гос. органов субъектов РФ (квартальная)',@vcNEW_FORM_CODE,@dNEW_START_DATE,2,1,1,1,18186,'RA_EXPORT_FORM_0503074#RA_IMPORT_FORM_0503074',0,0,'19000101',NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, 'svodprint_14_ask()','Sv_0503074G_20101231.bas','','KirRepMakerMultiSheet.xls','Sv_0503074G_20101231.xlt','',NULL,'RA_EXPORT_FORM_0503074#RA_IMPORT_FORM_0503074',0,NULL,NULL,'FORM14_EDIT#26#1','014       ','',NULL,NULL,'|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Таблица', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Утверждено',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Фактически',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Таблица', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Численность', @iLINK_FORM,2
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Утверждено',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Фактически',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Среднесписочная численность',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Численность', @iLINK_FORM,2, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Справка1', @iLINK_FORM,3
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Фактически',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Справка1', @iLINK_FORM,3, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Справка2', @iLINK_FORM,4
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,100,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,0,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'На отчетную дату',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В среднем',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Справка2', @iLINK_FORM,4, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (3,1,1,1)
INSERT #R VALUES (2,1,0,1)
INSERT #R VALUES (4,1,1,1)
INSERT #R VALUES (5,1,1,1)
INSERT #R VALUES (6,1,1,1)
INSERT #R VALUES (7,1,1,1)
INSERT #R VALUES (8,1,1,1)
INSERT #R VALUES (9,1,1,1)
INSERT #R VALUES (10,1,1,1)
INSERT #R VALUES (11,1,1,1)
INSERT #R VALUES (12,1,1,1)
INSERT #R VALUES (13,1,1,1)
INSERT #R VALUES (14,1,1,1)
INSERT #R VALUES (15,1,1,1)
INSERT #R VALUES (16,1,1,1)
INSERT #R VALUES (17,1,1,1)
INSERT #R VALUES (18,1,1,1)
INSERT #R VALUES (19,1,1,1)
INSERT #R VALUES (20,1,1,1)
INSERT #R VALUES (21,1,1,1)
INSERT #R VALUES (22,1,2,1)
INSERT #R VALUES (23,1,1,1)
INSERT #R VALUES (24,1,1,1)
INSERT #R VALUES (25,1,1,1)
INSERT #R VALUES (26,1,1,1)
INSERT #R VALUES (27,1,1,1)
INSERT #R VALUES (28,1,1,1)
INSERT #R VALUES (29,1,1,1)
INSERT #R VALUES (30,1,1,1)
INSERT #R VALUES (31,1,1,1)
INSERT #R VALUES (32,1,1,1)
INSERT #R VALUES (33,1,3,1)
INSERT #R VALUES (1,2,1,1)
INSERT #R VALUES (2,2,1,1)
INSERT #R VALUES (3,2,1,1)
INSERT #R VALUES (4,2,2,1)
INSERT #R VALUES (5,2,1,1)
INSERT #R VALUES (6,2,1,1)
INSERT #R VALUES (7,2,1,1)
INSERT #R VALUES (8,2,1,1)
INSERT #R VALUES (9,2,1,1)
INSERT #R VALUES (10,2,1,1)
INSERT #R VALUES (11,2,1,1)
INSERT #R VALUES (12,2,1,1)
INSERT #R VALUES (13,2,1,1)
INSERT #R VALUES (14,2,1,1)
INSERT #R VALUES (15,2,1,1)
INSERT #R VALUES (16,2,1,1)
INSERT #R VALUES (17,2,1,1)
INSERT #R VALUES (18,2,1,1)
INSERT #R VALUES (19,2,1,1)
INSERT #R VALUES (20,2,1,1)
INSERT #R VALUES (21,2,1,1)
INSERT #R VALUES (22,2,1,1)
INSERT #R VALUES (23,2,1,1)
INSERT #R VALUES (24,2,1,1)
INSERT #R VALUES (25,2,1,1)
INSERT #R VALUES (26,2,3,1)
INSERT #R VALUES (1,3,1,1)
INSERT #R VALUES (2,3,20,1)
INSERT #R VALUES (3,3,5,1)
INSERT #R VALUES (4,3,2,1)
INSERT #R VALUES (5,3,3,1)
INSERT #R VALUES (6,3,4,1)
INSERT #R VALUES (7,3,9,1)
INSERT #R VALUES (8,3,6,1)
INSERT #R VALUES (9,3,7,1)
INSERT #R VALUES (10,3,8,1)
INSERT #R VALUES (11,3,14,1)
INSERT #R VALUES (12,3,10,1)
INSERT #R VALUES (13,3,11,1)
INSERT #R VALUES (14,3,12,1)
INSERT #R VALUES (15,3,13,1)
INSERT #R VALUES (16,3,19,1)
INSERT #R VALUES (17,3,15,1)
INSERT #R VALUES (18,3,16,1)
INSERT #R VALUES (19,3,17,1)
INSERT #R VALUES (20,3,18,1)
INSERT #R VALUES (1,4,1,1)
INSERT #R VALUES (2,4,2,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 80
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,2,1,'Заработная плата лиц, замещающих государственные должности, всего  (сумма строк 011+012+013)                                                                                                                                                              ')
INSERT #F VALUES (1,3,1,'в т.ч.:денежное вознаграждение (денежное содержание, заработная плата судей)                                                                                                                                                                              ')
INSERT #F VALUES (1,4,1,'ежемесячное (ежеквартальное) денежное поощрение                                                                                                                                                                                                           ')
INSERT #F VALUES (1,5,1,'другие выплаты , предусмотренные действующим законодательством                                                                                                                                                                                            ')
INSERT #F VALUES (1,6,1,'Заработная плата  лиц, замещающих должности государственной гражданской службы, всего (сумма строк 021+023+025)                                                                                                                                           ')
INSERT #F VALUES (1,7,1,'в т.ч.:оклад денежного содержания                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,8,1,'из него  оклад по занимаемой должности                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,9,1,'дополнительные выплаты                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,10,1,'из них:  ежемесячное денежное поощрение                                                                                                                                                                                                                   ')
INSERT #F VALUES (1,11,1,'другие выплаты , предусмотренные действующим законодательством                                                                                                                                                                                            ')
INSERT #F VALUES (1,12,1,'Заработная плата лиц, замещающих отдельные должности государственной гражданской службы, 1) всего                               (сумма строк 031+032+033)                                                                                                 ')
INSERT #F VALUES (1,13,1,'в том числе: единое денежное вознаграждение                                                                                                                                                                                                               ')
INSERT #F VALUES (1,14,1,'ежемесячное денежное поощрение и премии                                                                                                                                                                                                                   ')
INSERT #F VALUES (1,15,1,'другие выплаты , предусмотренные действующим законодательством                                                                                                                                                                                            ')
INSERT #F VALUES (1,16,1,'Заработная плата лиц, замещающих  должности  иного вида федеральной государственной службы, 2) всего                     (сумма строк 041+042)                                                                                                            ')
INSERT #F VALUES (1,17,1,'в том числе: оклад денежного содержания                                                                                                                                                                                                                   ')
INSERT #F VALUES (1,18,1,'дополнительные выплаты                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,19,1,'из них ежемесячное денежное поощрение                                                                                                                                                                                                                     ')
INSERT #F VALUES (1,20,1,'Заработная плата лиц, замещающих должности, не являющиеся должностями государственной гражданской службы                                                                                                                                                  ')
INSERT #F VALUES (1,21,1,'Заработная плата работников государственного органа, переведенных на новые системы оплаты труда 3)                                                                                                                                                        ')
INSERT #F VALUES (1,22,1,'Итого расходов на заработную плату работников государственного органа (сумма строк 010+020+030+040+050+060)                                                                                                                                               ')
INSERT #F VALUES (1,23,1,'Прочие выплаты  работникам   государственного органа                                                                                                                                                                                                      ')
INSERT #F VALUES (1,24,1,'из них: компенсации работникам за использование личных легковых автомобилей для служебных целей                                                                                                                                                           ')
INSERT #F VALUES (1,25,1,'суточные при служебных командировках - всего  (сумма строк 083+084)                                                                                                                                                                                       ')
INSERT #F VALUES (1,26,1,'в том числе: на территории Российской Федерации                                                                                                                                                                                                           ')
INSERT #F VALUES (1,27,1,'на территории иностранных государств                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,28,1,'Другие расходы  на содержание   государственного органа                                                                                                                                                                                                   ')
INSERT #F VALUES (1,29,1,'в том числе: на служебные командировки (оплата проезда и проживания) - всего (сумма строк 092+093)                                                                                                                                                        ')
INSERT #F VALUES (1,30,1,'из них: на территории Российской Федерации                                                                                                                                                                                                                ')
INSERT #F VALUES (1,31,1,'на территории иностранных государств                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,32,1,'на содержание служебных легковых автомобилей                                                                                                                                                                                                              ')
INSERT #F VALUES (1,33,1,'Итого расходов  на содержание  государственного органа (сумма строк 070+080+090)                                                                                                                                                                          ')
INSERT #F VALUES (1,2,2,'010                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,3,2,'011                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,4,2,'012                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,5,2,'013                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,6,2,'020                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,7,2,'021                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,8,2,'022                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,9,2,'023                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,10,2,'024                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,11,2,'025                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,12,2,'030                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,13,2,'031                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,14,2,'032                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,15,2,'033                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,16,2,'040                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,17,2,'041                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,18,2,'042                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,19,2,'043                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,20,2,'050                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,21,2,'060                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,22,2,'070                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,23,2,'080                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,24,2,'081                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,25,2,'082                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,26,2,'083                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,27,2,'084                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,28,2,'090                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,29,2,'091                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,30,2,'092                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,31,2,'093                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,32,2,'094                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,33,2,'100                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,2,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,3,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,4,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,7,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,8,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,9,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,10,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,11,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,12,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,13,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,14,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,15,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,17,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,18,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,19,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,20,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,21,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,24,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,25,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,26,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,27,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,29,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,30,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,31,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,32,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,33,3,'ИТОГ_Ф14("070+080+090")')
INSERT #F VALUES (1,2,4,'14_УСТАНОВКА()+14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,3,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,4,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,6,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,8,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,9,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,10,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,11,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,12,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,13,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,14,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,15,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,17,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,18,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,19,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,20,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,21,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,22,4,'ИТОГ_Ф14("010+020+030+040+050+060")')
INSERT #F VALUES (1,23,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,24,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,25,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,26,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,27,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,28,4,'14_ФАКТ_РАСХОД(К.СТР.) ')
INSERT #F VALUES (1,29,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,30,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,31,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,32,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,33,4,'ИТОГ_Ф14("070+080+090")')
INSERT #F VALUES (2,1,1,'Государственные  должности                                                                                                                                                                                                                                ')
INSERT #F VALUES (2,2,1,'Должности государственной гражданской службы                                                                                                                                                                                                              ')
INSERT #F VALUES (2,3,1,'Отдельные должности государственной гражданской   службы 2)                                                                                                                                                                                               ')
INSERT #F VALUES (2,4,1,'Итого  должностей государственной гражданской службы (сумма строк 210+220)                                                                                                                                                                                ')
INSERT #F VALUES (2,5,1,'в том числе по категориям: руководители  (сумма строк 241+242+243)                                                                                                                                                                                        ')
INSERT #F VALUES (2,6,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (2,7,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,8,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,9,1,'помощники (советники) (сумма строк 251+252+253)                                                                                                                                                                                                           ')
INSERT #F VALUES (2,10,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (2,11,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,12,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,13,1,'специалисты  (сумма строк 261+262+263+264)                                                                                                                                                                                                                ')
INSERT #F VALUES (2,14,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (2,15,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,16,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,17,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,18,1,'Обеспечивающие специалисты (сумма строк 271+272+273+274)                                                                                                                                                                                                  ')
INSERT #F VALUES (2,19,1,'из них по группам: главные                                                                                                                                                                                                                                ')
INSERT #F VALUES (2,20,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,21,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,22,1,'младшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,23,1,'Должности иного вида федеральной государственной службы 3)                                                                                                                                                                                                ')
INSERT #F VALUES (2,24,1,'Должности, не являющиеся должностями государственной гражданской службы                                                                                                                                                                                   ')
INSERT #F VALUES (2,25,1,'Должности работников государственного органа, переведенных на новые системы оплаты труда 4)                                                                                                                                                               ')
INSERT #F VALUES (2,26,1,'Всего должностей работнриков (сумма строк 200+230+280+290+300)                                                                                                                                                                                            ')
INSERT #F VALUES (2,1,2,'200                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,2,2,'210                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,3,2,'220                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,4,2,'230                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,5,2,'240                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,6,2,'241                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,7,2,'242                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,8,2,'243                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,9,2,'250                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,10,2,'251                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,11,2,'252                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,12,2,'253                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,13,2,'260                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,14,2,'261                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,15,2,'262                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,16,2,'263                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,17,2,'264                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,18,2,'270                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,19,2,'271                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,20,2,'272                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,21,2,'273                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,22,2,'274                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,23,2,'280                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,24,2,'290                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,25,2,'300                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,26,2,'310                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,1,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,2,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,3,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,4,3,'ИТОГ_Ф14("210+220")')
INSERT #F VALUES (2,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,7,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,8,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,9,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,10,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,12,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,13,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,14,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,15,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,16,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,17,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,18,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,19,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,20,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,21,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,22,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,23,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,24,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,25,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,26,3,'ИТОГ_Ф14("200+230+280+290+300")')
INSERT #F VALUES (2,1,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,2,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,3,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,4,4,'ИТОГ_Ф14("210+220")')
INSERT #F VALUES (2,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,8,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,9,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,10,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,12,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,13,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,14,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,15,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,16,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,17,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,18,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,19,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,20,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,21,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,22,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,23,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,24,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,25,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,26,4,'ИТОГ_Ф14("200+230+280+290+300")')
INSERT #F VALUES (2,1,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,2,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,3,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,4,5,'ИТОГ_Ф14("210+220")')
INSERT #F VALUES (2,5,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,7,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,8,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,9,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,10,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,12,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,13,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,14,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,15,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,16,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,17,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,18,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,19,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,20,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,21,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,22,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,23,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,24,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,25,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,26,5,'ИТОГ_Ф14("200+230+280+290+300KBK")')
INSERT #F VALUES (3,1,1,'Количество государственных органов                                                                                                                                                                                                                        ')
INSERT #F VALUES (3,2,1,'Расходы на выплату денежного содержания, учтенного в строках 020 и 030 всего  (сумма строк 410+420+430+440)                                                                                                                                               ')
INSERT #F VALUES (3,3,1,'в том числе по категориям: руководители  (сумма строк 411+412+413)                                                                                                                                                                                        ')
INSERT #F VALUES (3,4,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (3,5,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,6,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,7,1,'помощники (советники) сумма строк (421+422+423)                                                                                                                                                                                                           ')
INSERT #F VALUES (3,8,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (3,9,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,10,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,11,1,'специалисты  (сумма строк 431+432+433+434)                                                                                                                                                                                                                ')
INSERT #F VALUES (3,12,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (3,13,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,14,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,15,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,16,1,'обеспечивающие специалисты (сумма строк 441+442+443+444)                                                                                                                                                                                                  ')
INSERT #F VALUES (3,17,1,'из них по группам: главные                                                                                                                                                                                                                                ')
INSERT #F VALUES (3,18,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,19,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,20,1,'младшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,1,2,'320                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,2,2,'400                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,3,2,'410                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,4,2,'411                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,5,2,'412                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,6,2,'413                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,7,2,'420                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,8,2,'421                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,9,2,'422                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,10,2,'423                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,11,2,'430                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,12,2,'431                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,13,2,'432                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,14,2,'433                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,15,2,'434                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,16,2,'440                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,17,2,'441                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,18,2,'442                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,19,2,'443                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,20,2,'444                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,2,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,3,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,4,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,7,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,8,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,9,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,10,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,11,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,12,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,13,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,14,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,15,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,16,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,17,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,18,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,19,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,20,3,'ЗАПРЕТ()')
INSERT #F VALUES (4,1,1,'Служебные легковые автомобили, состоящие на балансе государственного органа                                                                                                                                                                               ')
INSERT #F VALUES (4,2,1,'Служебные легковые автомобили, арендованные у других организаций по договорам найма                                                                                                                                                                       ')
INSERT #F VALUES (4,1,2,'450                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,2,2,'460                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,1,3,'ЗАПРЕТ()')
INSERT #F VALUES (4,2,3,'ЗАПРЕТ()')
INSERT #F VALUES (4,1,4,'ЗАПРЕТ()')
INSERT #F VALUES (4,2,4,'ЗАПРЕТ()')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 322
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,4,7,0,0,0,'070-(010+020+030+040+050+060) =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(2,NULL,0,NULL,7,1,0,0,0,'100-(070+080+090) =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(3,NULL,0,NULL,8,7,0,0,0,'230-(210+220) =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(4,NULL,0,NULL,9,1,0,0,0,'240-(241+242+243) =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(5,NULL,0,NULL,10,1,0,0,0,'250-(251+252+253) =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(6,NULL,0,NULL,13,7,0,0,0,'310-(200+230+280+290+300) =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(7,NULL,0,NULL,19,7,0,0,0,'070Гр3>=070Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(8,NULL,0,NULL,20,7,0,0,0,'080Гр3>=080Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(9,NULL,0,NULL,21,7,0,0,0,'100Гр3>=100Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(10,NULL,0,NULL,23,7,0,0,0,'200Гр3>=200Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(11,NULL,0,NULL,24,7,0,0,0,'210Гр3>=210Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(12,NULL,0,NULL,25,7,0,0,0,'220Гр3>=220Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(13,NULL,0,NULL,26,7,0,0,0,'230Гр3>=230Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(14,NULL,0,NULL,51,3,0,0,0,'090Гр3>=090Гр4 =  0',0,0,1,'20111024','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(15,NULL,0,NULL,53,7,0,0,0,'280Гр3>=280Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(16,NULL,0,NULL,54,7,0,0,0,'290Гр3>=290Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(17,NULL,0,NULL,55,7,0,0,0,'300Гр3>=300Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(18,NULL,0,NULL,56,7,0,0,0,'310Гр3>=310Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(19,NULL,0,NULL,58,3,0,0,0,'100>=070 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(20,NULL,0,NULL,59,3,0,0,0,'Укажите расходы по строке 010 или 200 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(21,NULL,0,NULL,60,3,0,0,0,'Укажите расходы по строке 020 или 210 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(22,NULL,0,NULL,61,3,0,0,0,'Укажите данные по строке 030 или 220 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(23,NULL,0,NULL,62,3,0,0,0,'Укажите данные по строке 040 или 280 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(24,NULL,0,NULL,63,3,0,0,0,'Укажите данные по строке 050 или 290 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(25,NULL,0,NULL,64,3,0,0,0,'Укажите данные по строке 060 или 300 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(26,NULL,0,NULL,86,7,0,0,0,'Средняя заработная плата лиц, замещающих  государственные должности =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(27,NULL,0,NULL,87,7,0,0,0,'Средняя заработная плата лиц, замещающие должности государственной гражданской службы =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(28,NULL,0,NULL,88,7,0,0,0,'Сред. заработн. плата лиц, замещающих отдельные должности гос. гражд. службы =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(29,NULL,0,NULL,89,7,0,0,0,'Сред. заработн. плата лиц, замещающих  должности иного вида фед. гос. службы =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(30,NULL,0,NULL,90,7,0,0,0,'Сред. заработн. плата работников государственного органа, замещающих  должности, не являющиеся  должн. гос. гражд. службы =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(31,NULL,0,NULL,91,7,0,0,0,'Сред. заработн. плата работников гос. органа, оплата труда которых производится на основе ETC =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(32,NULL,0,NULL,92,3,0,0,0,'Укажите данные по строке 320 или 310 =  0',0,0,1,'20111024','','','','0503074','20110101','','=',9,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 32
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%070%=%010%+%020%+%030%+%040%+%050%+%060%'',''4'')','070-(010+020+030+040+050+060)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%100%=%070%+%080%+%090%'',''*'')','100-(070+080+090)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%230%=%210%+%220%'' ,''*'')','230-(210+220)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%240%=%241%+%242%+%243%'' ,''*'')','240-(241+242+243)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(4,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%250%=%251%+%252%+%253%'' ,''*'')','250-(251+252+253)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(5,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%310%=%200%+%230%+%280%+%290%+%300%'' ,''*'')','310-(200+230+280+290+300)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%070Гр3%>=%070Гр4% '','''')','070Гр3>=070Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%080Гр3%>=%080Гр4%'','''')','080Гр3>=080Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(8,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%100Гр3%>=%100Гр4%'','''')','100Гр3>=100Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(9,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%200Гр3%>=%200Гр4%'','''')','200Гр3>=200Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(10,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%210Гр3%>=%210Гр4%'','''')','210Гр3>=210Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(11,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%220Гр3%>=%220Гр4%'','''')','220Гр3>=220Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(12,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%230Гр3%>=%230Гр4%'','''')','230Гр3>=230Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(13,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%090Гр3%>=%090Гр4%'','''')','090Гр3>=090Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(14,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%280Гр3%>=%280Гр4%'','''')','280Гр3>=280Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(15,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%290Гр3%>=%290Гр4%'','''')','290Гр3>=290Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(16,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%300Гр3%>=%300Гр4%'','''')','300Гр3>=300Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(17,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%310Гр3%>=%310Гр4%'','''')','310Гр3>=310Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(18,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%100%>=%070%'',''*'')','100>=070','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(19,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %010Гр4%=0 AND %200Гр5%=0 OR %010Гр4%>0 AND %200Гр5%>0 then 1 else 0 end'',''*#Укажите расходы по строке 010 или 200'')','Укажите расходы по строке 010 или 200','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(20,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %020Гр4%=0 AND %210Гр5%=0 OR %020Гр4%>0 AND %210Гр5%>0 then 1 else 0 end'',''*#Укажите расходы по строке 020 или 210'')','Укажите расходы по строке 020 или 210','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(21,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %030Гр4%=0 AND %220Гр5%=0 OR %030Гр4%>0 AND %220Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 030 или 220'')','Укажите данные по строке 030 или 220','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(22,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %040Гр4%=0 AND %280Гр5%=0 OR %040Гр4%>0 AND %280Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 040 или 280'')','Укажите данные по строке 040 или 280','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(23,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %050Гр4%=0 AND %290Гр5%=0 OR %050Гр4%>0 AND %290Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 050 или 290'')','Укажите данные по строке 050 или 290','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(24,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %060Гр4%=0 AND %300Гр5%=0 OR %060Гр4%>0 AND %300Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 060 или 300'')','Укажите данные по строке 060 или 300','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(25,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещ. гос. долж.=%%010Гр4%/%200Гр5%/%MONTH%'','''')','Средняя заработная плата лиц, замещающих  государственные должности','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(26,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещ. долж. гос. гражданской службы=%%020Гр4%/%210Гр5%/%MONTH%'','''')','Средняя заработная плата лиц, замещающие должности государственной гражданской службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(27,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещающих отдельные должности =%%030Гр4%/%220Гр5%/%MONTH%'','''')','Сред. заработн. плата лиц, замещающих отдельные должности гос. гражд. службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(28,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещающих  должности иного вида фед. гос. службы=%%040Гр4%/%280Гр5%/%MONTH%'','''')','Сред. заработн. плата лиц, замещающих  должности иного вида фед. гос. службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(29,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата работников государственного органа, замещающих  должности, не являющиеся  должн. гос. гражд. службы=%%050Гр4%/%290Гр5%/%MONTH%'','''')','Сред. заработн. плата работников государственного органа, замещающих  должности, не являющиеся  должн. гос. гражд. службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(30,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата работников гос. органа, оплата труда которых производится на основе ETC=%%060Гр4%/%300Гр5%/%MONTH%'','''')','Сред. заработн. плата работников гос. органа, оплата труда которых производится на основе ETC','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(31,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %320Гр3%=0 AND %310Гр3%=0 OR %320Гр3%>0 AND %310Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 310 или 320'')','Укажите данные по строке 320 или 310','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(32,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 64
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '8         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'8','14-ые формы',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '999999    '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'999999','формы отчетности',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2014-07-03 11:51:41.937',121) WHERE [LINK_FORM]=@iLINK_FORM

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
ELSE BEGIN
	DECLARE @vcMessage VARCHAR(8000)
	SELECT @vcMessage = [CURRENT_DATE] FROM #tabStop
	IF @vcMessage = '2014-07-03 11:51:41.937'
	BEGIN
		SELECT @vcMessage = 'Форма 0503074 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0503074 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-07-03 11:51:41.937. Обновление отклонено.'
	END

	 IF OBJECT_ID('tempdb..#tabUpdateMessages') IS NOT NULL
	 BEGIN
		 INSERT #tabUpdateMessages([TXT]) VALUES (@vcMessage)
	 END
	 SELECT @vcMessage
END
GO

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL DROP TABLE #tabInfo
SELECT * FROM #tabErrorLog

IF EXISTS(SELECT * FROM #tabErrorLog)
BEGIN
   ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
END

DROP TABLE #tabErrorLog
DROP TABLE #tabStop

COMMIT TRANSACTION -- Фиксация транзакции.
GO


GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (июл  3 2014 11:51:58:460AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0503075 (Отчет о расходах и численности работников органов местного самоуправл.)
-- Дата ввода : 20110101
-- Дата окончания действия :
-- Версия : 2014-07-03 11:51:58.460
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = '0503075' AND [START_DATE] = '20110101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-07-03 11:51:58.460',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + '0503075',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = '0503075'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20110101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SMETA'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Отчет о расходах и численности работников органов местного самоуправл.',@vcNEW_FORM_CODE,@dNEW_START_DATE,2,1,1,1,18186,'RA_EXPORT_FORM_0503074#RA_IMPORT_FORM_0503074',0,0,'19000101',NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, 'svodprint_14_ask()','Sv_0503075g_20101231.bas','','KirRepMakerMultiSheet.xls','SV_0503075_20110101.XLT','',NULL,'RA_EXPORT_FORM_0503074#RA_IMPORT_FORM_0503074',0,NULL,NULL,'FORM14_EDIT#26#1','014mo     ','',NULL,NULL,'|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Таблица', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Утверждено',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Фактически',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Таблица', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Численность', @iLINK_FORM,2
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Утверждено',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Фактически',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Среднесписочная численность',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Численность', @iLINK_FORM,2, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Справка1', @iLINK_FORM,3
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Фактически',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Справка1', @iLINK_FORM,3, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Справка2', @iLINK_FORM,4
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,100,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,0,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'На отчетную дату',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В среднем',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Справка2', @iLINK_FORM,4, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (18,1,1,1)
INSERT #R VALUES (22,1,1,1)
INSERT #R VALUES (1,1,0,1)
INSERT #R VALUES (2,1,1,1)
INSERT #R VALUES (4,1,1,1)
INSERT #R VALUES (5,1,1,1)
INSERT #R VALUES (6,1,1,1)
INSERT #R VALUES (7,1,1,1)
INSERT #R VALUES (8,1,1,1)
INSERT #R VALUES (9,1,1,1)
INSERT #R VALUES (10,1,1,1)
INSERT #R VALUES (11,1,1,1)
INSERT #R VALUES (13,1,2,1)
INSERT #R VALUES (14,1,1,1)
INSERT #R VALUES (17,1,1,1)
INSERT #R VALUES (19,1,1,1)
INSERT #R VALUES (20,1,1,1)
INSERT #R VALUES (21,1,1,1)
INSERT #R VALUES (23,1,1,1)
INSERT #R VALUES (24,1,1,1)
INSERT #R VALUES (25,1,1,1)
INSERT #R VALUES (26,1,3,1)
INSERT #R VALUES (2,2,1,1)
INSERT #R VALUES (3,2,1,1)
INSERT #R VALUES (4,2,1,1)
INSERT #R VALUES (5,2,1,1)
INSERT #R VALUES (6,2,1,1)
INSERT #R VALUES (7,2,1,1)
INSERT #R VALUES (8,2,1,1)
INSERT #R VALUES (9,2,1,1)
INSERT #R VALUES (10,2,1,1)
INSERT #R VALUES (11,2,2,1)
INSERT #R VALUES (1,3,1,1)
INSERT #R VALUES (2,3,20,1)
INSERT #R VALUES (3,3,5,1)
INSERT #R VALUES (4,3,2,1)
INSERT #R VALUES (5,3,3,1)
INSERT #R VALUES (6,3,4,1)
INSERT #R VALUES (7,3,9,1)
INSERT #R VALUES (1,4,1,1)
INSERT #R VALUES (2,4,2,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 41
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,1,1,'Заработная плата лиц, замещающих муниципальные должности, всего (сумма строк 011+012)                                                                                                                                                                     ')
INSERT #F VALUES (1,2,1,'в т.ч.:денежное вознаграждение (денежное содержание)                                                                                                                                                                                                      ')
INSERT #F VALUES (1,4,1,'другие выплаты , предусмотренные действующим законодательством                                                                                                                                                                                            ')
INSERT #F VALUES (1,5,1,'Заработная плата  лиц, замещающих должности муниципальной  службы, всего (сумма строк 021+022+024)                                                                                                                                                        ')
INSERT #F VALUES (1,6,1,'в т.ч.:должностной оклад                                                                                                                                                                                                                                  ')
INSERT #F VALUES (1,7,1,'дополнительные выплаты                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,8,1,'из них:  ежемесячное денежное поощрение                                                                                                                                                                                                                   ')
INSERT #F VALUES (1,9,1,'другие выплаты , предусмотренные действующим законодательством                                                                                                                                                                                            ')
INSERT #F VALUES (1,10,1,'Заработная плата лиц, замещающих должности, не являющиеся должностями муниципальной службы                                                                                                                                                                ')
INSERT #F VALUES (1,11,1,'Заработная плата работников органа местного самоуправления, избирательной комиссии муниципального образования, переведенных на новые системы оплаты труда 1)                                                                                              ')
INSERT #F VALUES (1,13,1,'Итого расходов на заработнрую плату работников органа местного самоуправления, избирательной комиссии муниципального образования (сумма строк 010+0520+030+040)                                                                                           ')
INSERT #F VALUES (1,14,1,'Прочие выплаты  работникам  органа местного самоуправления, избирательной комиссии  муниципального образования                                                                                                                                            ')
INSERT #F VALUES (1,17,1,'из них: компенсации работникам за использование  личных   легковых   автомобилей для служебных целей                                                                                                                                                      ')
INSERT #F VALUES (1,18,1,'суточные при служебных командировках, всего (сумма строк 063+064)                                                                                                                                                                                         ')
INSERT #F VALUES (1,19,1,'в том числе: на территории Российской Федерации                                                                                                                                                                                                           ')
INSERT #F VALUES (1,20,1,'на территории иностранных государств                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,21,1,'Другие расходы  на содержание органа местного самоуправления, избирательной комиссии муниципального образования                                                                                                                                           ')
INSERT #F VALUES (1,22,1,'из них: на служебные командировки (оплата проезда и проживания), всего (сумма строк 072+073)                                                                                                                                                              ')
INSERT #F VALUES (1,23,1,'в том числе: на территории Российской Федерации                                                                                                                                                                                                           ')
INSERT #F VALUES (1,24,1,'на территории иностранных государств                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,25,1,'на содержание служебных легковых автомобилей                                                                                                                                                                                                              ')
INSERT #F VALUES (1,26,1,'ВСЕГО расходов  на содержание  органа местного самоуправления, избирательной комиссии  муниципального образования (сумма строк 050+060+0701)                                                                                                              ')
INSERT #F VALUES (1,1,2,'010                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,2,2,'011                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,4,2,'012                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,5,2,'020                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,6,2,'021                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,7,2,'022                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,8,2,'023                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,9,2,'024                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,10,2,'030                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,11,2,'040                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,13,2,'050                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,14,2,'060')
INSERT #F VALUES (1,17,2,'061                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,18,2,'062                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,19,2,'063                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,20,2,'064                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,21,2,'070')
INSERT #F VALUES (1,22,2,'071                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,23,2,'072                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,24,2,'073                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,25,2,'074                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,26,2,'080                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,1,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,2,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,4,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,7,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,8,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,9,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,10,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,11,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,17,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,18,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,19,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,20,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,22,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,23,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,24,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,25,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,26,3,'ИТОГ_Ф14("050+060+070")')
INSERT #F VALUES (1,1,4,'14МО_УСТАНОВКА()+14МО_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,2,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,4,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,5,4,'14МО_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,6,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,8,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,9,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,10,4,'14МО_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,11,4,'14МО_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,13,4,'ИТОГ_Ф14("010+020+030+040")')
INSERT #F VALUES (1,14,4,'14МО_ФАКТ_РАСХОД(К.СТР.)                                                                                                                                                                                                                                  ')
INSERT #F VALUES (1,17,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,18,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,19,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,20,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,21,4,'14МО_ФАКТ_РАСХОД(К.СТР.)                                                                                                                                                                                                                                  ')
INSERT #F VALUES (1,22,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,23,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,24,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,25,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,26,4,'ИТОГ_Ф14("050+060+070KBK")')
INSERT #F VALUES (2,2,1,'Муниципальные должности                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,3,1,'Должности  муниципальной службы, всего (сумма строк 220+230+240+250+260)                                                                                                                                                                                  ')
INSERT #F VALUES (2,4,1,'в том числе по группам должностей: высшие                                                                                                                                                                                                                 ')
INSERT #F VALUES (2,5,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,6,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,7,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,8,1,'младшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,9,1,'Должности, не являющиеся должностями муниципальной службы                                                                                                                                                                                                 ')
INSERT #F VALUES (2,10,1,'Должности работников, переведенных на новые системы оплаты труда 2)                                                                                                                                                                                       ')
INSERT #F VALUES (2,11,1,'Всего должностей работников органа местного самоуправления, избирательной комиссии муниципального образования, (сумма строк 200+210+270+280)                                                                                                              ')
INSERT #F VALUES (2,2,2,'200                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,3,2,'210                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,4,2,'220                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,5,2,'230                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,6,2,'240                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,7,2,'250                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,8,2,'260                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,9,2,'270                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,10,2,'280                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,11,2,'290                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,2,3,'14МО_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,3,3,'14МО_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,4,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,7,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,8,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,9,3,'14МО_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,10,3,'14МО_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,11,3,'ИТОГ_Ф14("200+210+270+280")')
INSERT #F VALUES (2,2,4,'14МО_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,3,4,'14МО_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,4,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,8,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,9,4,'14МО_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,10,4,'14МО_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,11,4,'ИТОГ_Ф14("200+210+270+280")')
INSERT #F VALUES (2,2,5,'14МО_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,3,5,'14МО_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,4,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,5,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,7,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,8,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,9,5,'14МО_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,10,5,'14МО_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,11,5,'ИТОГ_Ф14("200+210+270+280KBK")')
INSERT #F VALUES (3,1,1,'Количество органов местного самоуправления, избирательных комиссий муниципальных образований')
INSERT #F VALUES (3,2,1,'Денежное содержание  муниципальных  служащих (стр. 020 - 024), всего (сумма строк 410+420+430+440+450)                                                                                                                                                    ')
INSERT #F VALUES (3,3,1,'в том числе по группам должностей: высшие                                                                                                                                                                                                                 ')
INSERT #F VALUES (3,4,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,5,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,6,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,7,1,'младшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,1,2,'300')
INSERT #F VALUES (3,2,2,'400                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,3,2,'410                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,4,2,'420                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,5,2,'430                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,6,2,'440                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,7,2,'450                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,2,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,3,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,4,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,7,3,'ЗАПРЕТ()')
INSERT #F VALUES (4,1,1,'Служебные легковые автомобили, состоящие на балансе органа местного самоуправления, избирательных комиссий муниципальных образований                                                                                                                      ')
INSERT #F VALUES (4,2,1,'Служебные легковые автомобили, арендованные у других организаций по договорам найма                                                                                                                                                                       ')
INSERT #F VALUES (4,1,2,'460                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,2,2,'470                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,1,3,'ЗАПРЕТ()')
INSERT #F VALUES (4,2,3,'ЗАПРЕТ()')
INSERT #F VALUES (4,1,4,'ЗАПРЕТ()')
INSERT #F VALUES (4,2,4,'ЗАПРЕТ()')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 163
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,7,0,0,0,'050(4)=010(4)+020(4)+030(4)+040(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(2,NULL,0,NULL,2,7,0,0,0,'050(3)>=050(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(3,NULL,0,NULL,3,7,0,0,0,'070(3) >=  070(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(4,NULL,0,NULL,4,7,0,0,0,'080(3) >=  080(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(5,NULL,0,NULL,5,7,0,0,0,'290 = 200+210+270+280 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(6,NULL,0,NULL,6,7,0,0,0,'200(3) >=  200(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(7,NULL,0,NULL,7,7,0,0,0,'210(3) >=  210(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(8,NULL,0,NULL,8,7,0,0,0,'270(3) >=  270(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(9,NULL,0,NULL,9,7,0,0,0,'280(3) >=  280(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(10,NULL,0,NULL,10,7,0,0,0,'290(3) >=  290(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(11,NULL,0,NULL,15,7,0,0,0,'080 = 050 + 060 + 070 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(12,NULL,0,NULL,19,7,0,0,0,'060(3)>=060(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(13,NULL,0,NULL,27,3,0,0,0,'Укажите расходы по строке 010 или 200 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(14,NULL,0,NULL,28,3,0,0,0,'Укажите расходы по строке 020 или 210 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(15,NULL,0,NULL,29,3,0,0,0,'Укажите данные по строке 030 или 270 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(16,NULL,0,NULL,30,3,0,0,0,'Укажите данные по строке 040 или 280 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(17,NULL,0,NULL,31,3,0,0,0,'Укажите данные по строке 050 или 290 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(18,NULL,0,NULL,39,3,0,0,0,'Укажите данные по строке 200Гр5 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(19,NULL,0,NULL,40,3,0,0,0,'Укажите данные по строке 270Гр5 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(20,NULL,0,NULL,41,3,0,0,0,'Укажите данные по строке 280Гр5 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(21,NULL,0,NULL,42,7,0,0,0,'Сред. заработн. плата лиц, замещающих муниципальные должности =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(22,NULL,0,NULL,43,7,0,0,0,'Сред. заработн. плата лиц, замещающих должности муниципальной  службы =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(23,NULL,0,NULL,44,7,0,0,0,'Сред. заработн. плата работников органа мест. самоуправ., не являющ.  должн. муниц. службы =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(24,NULL,0,NULL,45,7,0,0,0,'Заработная плата работников ОМС, избирательной комиссии муниц.образования, переведенных на новые системы оплаты труда =  0',0,0,1,'20110210','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(25,NULL,0,NULL,46,3,0,0,0,'Укажите данные по строке 290 или 300 =  0',0,0,1,'20130731','','','','0503075','20110101','','=',9,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 25
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%050%=%010%+%020%+%030%+%040%'',''4'')','050(4)=010(4)+020(4)+030(4)+040(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%050Гр3%>=%050Гр4%'','''')','050(3)>=050(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%070Гр3%>=%070Гр4%'','''')','070(3) >=  070(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%080Гр3%>=%080Гр4%'','''')','080(3) >=  080(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(4,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%290%=%200%+%210%+%270%+%280%'',''*'')','290 = 200+210+270+280','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(5,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%200Гр3%>=%200Гр4%'','''')','200(3) >=  200(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%210Гр3%>=%210Гр4%'','''')','210(3) >=  210(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%270Гр3%>=%270Гр4%'','''')','270(3) >=  270(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(8,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%280Гр3%>=%280Гр4%'','''')','280(3) >=  280(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(9,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%290Гр3%>=%290Гр4%'','''')','290(3) >=  290(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(10,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%080%=%050%+%060%+%070%'',''*'')','080 = 050 + 060 + 070','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(11,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%060Гр3%>=%060Гр4%'','''')','060(3)>=060(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(12,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %010Гр4%=0 AND %200Гр5%=0 OR %010Гр4%>0 AND %200Гр5%>0 then 1 else 0 end'',''*#Укажите расходы по строке 010 или 200'')','Укажите расходы по строке 010 или 200','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(13,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %020Гр4%=0 AND %210Гр5%=0 OR %020Гр4%>0 AND %210Гр5%>0 then 1 else 0 end'',''*#Укажите расходы по строке 020 или 210'')','Укажите расходы по строке 020 или 210','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(14,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %030Гр4%=0 AND %270Гр5%=0 OR %030Гр4%>0 AND %270Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 030 или 270'')','Укажите данные по строке 030 или 270','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(15,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %040Гр4%=0 AND %280Гр5%=0 OR %040Гр4%>0 AND %280Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 040 или 280'')','Укажите данные по строке 040 или 280','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(16,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %050Гр4%=0 AND %290Гр5%=0 OR %050Гр4%>0 AND %290Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 050 или 290'')','Укажите данные по строке 050 или 290','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(17,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when (%200Гр3%=0 and %200Гр4%=0) or (%200Гр3%>0 and %200Гр5%>0) or (%200Гр4%>0 and %200Гр5%>0) then 1 else 0 end'',''*#Укажите данные по строке 200Гр5'')','Укажите данные по строке 200Гр5','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(18,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when (%270Гр3%=0 and %270Гр4%=0) or (%270Гр3%>0 and %270Гр5%>0) or (%270Гр4%>0 and %270Гр5%>0) then 1 else 0 end'',''*#Укажите данные по строке 270Гр5'')','Укажите данные по строке 270Гр5','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(19,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when (%280Гр3%=0 and %280Гр4%=0) or (%280Гр3%>0 and %280Гр5%>0) or (%280Гр4%>0 and %280Гр5%>0) then 1 else 0 end'',''*#Укажите данные по строке 280Гр5'')','Укажите данные по строке 280Гр5','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(20,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещающих муниципальные должности=%%010Гр4%/%200Гр5%/%MONTH%'','''')','Сред. заработн. плата лиц, замещающих муниципальные должности','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(21,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещающих должности муниципальной  службы=%%020Гр4%/%210Гр5%/%MONTH%'','''')','Сред. заработн. плата лиц, замещающих должности муниципальной  службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(22,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата работников органа мест. самоуправ., не являющ.  должн. муниц. службы=%%030Гр4%/%270Гр5%/%MONTH%'','''')','Сред. заработн. плата работников органа мест. самоуправ., не являющ.  должн. муниц. службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(23,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Средняя заработная плата работников ОМС, избирательной комиссии муниц.образования, переведенных на новые системы оплаты труда=%%040Гр4%/%280Гр5%/%MONTH%'','''')','Заработная плата работников ОМС, избирательной комиссии муниц.образования, переведенных на новые системы оплаты труда','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(24,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %290Гр3%=0 AND %300Гр3%=0 OR %290Гр3%>0 AND %300Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 290 или 300'')','Укажите данные по строке 290 или 300','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(25,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 50
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '8         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'8','14-ые формы',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '999999    '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'999999','формы отчетности',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2014-07-03 11:51:58.460',121) WHERE [LINK_FORM]=@iLINK_FORM

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
ELSE BEGIN
	DECLARE @vcMessage VARCHAR(8000)
	SELECT @vcMessage = [CURRENT_DATE] FROM #tabStop
	IF @vcMessage = '2014-07-03 11:51:58.460'
	BEGIN
		SELECT @vcMessage = 'Форма 0503075 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0503075 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-07-03 11:51:58.460. Обновление отклонено.'
	END

	 IF OBJECT_ID('tempdb..#tabUpdateMessages') IS NOT NULL
	 BEGIN
		 INSERT #tabUpdateMessages([TXT]) VALUES (@vcMessage)
	 END
	 SELECT @vcMessage
END
GO

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL DROP TABLE #tabInfo
SELECT * FROM #tabErrorLog

IF EXISTS(SELECT * FROM #tabErrorLog)
BEGIN
   ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
END

DROP TABLE #tabErrorLog
DROP TABLE #tabStop

COMMIT TRANSACTION -- Фиксация транзакции.
GO


GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (июл  2 2014  9:42:40:590AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 4fss (Расчетная ведомость по средствам ФСС РФ)
-- Дата ввода : 20140101
-- Дата окончания действия :
-- Версия : 2014-07-02 09:42:40.587
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = '4fss' AND [START_DATE] = '20140101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-07-02 09:42:40.587',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + '4fss',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = '4fss'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20140101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SALARY'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Расчетная ведомость по средствам ФСС РФ',@vcNEW_FORM_CODE,@dNEW_START_DATE,2,0,0,1,2291,'i_report_export_nalog',0,0,'19000101',NULL,''
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, 'sa_print_4FSS_110214()','4FSS_110214.bas','','KirRepMakerMultiSheet.XLS','4FSS_110214.xlt','',NULL,'i_report_export_nalog',0,NULL,NULL,NULL,'          ','REPORTS_ATR_NOM_OBR',NULL,NULL,'|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р0. Титул', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование',@iLINK_TABLE,0,1,0,0,0,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,0,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала года',@iLINK_TABLE,1,0,3,1,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р0. Титул', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.1 Расчёты по обяз. страхованию', @iLINK_FORM,2
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,0,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Сумма',@iLINK_TABLE,0,0,3,2,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Номер платеж. поручения',@iLINK_TABLE,0,1,4,0,254,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.1 Расчёты по обяз. страхованию', @iLINK_FORM,2, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.2. Расходы на цели обязат. соц. страх', @iLINK_FORM,3
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование статей',@iLINK_TABLE,0,1,0,0,0,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Число случаев / количество получателей',@iLINK_TABLE,0,0,2,1,0,1,NULL,NULL,NULL,'999999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Количество дней, выплат, пособий',@iLINK_TABLE,0,0,3,2,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Расходы. Всего',@iLINK_TABLE,0,0,4,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Расходы. в т.ч. выплаты за счет средств федерального бюджета',@iLINK_TABLE,0,0,5,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.2. Расходы на цели обязат. соц. страх', @iLINK_FORM,3, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.3. Расчет базы для взносов ФСС', @iLINK_FORM,4
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование',@iLINK_TABLE,1,1,1,0,250,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строк',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В т.ч. сумма за 1 мес отч. квартала',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В т.ч. сумма за 2 мес отч. квартала',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В т.ч. сумма за 3 мес отч. квартала',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.3. Расчет базы для взносов ФСС', @iLINK_FORM,4, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.3.1. Сведения, для применения пониженного', @iLINK_FORM,5
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,4,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Фамилия имя отчество',@iLINK_TABLE,1,1,2,0,100,1,'KU_PERSON_FIO','COL2','CODE',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Дата справки',@iLINK_TABLE,1,1,3,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Срок действия',@iLINK_TABLE,1,1,4,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В т.ч. сумма за 1 мес отч. квартала',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'В т.ч. сумма за 2 мес отч. квартала',@iLINK_TABLE,1,0,7,7,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'В т.ч. сумма за 3 мес отч. квартала',@iLINK_TABLE,1,0,8,8,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.3.1. Сведения, для применения пониженного', @iLINK_FORM,5, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.SA_4FSS_28022011_PREPARE_INV @Lsf',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.4. Условия применения пониж. тарифа таб.1', @iLINK_FORM,6
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В т.ч. сумма за 1 мес отч. квартала',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В т.ч. сумма за 2 мес отч. квартала',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В т.ч. сумма за 3 мес отч. квартала',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.4. Условия применения пониж. тарифа таб.1', @iLINK_FORM,6, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.4.1 Условия применения пониж. тарифа таб.2', @iLINK_FORM,7
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В т.ч. сумма за 1 мес отч. квартала',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В т.ч. сумма за 2 мес отч. квартала',@iLINK_TABLE,1,0,5,5,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В т.ч. сумма за 3 мес отч. квартала',@iLINK_TABLE,1,0,6,6,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.4.1 Условия применения пониж. тарифа таб.2', @iLINK_FORM,7, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.4.2. Расчёт условий для орг. инф. техн.', @iLINK_FORM,8
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'По итогам  9-ти месяцев года, предшествующего текущему расчетному пери',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'По итогам текущего отчетного (расчетного) периода',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Дата записи в реестре аккредитованных организаций',@iLINK_TABLE,1,1,5,5,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'№ записи в реестре аккредитованных организаций',@iLINK_TABLE,1,1,6,6,50,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.4.2. Расчёт условий для орг. инф. техн.', @iLINK_FORM,8, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.4.3. Расчёт условий для орг. и и.п. - упро', @iLINK_FORM,9
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'С начала отчетного (расчетного) периода',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.4.3. Расчёт условий для орг. и и.п. - упро', @iLINK_FORM,9, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.4.4. Расчёт условий для некомерч. орг.', @iLINK_FORM,10
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'По итогам года, предшествующего текущему расчетному периоду',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'По итогам текущего расчетного периода',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.4.4. Расчёт условий для некомерч. орг.', @iLINK_FORM,10, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.4.5.Свед., для прим. пониж. тарифа п14 ч1', @iLINK_FORM,11
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'№ патента',@iLINK_TABLE,1,1,2,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Вид предпринимательской деятельности, установленный законом субъекта Российской Федерации',@iLINK_TABLE,1,1,3,0,254,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Сведения из патента - дата начала действия',@iLINK_TABLE,1,1,4,0,10,1,NULL,NULL,NULL,'99.99.9999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Сведения из патента - дата окончания действия',@iLINK_TABLE,1,1,5,0,10,1,NULL,NULL,NULL,'99.99.9999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Всего с начала расчетного периода',@iLINK_TABLE,0,0,6,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'В т.ч. за последние три месяца о.п. - 1 месяц',@iLINK_TABLE,1,0,7,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'В т.ч. за последние три месяца о.п. - 2 месяц',@iLINK_TABLE,1,0,8,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'В т.ч. за последние три месяца о.п. - 3 месяц',@iLINK_TABLE,1,0,9,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.4.5.Свед., для прим. пониж. тарифа п14 ч1', @iLINK_FORM,11, @iLINK_CODE_COL,1,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.5. Выпл. за счёт средств Федерал. бюджета', @iLINK_FORM,12
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование статей',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего число получателей',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Всего количество дней, выплат, пособий',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Всего расходы (сумма)',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В т.ч. Чернобыльская АЭС число получателей',@iLINK_TABLE,1,0,6,6,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'В т.ч. Чернобыльская АЭС количество дней, выплат, пособий',@iLINK_TABLE,1,0,7,7,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'В т.ч. Чернобыльская АЭС расходы (сумма)',@iLINK_TABLE,1,0,8,8,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'В т.ч. ПО "Маяк" число получателей',@iLINK_TABLE,1,0,9,9,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'В т.ч. ПО "Маяк" количество дней, выплат, пособий',@iLINK_TABLE,1,0,10,10,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'В т.ч. ПО "Маяк" расходы (сумма)',@iLINK_TABLE,1,0,11,11,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'В т.ч. Семипалатинский полигон число получателей',@iLINK_TABLE,1,0,12,12,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'В т.ч. Семипалатинский полигон количество дней, выплат, пособий',@iLINK_TABLE,1,0,13,13,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'В т.ч. Семипалатинский полигон расходы (сумма)',@iLINK_TABLE,1,0,14,14,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 15,'В т.ч. подразделения особого риска число получателей',@iLINK_TABLE,1,0,15,15,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 16,'В т.ч. подразделения особого риска количество дней, выплат, пособий',@iLINK_TABLE,1,0,16,16,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 17,'В т.ч. подразделения особого риска расходы (сумма)',@iLINK_TABLE,1,0,17,17,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 18,'В т.ч. доп.выпл. по № 255-ФЗ число получателей',@iLINK_TABLE,1,0,18,18,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 19,'В т.ч. доп.выпл. по № 255-ФЗ количество дней, выплат, пособий',@iLINK_TABLE,1,0,19,19,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 20,'В т.ч. доп.выпл. по № 255-ФЗ расходы (сумма)',@iLINK_TABLE,1,0,20,20,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.5. Выпл. за счёт средств Федерал. бюджета', @iLINK_FORM,12, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.Табл.6. Несчастные случаи - база', @iLINK_FORM,13
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Выплаты, на которые начисляются стр. взносы, всего',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'в.т.ч. выплаты инвалидам, на которые начисляются стр. взносы',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Выплаты , на которые не начисляются стр. взносы',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Размер страхового тарифа',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Скидка к страховому тарифу',@iLINK_TABLE,1,0,7,7,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Дата установления надбавки к стр. тарифу',@iLINK_TABLE,1,1,8,9,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'% надбавки к стр. тарифу',@iLINK_TABLE,1,0,9,9,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Размер тарифа с учётом скидки (надбавки)',@iLINK_TABLE,1,0,10,10,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.Табл.6. Несчастные случаи - база', @iLINK_FORM,13, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.Табл.7. Несчастные случаи - расчёт', @iLINK_FORM,14
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Сумма (руб.коп.)',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Номер платеж. поручения',@iLINK_TABLE,1,1,4,0,50,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.Табл.7. Несчастные случаи - расчёт', @iLINK_FORM,14, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.Табл.8. Расходы по страхованию от несч. случ.', @iLINK_FORM,15
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование статей',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Количество дней',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Сумма (руб., коп.)',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.Табл.8. Расходы по страхованию от несч. случ.', @iLINK_FORM,15, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.Табл.9. Численность пострадавших по стр. случ.', @iLINK_FORM,16
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Численность пострадавших человек',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.Табл.9. Численность пострадавших по стр. случ.', @iLINK_FORM,16, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.Табл.10. Свед. о рез. провед. спец. оценке усл.', @iLINK_FORM,17
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Общее количество рабочих мест страхователя',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Кол. раб. мест, в отн. усл.труд. на которых провед. спец.оценка у.т. - на начало года',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Кол. раб. мест, на которых провед. спец.оценка. Вред и опасн классы  - 3 класс',@iLINK_TABLE,1,0,6,6,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Кол. раб. мест, на которых провед. спец. оценка. Вред и опасн классы  - 4 класс',@iLINK_TABLE,1,0,7,7,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Общ. число. раб., на вред. и (или) опас. производст. подлежащих медосмот',@iLINK_TABLE,1,0,8,8,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Кол. раб., на вред. и (или) опас. производ. прошедших медосмотр на нач',@iLINK_TABLE,1,0,9,9,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.Табл.10. Свед. о рез. провед. спец. оценке усл.', @iLINK_FORM,17, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (1,1,1,1)
INSERT #R VALUES (2,1,3,1)
INSERT #R VALUES (3,1,4,1)
INSERT #R VALUES (4,1,4,1)
INSERT #R VALUES (1,2,1,1)
INSERT #R VALUES (2,2,2,1)
INSERT #R VALUES (3,2,34,1)
INSERT #R VALUES (4,2,4,1)
INSERT #R VALUES (5,2,33,1)
INSERT #R VALUES (6,2,6,1)
INSERT #R VALUES (7,2,7,1)
INSERT #R VALUES (8,2,8,1)
INSERT #R VALUES (9,2,34,1)
INSERT #R VALUES (10,2,10,1)
INSERT #R VALUES (11,2,33,1)
INSERT #R VALUES (12,2,12,1)
INSERT #R VALUES (13,2,13,1)
INSERT #R VALUES (14,2,14,1)
INSERT #R VALUES (15,2,34,1)
INSERT #R VALUES (16,2,16,1)
INSERT #R VALUES (17,2,33,1)
INSERT #R VALUES (18,2,18,1)
INSERT #R VALUES (19,2,19,1)
INSERT #R VALUES (20,2,20,1)
INSERT #R VALUES (21,2,34,1)
INSERT #R VALUES (22,2,22,1)
INSERT #R VALUES (23,2,33,1)
INSERT #R VALUES (24,2,24,1)
INSERT #R VALUES (25,2,25,1)
INSERT #R VALUES (26,2,26,1)
INSERT #R VALUES (27,2,34,1)
INSERT #R VALUES (28,2,28,1)
INSERT #R VALUES (29,2,33,1)
INSERT #R VALUES (30,2,30,1)
INSERT #R VALUES (31,2,31,1)
INSERT #R VALUES (32,2,32,1)
INSERT #R VALUES (33,2,55,1)
INSERT #R VALUES (34,2,34,1)
INSERT #R VALUES (35,2,35,1)
INSERT #R VALUES (36,2,36,1)
INSERT #R VALUES (37,2,37,1)
INSERT #R VALUES (38,2,38,1)
INSERT #R VALUES (39,2,39,1)
INSERT #R VALUES (40,2,53,1)
INSERT #R VALUES (41,2,41,1)
INSERT #R VALUES (42,2,52,1)
INSERT #R VALUES (43,2,43,1)
INSERT #R VALUES (44,2,44,1)
INSERT #R VALUES (45,2,45,1)
INSERT #R VALUES (46,2,53,1)
INSERT #R VALUES (47,2,47,1)
INSERT #R VALUES (48,2,52,1)
INSERT #R VALUES (49,2,49,1)
INSERT #R VALUES (50,2,50,1)
INSERT #R VALUES (1,3,2,1)
INSERT #R VALUES (2,3,1,1)
INSERT #R VALUES (3,3,2,1)
INSERT #R VALUES (4,3,1,1)
INSERT #R VALUES (5,3,3,1)
INSERT #R VALUES (6,3,2,1)
INSERT #R VALUES (7,3,1,1)
INSERT #R VALUES (8,3,2,1)
INSERT #R VALUES (9,3,1,1)
INSERT #R VALUES (10,3,1,1)
INSERT #R VALUES (11,3,1,1)
INSERT #R VALUES (12,3,4,1)
INSERT #R VALUES (1,4,1,1)
INSERT #R VALUES (2,4,2,1)
INSERT #R VALUES (3,4,3,1)
INSERT #R VALUES (4,4,4,1)
INSERT #R VALUES (5,4,5,1)
INSERT #R VALUES (6,4,6,1)
INSERT #R VALUES (7,4,7,1)
INSERT #R VALUES (8,4,8,1)
INSERT #R VALUES (1,6,1,1)
INSERT #R VALUES (2,6,2,1)
INSERT #R VALUES (3,6,4,1)
INSERT #R VALUES (1,7,1,1)
INSERT #R VALUES (2,7,2,1)
INSERT #R VALUES (3,7,4,1)
INSERT #R VALUES (4,7,5,1)
INSERT #R VALUES (5,7,6,1)
INSERT #R VALUES (6,7,7,1)
INSERT #R VALUES (1,8,1,1)
INSERT #R VALUES (2,8,3,1)
INSERT #R VALUES (3,8,4,1)
INSERT #R VALUES (4,8,5,1)
INSERT #R VALUES (5,8,6,1)
INSERT #R VALUES (1,9,1,1)
INSERT #R VALUES (2,9,2,1)
INSERT #R VALUES (3,9,3,1)
INSERT #R VALUES (1,10,1,1)
INSERT #R VALUES (2,10,2,1)
INSERT #R VALUES (3,10,3,1)
INSERT #R VALUES (4,10,4,1)
INSERT #R VALUES (5,10,5,1)
INSERT #R VALUES (1,12,1,1)
INSERT #R VALUES (2,12,3,1)
INSERT #R VALUES (3,12,4,1)
INSERT #R VALUES (4,12,5,1)
INSERT #R VALUES (5,12,6,1)
INSERT #R VALUES (6,12,7,1)
INSERT #R VALUES (7,12,8,1)
INSERT #R VALUES (1,13,1,1)
INSERT #R VALUES (2,13,3,1)
INSERT #R VALUES (3,13,4,1)
INSERT #R VALUES (4,13,5,1)
INSERT #R VALUES (5,13,6,1)
INSERT #R VALUES (1,14,1,1)
INSERT #R VALUES (2,14,3,1)
INSERT #R VALUES (3,14,4,1)
INSERT #R VALUES (4,14,5,1)
INSERT #R VALUES (5,14,6,1)
INSERT #R VALUES (6,14,7,1)
INSERT #R VALUES (7,14,8,1)
INSERT #R VALUES (8,14,9,1)
INSERT #R VALUES (9,14,10,1)
INSERT #R VALUES (10,14,11,1)
INSERT #R VALUES (11,14,12,1)
INSERT #R VALUES (12,14,13,1)
INSERT #R VALUES (13,14,14,1)
INSERT #R VALUES (14,14,15,1)
INSERT #R VALUES (15,14,16,1)
INSERT #R VALUES (16,14,17,1)
INSERT #R VALUES (17,14,18,1)
INSERT #R VALUES (18,14,19,1)
INSERT #R VALUES (19,14,20,1)
INSERT #R VALUES (20,14,21,1)
INSERT #R VALUES (21,14,22,1)
INSERT #R VALUES (22,14,23,1)
INSERT #R VALUES (23,14,24,1)
INSERT #R VALUES (24,14,25,1)
INSERT #R VALUES (25,14,26,1)
INSERT #R VALUES (26,14,27,1)
INSERT #R VALUES (27,14,28,1)
INSERT #R VALUES (28,14,29,1)
INSERT #R VALUES (29,14,30,1)
INSERT #R VALUES (30,14,31,1)
INSERT #R VALUES (31,14,32,1)
INSERT #R VALUES (1,15,1,1)
INSERT #R VALUES (2,15,3,1)
INSERT #R VALUES (3,15,4,1)
INSERT #R VALUES (4,15,5,1)
INSERT #R VALUES (5,15,6,1)
INSERT #R VALUES (6,15,7,1)
INSERT #R VALUES (7,15,8,1)
INSERT #R VALUES (8,15,9,1)
INSERT #R VALUES (9,15,10,1)
INSERT #R VALUES (10,15,11,1)
INSERT #R VALUES (1,16,1,1)
INSERT #R VALUES (2,16,3,1)
INSERT #R VALUES (3,16,4,1)
INSERT #R VALUES (4,16,5,1)
INSERT #R VALUES (5,16,6,1)
INSERT #R VALUES (1,17,1,1)
INSERT #R VALUES (2,17,2,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 156
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,1,1,'Численность работников                                                                                                                                                                                                                                        ')
INSERT #F VALUES (1,2,1,'из них: женщин                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,3,1,'работающих инвалидов                                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,4,1,'работающих, занятых на работах с вредными и (или) опасными производственными факторами                                                                                                                                                                    ')
INSERT #F VALUES (1,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (1,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,4,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,1,3,'4ФСС_09022012_УСТАНОВКА() + 4ФСС_РАЗДЕЛ1(К.СТР.,6)')
INSERT #F VALUES (1,2,3,'4ФСС_РАЗДЕЛ1(К.СТР.,6)')
INSERT #F VALUES (1,3,3,'4ФСС_РАЗДЕЛ1(К.СТР.,6)')
INSERT #F VALUES (1,4,3,'4ФСС_РАЗДЕЛ1(К.СТР.,6)')
INSERT #F VALUES (2,1,1,'Задолженность за страхователем на начало расчетного периода                                                                                                                                                                                               ')
INSERT #F VALUES (2,2,1,'Начислено страховых взносов                                                                                                                                                                                                                               ')
INSERT #F VALUES (2,3,1,'на начало квартала                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,4,1,'за отчетный квартал (месяцы)                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,5,1,'1 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,6,1,'2 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,7,1,'3 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,8,1,'Начислено страховых взносов по актам проверок                                                                                                                                                                                                             ')
INSERT #F VALUES (2,9,1,'на начало квартала                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,10,1,'за отчетный квартал (месяцы)                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,11,1,'1 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,12,1,'2 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,13,1,'3 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,14,1,'Начислено страховых взносов страхователем за прошлые годы                                                                                                                                                                                                 ')
INSERT #F VALUES (2,15,1,'Не принято к зачету расходов территориальным органом Фонда                                                                                                                                                                                                ')
INSERT #F VALUES (2,16,1,'на начало квартала                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,17,1,'за отчетный квартал (месяцы)                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,18,1,'1 месяц')
INSERT #F VALUES (2,19,1,'2 месяц')
INSERT #F VALUES (2,20,1,'3 месяц')
INSERT #F VALUES (2,21,1,'Получено от территориального органа Фонда на банковский счет в возмещение произведенных расходов                                                                                                                                                          ')
INSERT #F VALUES (2,22,1,'на начало квартала                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,23,1,'за отчетный квартал (месяцы)                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,24,1,'1 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,25,1,'2 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,26,1,'3 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,27,1,'Возврат сумм излишне перечисленных страховых взносов                                                                                                                                                                                                      ')
INSERT #F VALUES (2,28,1,'Всего (стр. 1 - 7)                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,29,1,'Задолженность за территориальным органом Фонда на конец отчетного (расчетного) периода                                                                                                                                                                    ')
INSERT #F VALUES (2,30,1,'в том числе: за счет превышения расходов                                                                                                                                                                                                                  ')
INSERT #F VALUES (2,31,1,'                       за счет переплаты страховых взносов                                                                                                                                                                                                ')
INSERT #F VALUES (2,32,1,'Задолженность за территориальным органом Фонда на начало расчетного периода                                                                                                                                                                               ')
INSERT #F VALUES (2,33,1,'в том числе: за счет превышения расходов                                                                                                                                                                                                                  ')
INSERT #F VALUES (2,34,1,'                       за счет переплаты страховых взносов                                                                                                                                                                                                ')
INSERT #F VALUES (2,35,1,'Расходы на цели обязательного социального страхования                                                                                                                                                                                                     ')
INSERT #F VALUES (2,36,1,'на начало квартала                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,37,1,'за отчетный квартал (месяцы)                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,38,1,'1 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,39,1,'2 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,40,1,'3 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,41,1,'Перечислены страховые взносы                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,42,1,'на начало квартала                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,43,1,'За отчетный квартал (месяцы)                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,44,1,'1 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,45,1,'2 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,46,1,'3 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,47,1,'Списано                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,48,1,'Всего (стр. 12, 15, 16, 17)                                                                                                                                                                                                                               ')
INSERT #F VALUES (2,49,1,'Задолженность за страхователем на конец отчетного (расчетного) периода                                                                                                                                                                                    ')
INSERT #F VALUES (2,50,1,'в том числе недоимка                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (2,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,3,2,'2_1                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,4,2,'2_2                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,5,2,'2_3                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,6,2,'2_4                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,7,2,'2_5                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,8,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,9,2,'3_1                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,10,2,'3_2                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,11,2,'3_3                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,12,2,'3_4                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,13,2,'3_5                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,14,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,15,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,16,2,'5_1                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,17,2,'5_2                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,18,2,'5_3')
INSERT #F VALUES (2,19,2,'5_4')
INSERT #F VALUES (2,20,2,'5_5')
INSERT #F VALUES (2,21,2,'6                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,22,2,'6_1                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,23,2,'6_2                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,24,2,'6_3                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,25,2,'6_4                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,26,2,'6_5                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,27,2,'7                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,28,2,'8                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,29,2,'9                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (2,30,2,'10                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (2,31,2,'11                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,32,2,'12                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (2,33,2,'13                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (2,34,2,'14                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,35,2,'15                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,36,2,'15_1                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,37,2,'15_2                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,38,2,'15_3                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,39,2,'15_4                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,40,2,'15_5                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,41,2,'16                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,42,2,'16_1                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,43,2,'16_2                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,44,2,'16_3                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,45,2,'16_4                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,46,2,'16_5                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,47,2,'17                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,48,2,'18                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,49,2,'19                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (2,50,2,'20                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,1,3,'4ФСС_РАЗДЕЛ1(''0101'',3)')
INSERT #F VALUES (2,3,3,'4ФСС_РАЗДЕЛ1(''0121'',3)')
INSERT #F VALUES (2,5,3,'4ФСС_РАЗДЕЛ1(''0123'',3)')
INSERT #F VALUES (2,6,3,'4ФСС_РАЗДЕЛ1(''0124'',3)')
INSERT #F VALUES (2,7,3,'4ФСС_РАЗДЕЛ1(''0125'',3)')
INSERT #F VALUES (2,18,3,'')
INSERT #F VALUES (2,19,3,'')
INSERT #F VALUES (2,20,3,'')
INSERT #F VALUES (2,22,3,'АДТКТ("_.304.05:_.201.11:_.201.21:_.201.27","_.303.02","ДЛЯ ДАТА>=''01.01'' И ДАТА<КВАРТАЛ")')
INSERT #F VALUES (2,24,3,'АДТКТ("_.304.05:_.201.11:_.201.21:_.201.27","_.303.02","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,25,3,'АДТКТ("_.304.05:_.201.11:_.201.21:_.201.27","_.303.02","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,26,3,'АДТКТ("_.304.05:_.201.11:_.201.21:_.201.27","_.303.02","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,29,3,'4ФСС_РАЗДЕЛ1(''0109'',3)')
INSERT #F VALUES (2,30,3,'4ФСС_РАЗДЕЛ1(''0109'',3)')
INSERT #F VALUES (2,32,3,'4ФСС_РАЗДЕЛ1(''0112'',3)')
INSERT #F VALUES (2,33,3,'4ФСС_РАЗДЕЛ1(''0112'',3)')
INSERT #F VALUES (2,36,3,'АДТКТ("_.303.02","_.302.13","ДЛЯ ДАТА>=''01.01'' И ДАТА<КВАРТАЛ")')
INSERT #F VALUES (2,38,3,'АДТКТ("_.303.02","_.302.13","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,39,3,'АДТКТ("_.303.02","_.302.13","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,40,3,'АДТКТ("_.303.02","_.302.13","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,42,3,'АДТКТ("_.303.02","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА>=''01.01'' И ДАТА<КВАРТАЛ")')
INSERT #F VALUES (2,44,3,'АДТКТ("_.303.02","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,45,3,'АДТКТ("_.303.02","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,46,3,'АДТКТ("_.303.02","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,49,3,'4ФСС_РАЗДЕЛ1(''0119'',3)')
INSERT #F VALUES (2,1,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,2,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,3,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,4,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,8,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,9,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,10,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,12,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,13,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,14,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,15,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,16,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,17,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,18,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,19,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,20,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,21,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,22,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,23,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,24,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,25,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,26,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,27,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,28,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,29,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,30,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,31,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,32,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,33,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,34,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,35,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,36,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,37,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,38,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,39,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,40,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,41,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,42,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,43,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,44,4,'НОМ_ПЛАТЕЖ("_.303.02","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,45,4,'НОМ_ПЛАТЕЖ("_.303.02","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,46,4,'НОМ_ПЛАТЕЖ("_.303.02","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,47,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,48,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,49,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,50,4,'ЗАПРЕТ()')
INSERT #F VALUES (3,1,1,'По временной нетрудоспособности                                                                                                                                                                                                                               ')
INSERT #F VALUES (3,2,1,'      из них: по внешнему совместительству                                                                                                                                                                                                                    ')
INSERT #F VALUES (3,3,1,'По беременности и родам                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,4,1,'      из них: по внешнему совместительству                                                                                                                                                                                                                    ')
INSERT #F VALUES (3,5,1,'Единовременное пособие женщинам, вставшим на учет в медицинских учреждениях в ранние сроки беременности                                                                                                                                                   ')
INSERT #F VALUES (3,6,1,'Единовременное пособие при рождении ребенка                                                                                                                                                                                                               ')
INSERT #F VALUES (3,7,1,'Ежемесячное пособие по уходу за ребенком                                                                                                                                                                                                                  ')
INSERT #F VALUES (3,8,1,'          в том числе: по уходу за первым ребенком                                                                                                                                                                                                        ')
INSERT #F VALUES (3,9,1,'          по уходу за вторым и последующими детьми                                                                                                                                                                                                        ')
INSERT #F VALUES (3,10,1,'Оплата 4-х дополнительных выходных дней для ухода за детьми-инвалидами                                                                                                                                                                                    ')
INSERT #F VALUES (3,11,1,'Социальное пособие на погребение                                                                                                                                                                                                                          ')
INSERT #F VALUES (3,12,1,'ИТОГО ( сумма строк 1+ 3+ 5+ 6+ 7+ 10+11)                                                                                                                                                                                                                 ')
INSERT #F VALUES (3,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (3,2,2,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (3,3,2,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (3,4,2,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (3,5,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (3,6,2,'6                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (3,7,2,'7                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (3,8,2,'8                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (3,9,2,'9                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (3,10,2,'10                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (3,11,2,'11                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (3,12,2,'12                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (3,1,3,'4ФСС_РАЗДЕЛ1(''0201'',7)')
INSERT #F VALUES (3,2,3,'4ФСС_РАЗДЕЛ1(''0202'',7)')
INSERT #F VALUES (3,3,3,'4ФСС_РАЗДЕЛ1(''0203'',7)')
INSERT #F VALUES (3,4,3,'4ФСС_РАЗДЕЛ1(''0204'',7)')
INSERT #F VALUES (3,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,8,3,'4ФСС_РАЗДЕЛ1(''0208'',7)')
INSERT #F VALUES (3,9,3,'4ФСС_РАЗДЕЛ1(''0209'',7)')
INSERT #F VALUES (3,10,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,11,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,12,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,1,4,'4ФСС_РАЗДЕЛ1(''0201'',6)')
INSERT #F VALUES (3,2,4,'4ФСС_РАЗДЕЛ1(''0202'',6)')
INSERT #F VALUES (3,3,4,'4ФСС_РАЗДЕЛ1(''0203'',6)')
INSERT #F VALUES (3,4,4,'4ФСС_РАЗДЕЛ1(''0204'',6)')
INSERT #F VALUES (3,5,4,'4ФСС_РАЗДЕЛ1(''0205'',6) ')
INSERT #F VALUES (3,6,4,'4ФСС_РАЗДЕЛ1(''0206'',6)  ')
INSERT #F VALUES (3,8,4,'4ФСС_РАЗДЕЛ1(''0208'',6)')
INSERT #F VALUES (3,9,4,'4ФСС_РАЗДЕЛ1(''0209'',6)')
INSERT #F VALUES (3,10,4,'4ФСС_РАЗДЕЛ1(''0210'',6)')
INSERT #F VALUES (3,11,4,'4ФСС_РАЗДЕЛ1(''0211'',6)')
INSERT #F VALUES (3,1,5,'4ФСС_РАЗДЕЛ1(''0201'',3)')
INSERT #F VALUES (3,2,5,'4ФСС_РАЗДЕЛ1(''0202'',3)')
INSERT #F VALUES (3,3,5,'4ФСС_РАЗДЕЛ1(''0203'',3)')
INSERT #F VALUES (3,4,5,'4ФСС_РАЗДЕЛ1(''0204'',3)')
INSERT #F VALUES (3,5,5,'4ФСС_РАЗДЕЛ1(''0205'',3) ')
INSERT #F VALUES (3,6,5,'4ФСС_РАЗДЕЛ1(''0206'',3)  ')
INSERT #F VALUES (3,8,5,'4ФСС_РАЗДЕЛ1(''0208'',3)')
INSERT #F VALUES (3,9,5,'4ФСС_РАЗДЕЛ1(''0209'',3)')
INSERT #F VALUES (3,10,5,'4ФСС_РАЗДЕЛ1(''0210'',3)')
INSERT #F VALUES (3,11,5,'4ФСС_РАЗДЕЛ1(''0211'',3)')
INSERT #F VALUES (3,5,6,'ЗАПРЕТ()')
INSERT #F VALUES (3,6,6,'ЗАПРЕТ()')
INSERT #F VALUES (4,1,1,'Суммы выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со ст.7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                           ')
INSERT #F VALUES (4,2,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии со ст.9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                                 ')
INSERT #F VALUES (4,3,1,'Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную в соответствии со ст. 8 Федерального закона от 24                                                                                                             ')
INSERT #F VALUES (4,4,1,'Итого база для начисления страховых взносов  (строка 1 - строка 2 - строка 3)                                                                                                                                                                             ')
INSERT #F VALUES (4,5,1,'из них: сумма выплат и иных вознаграждений физическим лицам, являющимся инвалидами I, II, III группы                                                                                                                                                      ')
INSERT #F VALUES (4,6,1,'Cумма выплат и иных вознаграждений, производимых физическим лицам в связи с осуществлением фармацевтической деятельности                                                                                                                                  ')
INSERT #F VALUES (4,7,1,'Cумма выплат и иных вознаграждений членам экипажей судов, зарегистрированных в Российском международном реестре судов, за исполнение трудовых обязанностей члена экипажа судна                                                                            ')
INSERT #F VALUES (4,8,1,'Cумма выплат и иных вознаграждений,производимых физическим лицам индивидуальными предпринимателями, применяющими патентную систему налогообложения                                                                                                        ')
INSERT #F VALUES (4,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (4,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,4,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,5,2,'5                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (4,6,2,'6                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (4,7,2,'7                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (4,8,2,'8                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (4,1,3,'4ФСС_РАЗДЕЛ1(''030103'',3)')
INSERT #F VALUES (4,2,3,'4ФСС_РАЗДЕЛ1(''030203'',3)')
INSERT #F VALUES (4,3,3,'4ФСС_РАЗДЕЛ1(''030303'',3)')
INSERT #F VALUES (4,5,3,'4ФСС_РАЗДЕЛ1(''030503'',3)')
INSERT #F VALUES (4,6,3,'4ФСС_РАЗДЕЛ1(''030603'',3)')
INSERT #F VALUES (4,7,3,'4ФСС_РАЗДЕЛ1(''030703'',3)')
INSERT #F VALUES (4,8,3,'4ФСС_РАЗДЕЛ1(''030803'',3)')
INSERT #F VALUES (4,1,4,'4ФСС_РАЗДЕЛ1(''030104'',3)')
INSERT #F VALUES (4,2,4,'4ФСС_РАЗДЕЛ1(''030204'',3)')
INSERT #F VALUES (4,3,4,'4ФСС_РАЗДЕЛ1(''030304'',3)')
INSERT #F VALUES (4,5,4,'4ФСС_РАЗДЕЛ1(''030504'',3)')
INSERT #F VALUES (4,6,4,'4ФСС_РАЗДЕЛ1(''030604'',3)')
INSERT #F VALUES (4,7,4,'4ФСС_РАЗДЕЛ1(''030704'',3)')
INSERT #F VALUES (4,8,4,'4ФСС_РАЗДЕЛ1(''030804'',3)')
INSERT #F VALUES (4,1,5,'4ФСС_РАЗДЕЛ1(''030105'',3)')
INSERT #F VALUES (4,2,5,'4ФСС_РАЗДЕЛ1(''030205'',3)')
INSERT #F VALUES (4,3,5,'4ФСС_РАЗДЕЛ1(''030305'',3)')
INSERT #F VALUES (4,5,5,'4ФСС_РАЗДЕЛ1(''030505'',3)')
INSERT #F VALUES (4,6,5,'4ФСС_РАЗДЕЛ1(''030605'',3)')
INSERT #F VALUES (4,7,5,'4ФСС_РАЗДЕЛ1(''030705'',3)')
INSERT #F VALUES (4,8,5,'4ФСС_РАЗДЕЛ1(''030805'',3)')
INSERT #F VALUES (4,1,6,'4ФСС_РАЗДЕЛ1(''030106'',3)')
INSERT #F VALUES (4,2,6,'4ФСС_РАЗДЕЛ1(''030206'',3)')
INSERT #F VALUES (4,3,6,'4ФСС_РАЗДЕЛ1(''030306'',3)')
INSERT #F VALUES (4,5,6,'4ФСС_РАЗДЕЛ1(''030506'',3)')
INSERT #F VALUES (4,6,6,'4ФСС_РАЗДЕЛ1(''030606'',3)')
INSERT #F VALUES (4,7,6,'4ФСС_РАЗДЕЛ1(''030706'',3)')
INSERT #F VALUES (4,8,6,'4ФСС_РАЗДЕЛ1(''030806'',3)')
INSERT #F VALUES (6,1,1,'Численность членов организации, всего (чел.)                                                                                                                                                                                                                  ')
INSERT #F VALUES (6,2,1,'     из них: численность инвалидов и их законных представителей (чел.)                                                                                                                                                                                    ')
INSERT #F VALUES (6,3,1,'Удельный вес, % ( стр.2  / стр.1) х 100                                                                                                                                                                                                                   ')
INSERT #F VALUES (6,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (6,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (6,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (7,1,1,'Среднесписочная численность, всего (чел.)                                                                                                                                                                                                                     ')
INSERT #F VALUES (7,2,1,'  из них: среднесписочная численность инвалидов (чел.)                                                                                                                                                                                                        ')
INSERT #F VALUES (7,3,1,'Удельный вес, % (стр. 5 / стр. 4) х 100                                                                                                                                                                                                                       ')
INSERT #F VALUES (7,4,1,'Фонд оплаты труда,
всего (руб.)                                                                                                                                                                                                                              ')
INSERT #F VALUES (7,5,1,'     из него: заработная плата инвалидов (руб.)                                                                                                                                                                                                               ')
INSERT #F VALUES (7,6,1,'Удельный вес заработной платы инвалидов, % (стр. 8 / стр. 7) х 100                                                                                                                                                                                            ')
INSERT #F VALUES (7,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (7,2,2,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (7,3,2,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (7,4,2,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (7,5,2,'5                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (7,6,2,'6                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (8,1,1,' Средняя численность работников/среднесписочная численность работников (чел.)                                                                                                                                                                             ')
INSERT #F VALUES (8,2,1,' Сумма доходов, определяемая в соответствии со статьей 248 Налогового кодекса Российской Федерации, всего (руб.)                                                                                                                                          ')
INSERT #F VALUES (8,3,1,'  из них: сумма доходов, определяемая  исходя из критериев, указанных в пункте 2 части 2.1 или пункте 2 части 2.2 статьи  57 Федерального закона от 24 июля 2009 г. № 212-ФЗ (руб.)                                                                           ')
INSERT #F VALUES (8,4,1,'  доля доходов, определяемая в целях применения  части 5 статьи  58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%)
(стр.3 / стр. 2) х 100                                                                                                               ')
INSERT #F VALUES (8,5,1,'Сведения из реестра аккредитованных организаций, осуществляющих деятельность в области информационных технологий*                                                                                                                                             ')
INSERT #F VALUES (8,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (8,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (8,3,2,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (8,4,2,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (8,5,2,'5                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (8,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (8,1,5,'ЗАПРЕТ()')
INSERT #F VALUES (8,2,5,'ЗАПРЕТ()')
INSERT #F VALUES (8,3,5,'ЗАПРЕТ()')
INSERT #F VALUES (8,4,5,'ЗАПРЕТ()')
INSERT #F VALUES (8,1,6,'ЗАПРЕТ()')
INSERT #F VALUES (8,2,6,'ЗАПРЕТ()')
INSERT #F VALUES (8,3,6,'ЗАПРЕТ()')
INSERT #F VALUES (8,4,6,'ЗАПРЕТ()')
INSERT #F VALUES (9,1,1,'Сумма доходов, определяемая в соответствии со статьей 346.15 Налогового кодекса Российской Федерации, всего (руб.)                                                                                                                                            ')
INSERT #F VALUES (9,2,1,'  из них: сумма доходов, определяемая в целях применения части 1.4 статьи 58 Федерального закона от 24 июля 2009 г.                                       № 212-ФЗ (руб.)                                                                                     ')
INSERT #F VALUES (9,3,1,'Доля доходов, определяемая в целях применения части 1.4 статьи 58 Федерального закона от 24 июля 2009 г.                                                              № 212-ФЗ (%)
(стр. 2 / стр. 1) х 100                                                   ')
INSERT #F VALUES (9,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (9,2,2,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (9,3,2,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,1,1,'Сумма доходов*, всего (руб.)                                                                                                                                                                                                                                  ')
INSERT #F VALUES (10,2,1,'из них: сумма доходов в виде целевых поступлений на содержание некоммерческих организаций и ведение ими уставной деятельности, поименованной в пункте 11 части 1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                    ')
INSERT #F VALUES (10,3,1,'сумма доходов в виде грантов, получаемых для осуществления деятельности, поименованной в пункте 11 части 1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                          ')
INSERT #F VALUES (10,4,1,'сумма доходов от осуществления видов экономической деятельности, указанных в подпунктах р - ф, я.4 - я.6 пункта 8 части 1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (руб.)                                                                    ')
INSERT #F VALUES (10,5,1,'Доля доходов, определяемая в целях применения части 5.1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%)
((с. 2 + с. 3 + с.4) / с. 1) х 100                                                                                                     ')
INSERT #F VALUES (10,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,2,2,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,3,2,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,4,2,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,5,2,'5                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,1,1,'Пособие по временной нетрудоспособности                                                                                                                                                                                                                   ')
INSERT #F VALUES (12,2,1,'Пособие по беременности и родам                                                                                                                                                                                                                           ')
INSERT #F VALUES (12,3,1,'Ежемесячное пособие по уходу за ребенком, всего (стр. 4, 5)                                                                                                                                                                                               ')
INSERT #F VALUES (12,4,1,'в том числе: по уходу за первым ребенком                                                                                                                                                                                                                      ')
INSERT #F VALUES (12,5,1,'по уходу за вторым и 
последующими детьми                                                                                                                                                                                                                ')
INSERT #F VALUES (12,6,1,'Социальное пособие на погребение или возмещение стоимости гарантированного перечня услуг по погребению                                                                                                                                                    ')
INSERT #F VALUES (12,7,1,'ВСЕГО (строки 1 - 3, 6)                                                                                                                                                                                                                                   ')
INSERT #F VALUES (12,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (12,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (12,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (12,4,2,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,5,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (12,6,2,'6                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (12,7,2,'7                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (12,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (12,7,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,7,10,'ЗАПРЕТ()')
INSERT #F VALUES (12,2,12,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,12,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,12,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,12,'ЗАПРЕТ()')
INSERT #F VALUES (12,6,12,'ЗАПРЕТ()')
INSERT #F VALUES (12,2,13,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,13,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,13,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,13,'ЗАПРЕТ()')
INSERT #F VALUES (12,6,13,'ЗАПРЕТ()')
INSERT #F VALUES (12,7,13,'ЗАПРЕТ()')
INSERT #F VALUES (12,2,14,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,14,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,14,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,14,'ЗАПРЕТ()')
INSERT #F VALUES (12,6,14,'ЗАПРЕТ()')
INSERT #F VALUES (12,7,16,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,18,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,18,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,18,'ЗАПРЕТ()')
INSERT #F VALUES (12,6,18,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,19,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,19,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,19,'ЗАПРЕТ()')
INSERT #F VALUES (12,6,19,'ЗАПРЕТ()')
INSERT #F VALUES (12,7,19,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,20,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,20,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,20,'ЗАПРЕТ()')
INSERT #F VALUES (12,6,20,'ЗАПРЕТ()')
INSERT #F VALUES (13,1,1,'Всего с начала расчетного  периода                                                                                                                                                                                                                        ')
INSERT #F VALUES (13,2,1,'    В том числе за последние три месяца отчетного периода                                                                                                                                                                                                 ')
INSERT #F VALUES (13,3,1,'       В том числе за 1 месяц                                                                                                                                                                                                                             ')
INSERT #F VALUES (13,4,1,'       В том числе за 2 месяц                                                                                                                                                                                                                             ')
INSERT #F VALUES (13,5,1,'       В том числе за 3 месяц                                                                                                                                                                                                                             ')
INSERT #F VALUES (13,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,4,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,5,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,1,3,'4ФСС_РАЗДЕЛ1(''060103'',3)')
INSERT #F VALUES (13,3,3,'4ФСС_РАЗДЕЛ1(''060303'',3)')
INSERT #F VALUES (13,4,3,'4ФСС_РАЗДЕЛ1(''060403'',3)')
INSERT #F VALUES (13,5,3,'4ФСС_РАЗДЕЛ1(''060503'',3)')
INSERT #F VALUES (13,1,4,'4ФСС_РАЗДЕЛ1(''060104'',3)')
INSERT #F VALUES (13,3,4,'4ФСС_РАЗДЕЛ1(''060304'',3)')
INSERT #F VALUES (13,4,4,'4ФСС_РАЗДЕЛ1(''060404'',3)')
INSERT #F VALUES (13,5,4,'4ФСС_РАЗДЕЛ1(''060504'',3)')
INSERT #F VALUES (13,1,5,'4ФСС_РАЗДЕЛ1(''060105'',3)')
INSERT #F VALUES (13,3,5,'4ФСС_РАЗДЕЛ1(''060305'',3)')
INSERT #F VALUES (13,4,5,'4ФСС_РАЗДЕЛ1(''060405'',3)')
INSERT #F VALUES (13,5,5,'4ФСС_РАЗДЕЛ1(''060505'',3)')
INSERT #F VALUES (13,1,6,'4ФСС_СПРАВОЧНИК(''tax_rate'')')
INSERT #F VALUES (13,2,6,'ЗАПРЕТ()')
INSERT #F VALUES (13,3,6,'ЗАПРЕТ()')
INSERT #F VALUES (13,4,6,'ЗАПРЕТ()')
INSERT #F VALUES (13,5,6,'ЗАПРЕТ()')
INSERT #F VALUES (13,1,7,'4ФСС_СПРАВОЧНИК(''discount'')')
INSERT #F VALUES (13,2,7,'ЗАПРЕТ()')
INSERT #F VALUES (13,3,7,'ЗАПРЕТ()')
INSERT #F VALUES (13,4,7,'ЗАПРЕТ()')
INSERT #F VALUES (13,5,7,'ЗАПРЕТ()')
INSERT #F VALUES (13,1,8,'4ФСС_СПРАВОЧНИК(''raise_date'')')
INSERT #F VALUES (13,2,8,'ЗАПРЕТ()')
INSERT #F VALUES (13,3,8,'ЗАПРЕТ()')
INSERT #F VALUES (13,4,8,'ЗАПРЕТ()')
INSERT #F VALUES (13,5,8,'ЗАПРЕТ()')
INSERT #F VALUES (13,1,9,'4ФСС_СПРАВОЧНИК(''raise_val'')')
INSERT #F VALUES (13,2,9,'ЗАПРЕТ()')
INSERT #F VALUES (13,3,9,'ЗАПРЕТ()')
INSERT #F VALUES (13,4,9,'ЗАПРЕТ()')
INSERT #F VALUES (13,5,9,'ЗАПРЕТ()')
INSERT #F VALUES (13,1,10,'4ФСС_СПРАВОЧНИК(''tax_total'')')
INSERT #F VALUES (13,2,10,'ЗАПРЕТ()')
INSERT #F VALUES (13,3,10,'ЗАПРЕТ()')
INSERT #F VALUES (13,4,10,'ЗАПРЕТ()')
INSERT #F VALUES (13,5,10,'ЗАПРЕТ()')
INSERT #F VALUES (14,1,1,'Задолженность за страхователем на начало расчетного периода                                                                                                                                                                                               ')
INSERT #F VALUES (14,2,1,'Начислено страховых взносов                                                                                                                                                                                                                               ')
INSERT #F VALUES (14,3,1,'на начало отчетного периода                                                                                                                                                                                                                               ')
INSERT #F VALUES (14,4,1,'за последние три месяца отчетного периода                                                                                                                                                                                                                 ')
INSERT #F VALUES (14,5,1,'          1 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,6,1,'          2 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,7,1,'          3 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,8,1,'Начислено взносов по результатам проверок                                                                                                                                                                                                                 ')
INSERT #F VALUES (14,9,1,'Не принято к зачету расходов территориальным органом Фонда за прошлые расчетные периоды                                                                                                                                                                   ')
INSERT #F VALUES (14,10,1,'Начислено взносов страхователем за прошлые расчетные периоды                                                                                                                                                                                              ')
INSERT #F VALUES (14,11,1,'Получено от территориального органа Фонда на банковский счет                                                                                                                                                                                              ')
INSERT #F VALUES (14,12,1,'Возврат сумм излишне уплаченных (взысканных) страховых взносов                                                                                                                                                                                            ')
INSERT #F VALUES (14,13,1,'Всего  (сумма строк 1+2+3+4+5+6+7)                                                                                                                                                                                                                        ')
INSERT #F VALUES (14,14,1,'Задолженность за территориальным органом Фонда на конец отчетного периода                                                                                                                                                                                 ')
INSERT #F VALUES (14,15,1,'Задолженность за территориальным органом Фонда на начало расчетного периода                                                                                                                                                                               ')
INSERT #F VALUES (14,16,1,'Расходы по обязательному социальному страхованию                                                                                                                                                                                                          ')
INSERT #F VALUES (14,17,1,'на начало отчетного периода                                                                                                                                                                                                                               ')
INSERT #F VALUES (14,18,1,'за последние три месяца отчетного периода                                                                                                                                                                                                                 ')
INSERT #F VALUES (14,19,1,'          1 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,20,1,'          2 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,21,1,'          3 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,22,1,'Уплачено страховых взносов                                                                                                                                                                                                                                ')
INSERT #F VALUES (14,23,1,'на начало отчетного периода                                                                                                                                                                                                                               ')
INSERT #F VALUES (14,24,1,'за последние три месяца отчетного периода дата, № платежного  поручения                                                                                                                                                                                   ')
INSERT #F VALUES (14,25,1,'          1 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,26,1,'          2 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,27,1,'          3 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,28,1,'Списанная сумма задолженности страхователя                                                                                                                                                                                                                ')
INSERT #F VALUES (14,29,1,'Всего (сумма строк 10+11+12+13                                                                                                                                                                                                                            ')
INSERT #F VALUES (14,30,1,'Задолженность за страхователем на конец отчетного периода                                                                                                                                                                                                 ')
INSERT #F VALUES (14,31,1,'           в том числе недоимка                                                                                                                                                                                                                           ')
INSERT #F VALUES (14,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,3,2,'2_1                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (14,4,2,'2_2                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (14,5,2,'2_3                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (14,6,2,'2_4                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (14,7,2,'2_5                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (14,8,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,9,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,10,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,11,2,'6                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,12,2,'7                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,13,2,'8                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,14,2,'9                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,15,2,'10                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (14,16,2,'11                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (14,17,2,'11_1                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (14,18,2,'11_2                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (14,19,2,'11_3                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (14,20,2,'11_4                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (14,21,2,'11_5                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (14,22,2,'12                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (14,23,2,'12_1                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (14,24,2,'12_2                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (14,25,2,'12_3                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (14,26,2,'12_4                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (14,27,2,'12_5                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (14,28,2,'13                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (14,29,2,'14                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (14,30,2,'15                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (14,31,2,'16                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (14,1,3,'КТСН("_.303.06","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (14,3,3,'4ФСС_РАЗДЕЛ1(''1021'',3)')
INSERT #F VALUES (14,5,3,'4ФСС_РАЗДЕЛ1(''1023'',3)')
INSERT #F VALUES (14,6,3,'4ФСС_РАЗДЕЛ1(''1024'',3)')
INSERT #F VALUES (14,7,3,'4ФСС_РАЗДЕЛ1(''1025'',3)')
INSERT #F VALUES (14,11,3,'АДТКТ("_.304.05:_.201.11:_.201.21:_.201.27","_.303.06")')
INSERT #F VALUES (14,17,3,'АДТКТ("_.303.06","_.302.13,"ДЛЯ ДАТА>=''01.01'' И ДАТА<КВАРТАЛ")')
INSERT #F VALUES (14,19,3,'АДТКТ("_.303.06","_.302.13,"ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (14,20,3,'АДТКТ("_.303.06","_.302.13","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (14,21,3,'АДТКТ("_.303.06","_.302.13","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (14,23,3,'АДТКТ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА>=''01.01'' И ДАТА<КВАРТАЛ")')
INSERT #F VALUES (14,25,3,'АДТКТ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (14,26,3,'АДТКТ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (14,27,3,'АДТКТ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (14,30,3,'КТСК("_.303.06")')
INSERT #F VALUES (14,1,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,2,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,3,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,4,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,6,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,8,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,9,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,10,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,11,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,12,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,13,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,14,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,15,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,16,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,17,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,18,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,19,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,20,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,21,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,22,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,23,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,24,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,25,4,'НОМ_ПЛАТЕЖ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (14,26,4,'НОМ_ПЛАТЕЖ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (14,27,4,'НОМ_ПЛАТЕЖ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (14,28,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,29,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,30,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,31,4,'ЗАПРЕТ()')
INSERT #F VALUES (15,1,1,'Пособия по временной нетрудоспособности в связи
с несчастными случаями на производстве, всего                                                                                                                                                            ')
INSERT #F VALUES (15,2,1,'      из них: по внешнему совместительству                                                                                                                                                                                                                ')
INSERT #F VALUES (15,3,1,'      пострадавшим в другой организации                                                                                                                                                                                                                       ')
INSERT #F VALUES (15,4,1,'Пособия по временной нетрудоспособности в связи
с профессиональными заболеваниями, всего                                                                                                                                                                 ')
INSERT #F VALUES (15,5,1,'      из них: по внешнему совместительству                                                                                                                                                                                                                ')
INSERT #F VALUES (15,6,1,'      пострадавшим в другой организации                                                                                                                                                                                                                       ')
INSERT #F VALUES (15,7,1,'Оплата отпуска для санаторно-курортного лечения застрахованным (сверх ежегодного оплачиваемого отпуска, установленного законодательством Российской Федерации)                                                                                            ')
INSERT #F VALUES (15,8,1,'      из них: пострадавшим в другой организации                                                                                                                                                                                                               ')
INSERT #F VALUES (15,9,1,'Финансирование предупредительных мер по сокращению производственного травматизма и профзаболеваний                                                                                                                                                        ')
INSERT #F VALUES (15,10,1,'Всего расходов (сумма строк 1, 4, 7, 9)                                                                                                                                                                                                                   ')
INSERT #F VALUES (15,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (15,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (15,3,2,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (15,4,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (15,5,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (15,6,2,'6                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (15,7,2,'7                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (15,8,2,'8                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (15,9,2,'9                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (15,10,2,'10                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (15,1,3,'4ФСС_РАЗДЕЛ1(''1101'',6)')
INSERT #F VALUES (15,2,3,'4ФСС_РАЗДЕЛ1(''1102'',6)')
INSERT #F VALUES (15,4,3,'4ФСС_РАЗДЕЛ1(''1104'',6)')
INSERT #F VALUES (15,5,3,'4ФСС_РАЗДЕЛ1(''1105'',6)')
INSERT #F VALUES (15,7,3,'4ФСС_РАЗДЕЛ1(''1107'',6)')
INSERT #F VALUES (15,9,3,'ЗАПРЕТ()')
INSERT #F VALUES (15,10,3,'ЗАПРЕТ()')
INSERT #F VALUES (15,1,4,'4ФСС_РАЗДЕЛ1(''1101'',3)')
INSERT #F VALUES (15,2,4,'4ФСС_РАЗДЕЛ1(''1102'',3)')
INSERT #F VALUES (15,4,4,'4ФСС_РАЗДЕЛ1(''1104'',3)')
INSERT #F VALUES (15,5,4,'4ФСС_РАЗДЕЛ1(''1105'',3)')
INSERT #F VALUES (15,7,4,'4ФСС_РАЗДЕЛ1(''1107'',3)')
INSERT #F VALUES (16,1,1,'По несчастным случаям                                                                                                                                                                                                                                     ')
INSERT #F VALUES (16,2,1,'      из них: со смертельным исходом                                                                                                                                                                                                                      ')
INSERT #F VALUES (16,3,1,'По профессиональным заболеваниям                                                                                                                                                                                                                          ')
INSERT #F VALUES (16,4,1,'ВСЕГО пострадавших (сумма строк 1, 3)                                                                                                                                                                                                                     ')
INSERT #F VALUES (16,5,1,'в том числе пострадавших (застрахованных) по случаям, закончившимся только временной нетрудоспособностью                                                                                                                                                  ')
INSERT #F VALUES (16,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (16,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (16,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (16,4,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (16,5,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (17,1,1,'Аттестация рабочих мест по условиям труда                                                                                                                                                                                                                     ')
INSERT #F VALUES (17,2,1,'Проведение обязательных предварительных и периодических медицинских осмотров (обследований) работников                                                                                                                                                        ')
INSERT #F VALUES (17,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (17,2,2,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (17,1,3,'4ФСС_РАЗДЕЛ1(''100103'',3)')
INSERT #F VALUES (17,2,3,'ЗАПРЕТ()')
INSERT #F VALUES (17,1,4,'4ФСС_РАЗДЕЛ1(''100104'',3)')
INSERT #F VALUES (17,2,4,'ЗАПРЕТ()')
INSERT #F VALUES (17,1,6,'4ФСС_РАЗДЕЛ1(''100105'',3)')
INSERT #F VALUES (17,2,6,'ЗАПРЕТ()')
INSERT #F VALUES (17,1,7,'4ФСС_РАЗДЕЛ1(''100106'',3)')
INSERT #F VALUES (17,2,7,'ЗАПРЕТ()')
INSERT #F VALUES (17,1,8,'ЗАПРЕТ()')
INSERT #F VALUES (17,1,9,'ЗАПРЕТ()')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 599
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,7,0,0,0,'т.2стр.2_2гр.3 =  т.2стр.2_3гр.3 +  т.2стр.2_4гр.3 +  т.2стр.2_5гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(2,NULL,0,NULL,2,7,0,0,0,'т.2стр.3_2гр.3 =  т.2стр.3_3гр.3 +  т.2стр.3_4гр.3 +  т.2стр.3_5гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(3,NULL,0,NULL,3,7,0,0,0,'т.2стр.5_2гр.3 =  т.2стр.5_3гр.3 +  т.2стр.5_4гр.3 +  т.2стр.5_5гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(4,NULL,0,NULL,4,7,0,0,0,'т.2стр.6_2гр.3 =  т.2стр.6_3гр.3 +  т.2стр.6_4гр.3 +  т.2стр.6_5гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(5,NULL,0,NULL,5,7,0,0,0,'т.2стр.15_2гр.3 =  т.2стр.15_3гр.3 +  т.2стр.15_4гр.3 +  т.2стр.15_5гр.3',1,0,1,'20140409','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(6,NULL,0,NULL,6,7,0,0,0,'т.2стр.16_2гр.3 =  т.2стр.16_3гр.3 +  т.2стр.16_4гр.3 +  т.2стр.16_5гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(7,NULL,0,NULL,7,7,0,0,0,'т.2стр.15гр.3 =  т.3стр.12гр.4',0,0,1,'20140409','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(8,NULL,0,NULL,8,7,0,0,0,'т.4стр.4гр.3 =  т.4стр.1гр.3 -  т.4стр.2гр.3 -  т.4стр.3гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(9,NULL,0,NULL,9,7,0,0,0,'т.4стр.4гр.4 =  т.4стр.1гр.4 -  т.4стр.2гр.4 -  т.4стр.3гр.4',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(10,NULL,0,NULL,10,7,0,0,0,'т.4стр.4гр.5 =  т.4стр.1гр.5 -  т.4стр.2гр.5 -  т.4стр.3гр.5',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(11,NULL,0,NULL,11,7,0,0,0,'т.4стр.4гр.6 =  т.4стр.1гр.6 -  т.4стр.2гр.6 -  т.4стр.3гр.6',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(12,NULL,0,NULL,12,7,0,0,0,'т.6стр.1гр.3 =  т.6стр.1гр.6',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(13,NULL,0,NULL,13,7,0,0,0,'т.6стр.2гр.3 =  т.6стр.2гр.6',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(14,NULL,0,NULL,14,7,0,0,0,'т.6стр.3гр.3 =  т.6стр.2гр.3 /  т.6стр.1гр.3 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(15,NULL,0,NULL,15,7,0,0,0,'т.6стр.3гр.4 =  т.6стр.2гр.4 /  т.6стр.1гр.4 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(16,NULL,0,NULL,16,7,0,0,0,'т.6стр.3гр.5 =  т.6стр.2гр.5 /  т.6стр.1гр.5 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(17,NULL,0,NULL,17,7,0,0,0,'т.6стр.3гр.6 =  т.6стр.2гр.6 /  т.6стр.1гр.6 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(18,NULL,0,NULL,18,7,0,0,0,'т.7стр.1гр.3 =  т.7стр.1гр.6',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(19,NULL,0,NULL,19,7,0,0,0,'т.7стр.2гр.3 =  т.7стр.2гр.6',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(20,NULL,0,NULL,20,7,0,0,0,'т.7стр.3гр.3 =  т.7стр.2гр.3 /  т.7стр.1гр.3 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(21,NULL,0,NULL,21,7,0,0,0,'т.7стр.3гр.4 =  т.7стр.2гр.4 /  т.7стр.1гр.4 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(22,NULL,0,NULL,22,7,0,0,0,'т.7стр.3гр.5 =  т.7стр.2гр.5 /  т.7стр.1гр.5 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(23,NULL,0,NULL,23,7,0,0,0,'т.7стр.3гр.6 =  т.7стр.2гр.6 /  т.7стр.1гр.6 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(24,NULL,0,NULL,24,7,0,0,0,'т.7стр.6гр.3 =  т.7стр.5гр.3 /  т.7стр.4гр.3 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(25,NULL,0,NULL,25,7,0,0,0,'т.7стр.6гр.4 =  т.7стр.5гр.4 /  т.7стр.4гр.4 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(26,NULL,0,NULL,26,7,0,0,0,'т.7стр.6гр.5 =  т.7стр.5гр.5 /  т.7стр.4гр.5 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(27,NULL,0,NULL,27,7,0,0,0,'т.7стр.6гр.6 =  т.7стр.5гр.6 /  т.7стр.4гр.6 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(28,NULL,0,NULL,28,7,0,0,0,'т.8стр.4гр.3 =  т.8стр.3гр.3 /  т.8стр.2гр.3 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(29,NULL,0,NULL,29,7,0,0,0,'т.12стр.1гр.5 =  т.3стр.1гр.5',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(30,NULL,0,NULL,30,7,0,0,0,'т.12стр.2гр.5 =  т.3стр.3гр.5',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(31,NULL,0,NULL,31,7,0,0,0,'т.12стр.4гр.5 =  т.3стр.8гр.5',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(32,NULL,0,NULL,32,7,0,0,0,'т.12стр.5гр.5 =  т.3стр.9гр.5',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(33,NULL,0,NULL,33,7,0,0,0,'т.12стр.6гр.5 =  т.3стр.11гр.5',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(34,NULL,0,NULL,34,7,0,0,0,'т.13стр.2гр.3 =  т.13стр.3гр.3 +  т.13стр.4гр.3 +  т.13стр.5гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(35,NULL,0,NULL,35,7,0,0,0,'т.13стр.2гр.4 =  т.13стр.3гр.4 +  т.13стр.4гр.4 +  т.13стр.5гр.4',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(36,NULL,0,NULL,36,7,0,0,0,'т.13стр.2гр.5 =  т.13стр.3гр.5 +  т.13стр.4гр.5 +  т.13стр.5гр.5',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(37,NULL,0,NULL,37,7,0,0,0,'т.14стр.2_2гр.3 =  т.14стр.2_3гр.3 +  т.14стр.2_4гр.3 +  т.14стр.2_5гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(38,NULL,0,NULL,38,7,0,0,0,'т.14стр.11_2гр.3 =  т.14стр.11_3гр.3 +  т.14стр.11_4гр.3 +  т.14стр.11_5гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(39,NULL,0,NULL,39,7,0,0,0,'т.14стр.12_2гр.3 =  т.14стр.12_3гр.3 +  т.14стр.12_4гр.3 +  т.14стр.12_5гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(40,NULL,0,NULL,40,7,0,0,0,'т.15стр.10гр.4 =  т.15стр.1гр.4 +  т.15стр.4гр.4 +  т.15стр.7гр.4 +  т.15стр.9гр.4',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(41,NULL,0,NULL,41,7,0,0,0,'т.16стр.4гр.3 =  т.16стр.1гр.3 +  т.16стр.3гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(42,NULL,0,NULL,42,7,0,0,0,'т.13гр.3 =  -  т.13гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(43,NULL,0,NULL,43,7,0,0,0,'т.13гр.3 =  -  т.13гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(44,NULL,0,NULL,44,7,0,0,0,'т.3стр.7гр.2 =  т.3стр.8гр.2 +  т.3стр.9гр.2',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(45,NULL,0,NULL,45,7,0,0,0,'т.3стр.7гр.3 =  т.3стр.8гр.3 +  т.3стр.9гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(46,NULL,0,NULL,46,7,0,0,0,'т.3стр.7гр.4 =  т.3стр.8гр.4 +  т.3стр.9гр.4',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(47,NULL,0,NULL,47,7,0,0,0,'т.3стр.7гр.5 =  т.3стр.8гр.5 +  т.3стр.9гр.5',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(48,NULL,0,NULL,48,7,0,0,0,'т.1стр.2гр.3 <=  т.1стр.1гр.3',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(49,NULL,0,NULL,49,7,0,0,0,'т.1стр.3гр.3 <=  т.1стр.1гр.3',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(50,NULL,0,NULL,50,7,0,0,0,'т.1стр.4гр.3 <=  т.1стр.1гр.3',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(51,NULL,0,NULL,51,7,0,0,0,'т.3стр.2гр.2 <=  т.3стр.1гр.2',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(52,NULL,0,NULL,52,7,0,0,0,'т.3стр.2гр.3 <=  т.3стр.1гр.3',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(53,NULL,0,NULL,53,7,0,0,0,'т.3стр.2гр.4 <=  т.3стр.1гр.4',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(54,NULL,0,NULL,54,7,0,0,0,'т.3стр.2гр.5 <=  т.3стр.1гр.5',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(55,NULL,0,NULL,55,7,0,0,0,'т.3стр.4гр.3 <=  т.3стр.3гр.3',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(56,NULL,0,NULL,56,7,0,0,0,'т.3стр.4гр.4 <=  т.3стр.3гр.4',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(57,NULL,0,NULL,57,7,0,0,0,'т.3стр.4гр.5 <=  т.3стр.3гр.5',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(58,NULL,0,NULL,58,7,0,0,0,'т.4стр.1гр.3 >=  т.4стр.1гр.4 +  т.4стр.1гр.5 +  т.4стр.1гр.6',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(59,NULL,0,NULL,59,7,0,0,0,'т.4стр.2гр.3 >=  т.4стр.2гр.4 +  т.4стр.2гр.5 +  т.4стр.2гр.6',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(60,NULL,0,NULL,60,7,0,0,0,'т.4стр.3гр.3 >=  т.4стр.3гр.4 +  т.4стр.3гр.5 +  т.4стр.3гр.6',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(61,NULL,0,NULL,61,7,0,0,0,'т.4стр.4гр.3 >=  т.4стр.4гр.4 +  т.4стр.4гр.5 +  т.4стр.4гр.6',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(62,NULL,0,NULL,62,7,0,0,0,'т.4стр.5гр.3 >=  т.4стр.5гр.4 +  т.4стр.5гр.5 +  т.4стр.5гр.6',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(63,NULL,0,NULL,63,7,0,0,0,'т.4стр.5гр.3 <=  т.4стр.4гр.3',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(64,NULL,0,NULL,64,7,0,0,0,'т.4стр.5гр.4 <=  т.4стр.4гр.4',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(65,NULL,0,NULL,65,7,0,0,0,'т.4стр.5гр.5 <=  т.4стр.4гр.5',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(66,NULL,0,NULL,66,7,0,0,0,'т.4стр.5гр.6 <=  т.4стр.4гр.6',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(67,NULL,0,NULL,67,7,0,0,0,'т.13стр.1гр.4 <=  т.13стр.1гр.3',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(68,NULL,0,NULL,68,7,0,0,0,'т.14стр.16гр.3 <=  т.14стр.15гр.3',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(69,NULL,0,NULL,69,7,0,0,0,'т.14стр.11гр.3 =  т.15стр.10гр.4',0,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(70,NULL,0,NULL,70,7,0,0,0,'т.15стр.1гр.3 >=  т.15стр.2гр.3 +  т.15стр.3гр.3',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(71,NULL,0,NULL,71,7,0,0,0,'т.15стр.1гр.4 >=  т.15стр.2гр.4 +  т.15стр.3гр.4',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(72,NULL,0,NULL,72,7,0,0,0,'т.15стр.4гр.3 >=  т.15стр.5гр.3 +  т.15стр.6гр.3',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(73,NULL,0,NULL,73,7,0,0,0,'т.15стр.4гр.4 >=  т.15стр.5гр.4 +  т.15стр.6гр.4',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(74,NULL,0,NULL,74,7,0,0,0,'т.15стр.7гр.3 >=  т.15стр.8гр.3',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(75,NULL,0,NULL,75,7,0,0,0,'т.15стр.7гр.4 >=  т.15стр.8гр.4',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(76,NULL,0,NULL,76,7,0,0,0,'т.8стр.4гр.4 =  т.8стр.3гр.4 /  т.8стр.2гр.4 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(77,NULL,0,NULL,77,7,0,0,0,'т.9стр.3гр.3 =  т.9стр.2гр.3 /  т.9стр.1гр.3 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(78,NULL,0,NULL,78,7,0,0,0,'т.10стр.5гр.3 =  т.10стр.4гр.3 +  т.10стр.3гр.3 +  т.10стр.2гр.3 /  т.10стр.1гр.3 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(79,NULL,0,NULL,79,7,0,0,0,'т.10стр.5гр.4 =  т.10стр.4гр.4 +  т.10стр.3гр.4 +  т.10стр.2гр.4 /  т.10стр.1гр.4 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(80,NULL,0,NULL,80,7,0,0,0,'т.3стр.12гр.4 =  т.3стр.1гр.4 +  т.3стр.3гр.4 +  т.3стр.5гр.4 +  т.3стр.6гр.4 +  т.3стр.7гр.4 +  т.3стр.10гр.4 +  т.3стр.11гр.4',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(81,NULL,0,NULL,81,7,0,0,0,'т.3стр.12гр.5 =  т.3стр.1гр.5 +  т.3стр.3гр.5 +  т.3стр.5гр.5 +  т.3стр.6гр.5 +  т.3стр.7гр.5 +  т.3стр.10гр.5 +  т.3стр.11гр.5',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(82,NULL,0,NULL,82,7,0,0,0,'т.12стр.3гр.5 =  т.12стр.4гр.5 +  т.12стр.5гр.5',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(83,NULL,0,NULL,83,7,0,0,0,'т.14стр.2гр.3 =  т.14стр.2_1гр.3 +  т.14стр.2_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(84,NULL,0,NULL,84,7,0,0,0,'т.14стр.11гр.3 =  т.14стр.11_1гр.3 +  т.14стр.11_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(85,NULL,0,NULL,85,7,0,0,0,'т.14стр.12гр.3 =  т.14стр.12_1гр.3 +  т.14стр.12_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(86,NULL,0,NULL,86,7,0,0,0,'т.14гр.3 =  т.14гр.3 -  т.14гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(87,NULL,0,NULL,87,7,0,0,0,'т.14гр.3 =  т.14гр.3 -  т.14гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(88,NULL,0,NULL,88,7,0,0,0,'т.2стр.2гр.3 =  т.2стр.2_1гр.3 +  т.2стр.2_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(89,NULL,0,NULL,89,7,0,0,0,'т.2стр.3гр.3 =  т.2стр.3_1гр.3 +  т.2стр.3_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(90,NULL,0,NULL,90,7,0,0,0,'т.2стр.5гр.3 =  т.2стр.5_1гр.3 +  т.2стр.5_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(91,NULL,0,NULL,91,7,0,0,0,'т.2стр.6гр.3 =  т.2стр.6_1гр.3 +  т.2стр.6_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(92,NULL,0,NULL,92,7,0,0,0,'т.2стр.15гр.3 =  т.2стр.15_1гр.3 +  т.2стр.15_2гр.3',1,1,1,'20140409','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(93,NULL,0,NULL,93,7,0,0,0,'т.2стр.16гр.3 =  т.2стр.16_1гр.3 +  т.2стр.16_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(94,NULL,0,NULL,95,7,0,0,0,'т.3стр.12гр.4 =  т.3стр.1гр.4 +  т.3стр.3гр.4 +  т.3стр.5гр.4 +  т.3стр.6гр.4 +  т.3стр.7гр.4 +  т.3стр.10гр.4 +  т.3стр.11гр.4',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(95,NULL,0,NULL,96,7,0,0,0,'т.3стр.12гр.5 =  т.3стр.1гр.5 +  т.3стр.3гр.5 +  т.3стр.5гр.5 +  т.3стр.6гр.5 +  т.3стр.7гр.5 +  т.3стр.10гр.5 +  т.3стр.11гр.5',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(96,NULL,0,NULL,97,7,0,0,0,'т.12стр.3гр.5 =  т.12стр.4гр.5 +  т.12стр.5гр.5',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(97,NULL,0,NULL,98,7,0,0,0,'т.14стр.2гр.3 =  т.14стр.2_1гр.3 +  т.14стр.2_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(98,NULL,0,NULL,99,7,0,0,0,'т.14стр.11гр.3 =  т.14стр.11_1гр.3 +  т.14стр.11_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(99,NULL,0,NULL,100,7,0,0,0,'т.14стр.12гр.3 =  т.14стр.12_1гр.3 +  т.14стр.12_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(100,NULL,0,NULL,101,7,0,0,0,'т.14гр.3 =  т.14гр.3 -  т.14гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(101,NULL,0,NULL,102,7,0,0,0,'т.14гр.3 =  т.14гр.3 -  т.14гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(102,NULL,0,NULL,103,7,0,0,0,'т.2стр.8гр.3 =  т.2стр.1гр.3 +  т.2стр.2гр.3 +  т.2стр.3гр.3 +  т.2стр.4гр.3 +  т.2стр.5гр.3 +  т.2стр.6гр.3 +  т.2стр.7гр.3',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(103,NULL,0,NULL,104,7,0,0,0,'т.2стр.18гр.3 =  т.2стр.12гр.3 +  т.2стр.15гр.3 +  т.2стр.16гр.3 +  т.2стр.17гр.3',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(104,NULL,0,NULL,105,7,0,0,0,'т.12стр.7гр.3 =  т.12стр.1гр.3 +  т.12стр.2гр.3 +  т.12стр.3гр.3 +  т.12стр.6гр.3',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(105,NULL,0,NULL,106,7,0,0,0,'т.12стр.7гр.5 =  т.12стр.1гр.5 +  т.12стр.2гр.5 +  т.12стр.3гр.5 +  т.12стр.6гр.5',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(106,NULL,0,NULL,107,7,0,0,0,'т.12стр.7гр.6 =  т.12стр.1гр.6 +  т.12стр.2гр.6 +  т.12стр.3гр.6 +  т.12стр.6гр.6',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(107,NULL,0,NULL,108,7,0,0,0,'т.12стр.7гр.8 =  т.12стр.1гр.8 +  т.12стр.2гр.8 +  т.12стр.3гр.8 +  т.12стр.6гр.8',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(108,NULL,0,NULL,109,7,0,0,0,'т.12стр.7гр.9 =  т.12стр.1гр.9 +  т.12стр.2гр.9 +  т.12стр.3гр.9 +  т.12стр.6гр.9',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(109,NULL,0,NULL,110,7,0,0,0,'т.12стр.7гр.11 =  т.12стр.1гр.11 +  т.12стр.2гр.11 +  т.12стр.3гр.11 +  т.12стр.6гр.11',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(110,NULL,0,NULL,111,7,0,0,0,'т.12стр.7гр.12 =  т.12стр.1гр.12 +  т.12стр.2гр.12 +  т.12стр.3гр.12 +  т.12стр.6гр.12',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(111,NULL,0,NULL,112,7,0,0,0,'т.12стр.7гр.14 =  т.12стр.1гр.14 +  т.12стр.2гр.14 +  т.12стр.3гр.14 +  т.12стр.6гр.14',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(112,NULL,0,NULL,113,7,0,0,0,'т.12стр.7гр.15 =  т.12стр.1гр.15 +  т.12стр.2гр.15 +  т.12стр.3гр.15 +  т.12стр.6гр.15',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(113,NULL,0,NULL,114,7,0,0,0,'т.12стр.7гр.17 =  т.12стр.1гр.17 +  т.12стр.2гр.17 +  т.12стр.3гр.17 +  т.12стр.6гр.17',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(114,NULL,0,NULL,115,7,0,0,0,'т.12стр.7гр.18 =  т.12стр.1гр.18 +  т.12стр.2гр.18 +  т.12стр.3гр.18 +  т.12стр.6гр.18',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(115,NULL,0,NULL,116,7,0,0,0,'т.12стр.7гр.20 =  т.12стр.1гр.20 +  т.12стр.2гр.20 +  т.12стр.3гр.20 +  т.12стр.6гр.20',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(116,NULL,0,NULL,117,7,0,0,0,'т.14стр.8гр.3 =  т.14стр.1гр.3 +  т.14стр.2гр.3 +  т.14стр.3гр.3 +  т.14стр.4гр.3 +  т.14стр.5гр.3 +  т.14стр.6гр.3 +  т.14стр.7гр.3',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(117,NULL,0,NULL,118,7,0,0,0,'т.14стр.14гр.3 =  т.14стр.10гр.3 +  т.14стр.11гр.3 +  т.14стр.12гр.3 +  т.14стр.13гр.3',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(118,NULL,0,NULL,119,7,0,0,0,'Проверки =  0',0,100,1,'20140401','','','','4fss','20140101','','=',9,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 118
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(4,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(5,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','12','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(8,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(9,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(10,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(11,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(12,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(13,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(14,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(15,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(16,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(17,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(18,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(19,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(20,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(21,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(22,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(23,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(24,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','6','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(25,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(26,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','6','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(27,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(28,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(29,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(30,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(31,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(32,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(33,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(34,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(35,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(36,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(37,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_3','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_4','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_5','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_2','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(38,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_3','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_4','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_5','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_2','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(39,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_3','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_4','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_5','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','10','15',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(40,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','7','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','9','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','16',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(41,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','16',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','16',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(42,2,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''1'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(43,2,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''15'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(44,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','7','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(45,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','7','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(46,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','7','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(47,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(48,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(49,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(50,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(51,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(52,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(53,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(54,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(55,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(56,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(57,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(58,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(59,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(60,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(61,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(62,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(63,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(64,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(65,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(65,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(66,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(67,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(68,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(68,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(69,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(69,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','10','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(70,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','15',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(70,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(70,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(71,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','15',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(71,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(71,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','15',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(72,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','15',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(73,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','6','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(74,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','15',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(74,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','8','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(75,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','7','15',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(75,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','8','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(76,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','9',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(77,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(78,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,5,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,6,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(79,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,5,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,6,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','12','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(80,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','7','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','10','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','12','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(81,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','6','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','7','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','10','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(82,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(82,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(82,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(83,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(83,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(83,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(84,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(84,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(84,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(85,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(85,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(85,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(86,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''1'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(86,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(86,3,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(87,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''15'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(87,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(87,3,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(88,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(88,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(88,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(89,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(90,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(91,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(92,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(92,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(92,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(93,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(93,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(93,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','12','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(94,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','7','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','10','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','12','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(95,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','6','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','7','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','10','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(96,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(97,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(97,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(97,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(98,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(98,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(98,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(99,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(99,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(99,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(100,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''1'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(100,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(100,3,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(101,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''15'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(101,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(101,3,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','8','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(102,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','18','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(103,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','17','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(104,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(105,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(106,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(107,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(108,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(109,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(110,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(111,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(112,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(113,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(114,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(115,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','8','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(116,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','14','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(117,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','10','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','13','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(118,1,2,'+',NULL,NULL,NULL,NULL,0,0,'SA_4FSS_EXPORT_TEST(0)','Проверки','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(118,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 424
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '3         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'3','Квартальные формы',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '999999    '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'999999','формы отчетности',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2014-07-02 09:42:40.587',121) WHERE [LINK_FORM]=@iLINK_FORM

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
ELSE BEGIN
	DECLARE @vcMessage VARCHAR(8000)
	SELECT @vcMessage = [CURRENT_DATE] FROM #tabStop
	IF @vcMessage = '2014-07-02 09:42:40.587'
	BEGIN
		SELECT @vcMessage = 'Форма 4fss с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 4fss с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-07-02 09:42:40.587. Обновление отклонено.'
	END

	 IF OBJECT_ID('tempdb..#tabUpdateMessages') IS NOT NULL
	 BEGIN
		 INSERT #tabUpdateMessages([TXT]) VALUES (@vcMessage)
	 END
	 SELECT @vcMessage
END
GO

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL DROP TABLE #tabInfo
SELECT * FROM #tabErrorLog

IF EXISTS(SELECT * FROM #tabErrorLog)
BEGIN
   ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
END

DROP TABLE #tabErrorLog
DROP TABLE #tabStop

COMMIT TRANSACTION -- Фиксация транзакции.
GO


GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (апр 22 2014  3:06:34:023PM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : РСВ-1 (Расчет по начисленным и уплаченным страховым взносам на ОПС и в ФСС (ФЗ от 24 июля 2009 г. № 212-ФЗ))
-- Дата ввода : 20140101
-- Дата окончания действия :
-- Версия : 2014-04-22 15:06:34.013
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = 'РСВ-1' AND [START_DATE] = '20140101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-04-22 15:06:34.013',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + 'РСВ-1',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = 'РСВ-1'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20140101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SALARY'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Расчет по начисленным и уплаченным страховым взносам на ОПС и в ФСС (ФЗ от 24 июля 2009 г. № 212-ФЗ)',@vcNEW_FORM_CODE,@dNEW_START_DATE,2,0,0,1,2291,'i_report_export_nalog',0,0,'19000101',NULL,''
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, 'sa_print_rsv_1_pfr_2014()','RSV_1_PFR_2014.bas','','KirRepMakerMultiSheet.XLS','RSV-1-PFR_2014.XLT','',NULL,'i_report_export_nalog',0,NULL,NULL,NULL,'          ','REPORTS_ATR_PERS_UCH,REPORTS_ATR_TYPE_KOR',NULL,NULL,'RN_PRINT_RSV1|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Титульный лист', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование',@iLINK_TABLE,0,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код',@iLINK_TABLE,1,1,2,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Количество застрахованных лиц',@iLINK_TABLE,1,0,3,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Среднесписочная численность',@iLINK_TABLE,1,0,4,1,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Титульный лист', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1. Расчет по начисленным и уплаченным страховым', @iLINK_FORM,2
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Страховые взносы на ОПС за периоды, начиная с 2014 г.',@iLINK_TABLE,1,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Страховые взносы на ОПС за периоды 2010-2013: страховая часть',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Страховые взносы на ОПС за периоды 2010-2013: накопительная часть',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Страховые взносы на ОПС:по доп тарифу - занятых на видах работ, указанных в подпункте 1 пункта 1 статьи 27 Федерального закона № 173-ФЗ',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Страховые взносы на ОПС:по доп тарифу - занятых на видах работ, указанных в подпунктах 2-18 пункта 1 статьи 27 Федерального закона № 173-ФЗ',@iLINK_TABLE,1,0,7,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Страховые взносы на ОМС',@iLINK_TABLE,1,0,8,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1. Расчет по начисленным и уплаченным страховым', @iLINK_FORM,2, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2. Расчет страховых взносов по тарифу', @iLINK_FORM,3
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода: 1 месяц',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода: 2 месяц',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода: 3 месяц',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2. Расчет страховых взносов по тарифу', @iLINK_FORM,3, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2_1. Расчет страховых взносов по тарифу ОИ', @iLINK_FORM,4
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода: 1 месяц',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода: 2 месяц',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода: 3 месяц',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2_1. Расчет страховых взносов по тарифу ОИ', @iLINK_FORM,4, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.2_2.3.Расчет страховых взнос. по доп.тар. для о', @iLINK_FORM,5
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,0,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода: 1 месяц',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода: 2 месяц',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода: 3 месяц',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.2_2.3.Расчет страховых взнос. по доп.тар. для о', @iLINK_FORM,5, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.4_1.Расчет страховых по доп.тар. 1', @iLINK_FORM,6
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,0,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода: 1 месяц',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода: 2 месяц',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода: 3 месяц',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.4_1.Расчет страховых по доп.тар. 1', @iLINK_FORM,6, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.4_2.Расчет страховых по доп.тарифу 2', @iLINK_FORM,7
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,0,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода: 1 месяц',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода: 2 месяц',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода: 3 месяц',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.4_2.Расчет страховых по доп.тарифу 2', @iLINK_FORM,7, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.5.1.Перечень пачек док-ов исход. свед. индивид.', @iLINK_FORM,8
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ пп',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Сведения о базе для начисления страховых взносов на обязательное пенсионное страхование с сумм выплат и иных вознаграждений, не превышающих предельную величину базы для начисления страховых взносов, содержащиеся в пачке документов',@iLINK_TABLE,1,0,3,2,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Сведения о начисленных страховых взносах с сумм, не превышающих предельную величину базы для начисления страховых взносов, содержащихся в пачке документов',@iLINK_TABLE,1,0,4,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Сведения о количестве застрахованных лиц в пачке документов',@iLINK_TABLE,1,0,5,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Имя файла (номер пачки документов)',@iLINK_TABLE,1,1,6,0,50,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Дата составления',@iLINK_TABLE,1,1,7,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Тип сведений',@iLINK_TABLE,1,0,8,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Период',@iLINK_TABLE,1,0,9,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Год',@iLINK_TABLE,1,0,10,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Ссылка на документ',@iLINK_TABLE,1,0,11,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.5.1.Перечень пачек док-ов исход. свед. индивид.', @iLINK_FORM,8, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RSA_RSV_1_PERS_UCH @dateBeginPeriod, @dateEndPeriod, @depLink, 0, @LSF',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.5.2.Переч. пачек док-ов коррект. свед. индивид(', @iLINK_FORM,9
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ пп',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Сведения о периоде, за который производится корректировка сведений - отчетный период (код)',@iLINK_TABLE,1,1,3,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Сведения о периоде, за который производится корректировка сведений - год',@iLINK_TABLE,1,1,4,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Сведения о сумме доначисленных страховых взносов, содержащихся в пачке документов (руб.коп.)на обязательное пенсионное страхование за периоды, начиная с 2014 г.',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Сведения о сумме доначисленных страховых взносов, содержащихся в пачке документов (руб.коп.)за периоды 2010-2013 гг.на страховую часть',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Сведения о сумме доначисленных страховых взносов, содержащихся в пачке документов (руб.коп.) за периоды 2010-2013 гг.на накопительную часть',@iLINK_TABLE,1,0,7,7,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Сведения о количестве застрахованных лиц в пачке документов',@iLINK_TABLE,1,0,8,8,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Имя файла (номер пачки документов)',@iLINK_TABLE,1,1,9,0,50,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Дата составления',@iLINK_TABLE,1,1,10,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Тип сведений',@iLINK_TABLE,1,0,11,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Период(код)',@iLINK_TABLE,1,1,12,0,1,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Период(год)',@iLINK_TABLE,1,1,13,0,4,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Сумма базы',@iLINK_TABLE,1,0,14,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 15,'Сумма ОПС',@iLINK_TABLE,1,0,15,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 16,'Ссылка на документ',@iLINK_TABLE,1,0,16,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.5.2.Переч. пачек док-ов коррект. свед. индивид(', @iLINK_FORM,9, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RSA_RSV_1_PERS_UCH @dateBeginPeriod, @dateEndPeriod, @depLink, 1, @LSF',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3.1_3.2. Соотв. условиям  п.3 ч.1 ст.58 № 212-ФЗ', @iLINK_FORM,10
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода, 1 месяц',@iLINK_TABLE,1,0,4,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода, 2 месяц',@iLINK_TABLE,1,0,5,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода, 3 месяц',@iLINK_TABLE,1,0,6,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.1_3.2. Соотв. условиям  п.3 ч.1 ст.58 № 212-ФЗ', @iLINK_FORM,10, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3.3. Соответствия условиям п.6 ч.1 ст.58 № 212-ФЗ', @iLINK_FORM,11
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'По итогам 9-ти месяцев года, предшествующего текущему расчетному перио',@iLINK_TABLE,1,0,3,1,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'По итогам текущего отчетного (расчетного) периода',@iLINK_TABLE,1,0,4,2,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Дата записи в реестре  аккредитованных организаций',@iLINK_TABLE,1,1,5,5,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'№ записи в реестре аккредитованных организаций',@iLINK_TABLE,1,1,6,6,50,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.3. Соответствия условиям п.6 ч.1 ст.58 № 212-ФЗ', @iLINK_FORM,11, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3.4. Соответствие условиям п.7 ч.1 ст. 58  №212-Ф', @iLINK_FORM,12
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Наименование вида экономической деятельности с указанием кода ОКВЭД',@iLINK_TABLE,1,1,2,0,254,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'',@iLINK_TABLE,1,1,3,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Код строки',@iLINK_TABLE,1,1,4,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Доходы по виду экономической деятельности',@iLINK_TABLE,1,0,5,5,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Доля дох. и поступ по данному виду эконом деят-ти в общей сумме доходо',@iLINK_TABLE,1,0,6,6,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Дата внесения в реестр СМИ',@iLINK_TABLE,1,1,7,7,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'№ записи в реестре СМИ',@iLINK_TABLE,1,1,8,8,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.4. Соответствие условиям п.7 ч.1 ст. 58  №212-Ф', @iLINK_FORM,12, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3.5_3.6. Соотв. условиям п.8,п.11 ч.1. ст.58 № 21', @iLINK_FORM,13
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'С начала отчетного (расчетного) периода',@iLINK_TABLE,0,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'По итогам года, предшествующего текущему расчетному периоду',@iLINK_TABLE,1,0,4,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'По итогам текущего расчетного периода',@iLINK_TABLE,1,0,5,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.5_3.6. Соотв. условиям п.8,п.11 ч.1. ст.58 № 21', @iLINK_FORM,13, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р4.Суммы доначисл. страховых взносов с начала расч', @iLINK_FORM,14
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,3,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Основание для доначисления страховых взносов*',@iLINK_TABLE,1,0,2,0,0,1,NULL,NULL,NULL,'9',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Код основания для применения части 2.1 статьи 58.3 Федерального закона от 24 июля 2009 г.',@iLINK_TABLE,1,0,3,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Период, за который выявлены и доначислены страховые взносы, год',@iLINK_TABLE,1,1,4,4,4,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Период, за который выявлены и доначислены страховые взносы, месяц',@iLINK_TABLE,1,0,5,5,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Страховые взносы: страховая часть, начиная с 2014 г. - Всего',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Страховые взносы: страховая часть, начиная с 2014 г. - в том числе с сумм, превышающих предельную величину базы для начисления страховых взносов',@iLINK_TABLE,1,0,7,7,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Страховые взносы: страховая часть - Всего',@iLINK_TABLE,1,0,8,8,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Страховые взносы: страховая часть - в том числе сумм превышающих предельную величину базы для начисления страховых взносов',@iLINK_TABLE,1,0,9,9,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Страховые взносы на обязательное пенсионное страхование, накопительная',@iLINK_TABLE,1,0,10,10,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Страх. взносы на ОПС, по доп тарифу: в соответствии с частью 1 статьи 58.3 Федерального закона от 24 июля 2009 г. № 212-ФЗ',@iLINK_TABLE,1,0,11,11,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Страх. взносы на ОПС, по доп тарифу: в соответствии с частью 2 статьи 58.3 Федерального закона от 24 июля 2009 г. № 212-ФЗ',@iLINK_TABLE,1,0,12,12,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Страх. взносы на ОПС, по доп тарифу: в соответствии с частью 2.1 статьи 58.3 Федерального закона от 24 июля 2009 г. № 212-ФЗ',@iLINK_TABLE,1,0,13,13,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Страховые взносы на обязательное медицинское страхование',@iLINK_TABLE,1,0,14,14,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р4.Суммы доначисл. страховых взносов с начала расч', @iLINK_FORM,14, @iLINK_CODE_COL,1,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р5.Свед., необходимые для применения п.1 ч.3 ст.9', @iLINK_FORM,15
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,3,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Фамилия, имя, отчество обучающегося',@iLINK_TABLE,1,1,2,0,254,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Сведения из справки (номер, дата), подтверждающие членство в студенческом отряде',@iLINK_TABLE,1,1,3,0,20,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Сведения из справки (номер, дата), подтверждающие очную форму обучения',@iLINK_TABLE,1,1,4,0,20,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Всего с начала расчетного периода',@iLINK_TABLE,0,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'в том числе за последние три месяца отчетного периода, 1 месяц',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'в том числе за последние три месяца отчетного периода, 2 месяц',@iLINK_TABLE,1,0,7,7,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'в том числе за последние три месяца отчетного периода, 3 месяц',@iLINK_TABLE,1,0,8,8,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р5.Свед., необходимые для применения п.1 ч.3 ст.9', @iLINK_FORM,15, @iLINK_CODE_COL,1,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р5_2.Свед, необходимые для прим п.1 ч.3 ст.9 № 212', @iLINK_FORM,16
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Дата записи в реестре',@iLINK_TABLE,1,1,3,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'№ записи в реестре',@iLINK_TABLE,1,1,4,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р5_2.Свед, необходимые для прим п.1 ч.3 ст.9 № 212', @iLINK_FORM,16, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р6.1.Сведения о застрахованном лице', @iLINK_FORM,17
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Фамилия',@iLINK_TABLE,1,1,2,0,100,1,NULL,NULL,NULL,NULL,8,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Имя',@iLINK_TABLE,1,1,3,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Отчество',@iLINK_TABLE,1,1,4,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'СНИЛС',@iLINK_TABLE,1,1,5,0,14,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Тип сведений',@iLINK_TABLE,1,1,6,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Номер пачки',@iLINK_TABLE,1,1,7,0,3,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Наименование файла',@iLINK_TABLE,1,1,8,0,100,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Дата документа',@iLINK_TABLE,1,1,9,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р6.1.Сведения о застрахованном лице', @iLINK_FORM,17, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RSA_RSV_1_PERS_UCH_SZV @dateBeginPeriod, @dateEndPeriod, @depLink, 0 , @LSF',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р6.4. Свед. о сумме вып. и иных вознаг., начисленн', @iLINK_FORM,18
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'СНИЛС',@iLINK_TABLE,1,1,2,0,14,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'',@iLINK_TABLE,1,1,3,0,254,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Код строки',@iLINK_TABLE,1,1,4,0,4,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Код категории застрахованного лица',@iLINK_TABLE,1,1,5,0,15,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Сумма выплат и иных вознаграждений, начисленных в пользу физического лица',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'База для начисления страховых взносов на обязательное пенсионное страхование с сумм выплат и иных вознаграждений, не превышающих предельную величину базы для начисления страховых взносов, Всего',@iLINK_TABLE,1,0,7,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'в том числе  по гражданско-правовым  договорам',@iLINK_TABLE,1,0,8,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Сумма выплат и иных вознаграждений, превышающая предельную величину базы для начисления страховых взносов',@iLINK_TABLE,1,0,9,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Отчетный период(код)',@iLINK_TABLE,1,1,10,0,1,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Календарный год',@iLINK_TABLE,1,1,11,0,4,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Тип сведений',@iLINK_TABLE,1,1,12,0,14,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Отчетный период(код) корректирующие\отменяющие',@iLINK_TABLE,1,1,13,0,1,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Календарный год - корректирующие\отменяющие',@iLINK_TABLE,1,1,14,0,4,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 15,'Номер',@iLINK_TABLE,0,0,15,0,0,1,NULL,NULL,NULL,NULL,9,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 16,'Фамилия',@iLINK_TABLE,1,1,16,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 17,'Имя',@iLINK_TABLE,1,1,17,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 18,'Отчество',@iLINK_TABLE,1,1,18,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 19,'Период корректировки (код)1',@iLINK_TABLE,1,0,19,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 20,'Год корректировки (код)1',@iLINK_TABLE,1,0,20,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 21,'Сумма на ОПС1',@iLINK_TABLE,1,0,21,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 22,'Сумма на страховую часть ОПС1',@iLINK_TABLE,1,0,22,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 23,'Сумма на накопительную часть ОПС1',@iLINK_TABLE,1,0,23,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 24,'Период корректировки(код)2',@iLINK_TABLE,1,0,24,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 25,'Год корректировки (код)2',@iLINK_TABLE,1,0,25,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 26,'Сумма на ОПС2',@iLINK_TABLE,1,0,26,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 27,'Сумма на страховую часть ОПС2',@iLINK_TABLE,1,0,27,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 28,'Сумма на накопительную часть ОПС2',@iLINK_TABLE,1,0,28,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 29,'Период корректировки(код)3',@iLINK_TABLE,1,0,29,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 30,'Год корректировки (код)3',@iLINK_TABLE,1,0,30,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 31,'Сумма на ОПС3',@iLINK_TABLE,1,0,31,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 32,'Сумма на страховую часть ОПС3',@iLINK_TABLE,1,0,32,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 33,'Сумма на накопительную часть ОПС3',@iLINK_TABLE,1,0,33,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 34,'Период корректировки(код)4',@iLINK_TABLE,1,0,34,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 35,'Год корректировки (код)4',@iLINK_TABLE,1,0,35,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 36,'Сумма на ОПС4',@iLINK_TABLE,1,0,36,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 37,'Сумма на страховую часть ОПС4',@iLINK_TABLE,1,0,37,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 38,'Сумма на накопительную часть ОПС4',@iLINK_TABLE,1,0,38,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 39,'Период корректировки(код)5',@iLINK_TABLE,1,0,39,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 40,'Год корректировки (код)5',@iLINK_TABLE,1,0,40,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 41,'Сумма на ОПС5',@iLINK_TABLE,1,0,41,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 42,'Сумма на страховую часть ОПС5',@iLINK_TABLE,1,0,42,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 43,'Сумма на накопительную часть ОПС5',@iLINK_TABLE,1,0,43,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 44,'Общая сумма для раздела 6_5',@iLINK_TABLE,1,0,44,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р6.4. Свед. о сумме вып. и иных вознаг., начисленн', @iLINK_FORM,18, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RSA_RSV_1_PERS_UCH_SZV @dateBeginPeriod, @dateEndPeriod, @depLink, 1, @LSF',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р6.6.Информация о корректирующих сведениях', @iLINK_FORM,19
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Отчетный период (код)',@iLINK_TABLE,1,0,2,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Год',@iLINK_TABLE,1,1,3,0,4,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Сумма доначисленных страховых взносов (руб.коп.) на ОПС с 2014 г',@iLINK_TABLE,1,0,4,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Сумма доначисленных страховых взносов (руб.коп.) - на страховую часть',@iLINK_TABLE,1,0,5,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Сумма доначисленных страховых взносов (руб.коп.) - на накопительную часть',@iLINK_TABLE,1,0,6,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'СНИЛС',@iLINK_TABLE,0,1,7,0,14,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Номер',@iLINK_TABLE,0,0,8,0,0,1,NULL,NULL,NULL,NULL,9,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р6.6.Информация о корректирующих сведениях', @iLINK_FORM,19, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RSA_RSV_1_PERS_UCH_SZV @dateBeginPeriod, @dateEndPeriod, @depLink, 2, @LSF',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р6.7.Свед. о сумме вып. п1, 2 и п.1 ст.58.3 № 212-', @iLINK_FORM,20
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'',@iLINK_TABLE,1,1,2,0,254,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Код строки',@iLINK_TABLE,1,1,3,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Код специальной оценки условий труда',@iLINK_TABLE,1,1,4,0,15,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Сумма выплат и иных вознаграждений, начисленых в пользу физического лица, занятого на видах работ, указанных в подпункте 1 пункта 1 статьи 27 Федерального закона от  17 декабря 2001 г. № 173-ФЗ',@iLINK_TABLE,1,0,5,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Сумма выплат и иных вознаграждений, начисленных в пользу физического лица, занятого на видах работ, указанных в подпунктах 2-18 пункта 1 статьи 27 Федерального закона от  17 декабря 2001 г.',@iLINK_TABLE,1,0,6,5,0,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'СНИЛС',@iLINK_TABLE,1,1,7,0,14,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Номер',@iLINK_TABLE,1,0,8,0,0,1,NULL,NULL,NULL,NULL,9,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Тип сведений',@iLINK_TABLE,1,0,9,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Начало периода с (дд.мм.гггг.)1',@iLINK_TABLE,0,1,10,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Конец периода по (дд.мм.гггг.)1',@iLINK_TABLE,1,1,11,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Территориальные условия труда(код)1',@iLINK_TABLE,1,1,12,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Особые условия труда (код)1',@iLINK_TABLE,1,1,13,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Исчисление страхового стажа - Основание (код)1',@iLINK_TABLE,1,1,14,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 15,'Исчисление страхового стажа - Дополнительные сведения1',@iLINK_TABLE,1,1,15,0,100,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 16,'Условия досрочного назначения трудовой пенсии - Основание (код)1',@iLINK_TABLE,1,1,16,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 17,'Условия досрочного назначения трудовой пенсии - Дополнительные сведения1',@iLINK_TABLE,1,1,17,0,100,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 18,'Начало периода с (дд.мм.гггг.)2',@iLINK_TABLE,1,1,18,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 19,'Конец периода по (дд.мм.гггг.)2',@iLINK_TABLE,0,1,19,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 20,'Территориальные условия труда(код)2',@iLINK_TABLE,0,1,20,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 21,'Особые условия труда (код)2',@iLINK_TABLE,0,1,21,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 22,'Исчисление страхового стажа - Основание (код)2',@iLINK_TABLE,1,1,22,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 23,'Исчисление страхового стажа - Дополнительные сведения2',@iLINK_TABLE,1,1,23,0,100,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 24,'Условия досрочного назначения трудовой пенсии - Основание (код)2',@iLINK_TABLE,1,1,24,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 25,'Условия досрочного назначения трудовой пенсии - Дополнительные сведения2',@iLINK_TABLE,0,1,25,0,100,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 26,'Начало периода с (дд.мм.гггг.)3',@iLINK_TABLE,1,1,26,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 27,'Конец периода по (дд.мм.гггг.)3',@iLINK_TABLE,1,1,27,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 28,'Территориальные условия труда(код)3',@iLINK_TABLE,1,1,28,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 29,'Особые условия труда (код)3',@iLINK_TABLE,1,1,29,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 30,'Исчисление страхового стажа - Основание (код)3',@iLINK_TABLE,1,1,30,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 31,'Исчисление страхового стажа - Дополнительные сведения3',@iLINK_TABLE,1,1,31,0,100,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 32,'Условия досрочного назначения трудовой пенсии - Основание (код)3',@iLINK_TABLE,1,1,32,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 33,'Условия досрочного назначения трудовой пенсии - Дополнительные сведения3',@iLINK_TABLE,1,1,33,0,100,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 34,'Начало периода с (дд.мм.гггг.)4',@iLINK_TABLE,1,1,34,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 35,'Конец периода по (дд.мм.гггг.)4',@iLINK_TABLE,1,1,35,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 36,'Территориальные условия труда(код)4',@iLINK_TABLE,1,1,36,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 37,'Особые условия труда (код)4',@iLINK_TABLE,1,1,37,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 38,'Исчисление страхового стажа - Основание (код)4',@iLINK_TABLE,1,1,38,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 39,'Исчисление страхового стажа - Дополнительные сведения4',@iLINK_TABLE,1,1,39,0,100,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 40,'Условия досрочного назначения трудовой пенсии - Основание (код)4',@iLINK_TABLE,1,1,40,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 41,'Условия досрочного назначения трудовой пенсии - Дополнительные сведения4',@iLINK_TABLE,1,1,41,0,100,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 42,'Фамилия',@iLINK_TABLE,0,1,42,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 43,'Имя',@iLINK_TABLE,0,1,43,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 44,'Отчество',@iLINK_TABLE,0,1,44,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р6.7.Свед. о сумме вып. п1, 2 и п.1 ст.58.3 № 212-', @iLINK_FORM,20, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RSA_RSV_1_PERS_UCH_SZV @dateBeginPeriod, @dateEndPeriod, @depLink, 3, @LSF',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р6.8. Период работы за последние три месяца отчетн', @iLINK_FORM,21
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ пп',@iLINK_TABLE,1,1,1,0,254,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Начало периода с (дд.мм.гггг.)',@iLINK_TABLE,1,1,2,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Конец периода по (дд.мм.гггг)',@iLINK_TABLE,1,1,3,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Территориальные условия труда(код)',@iLINK_TABLE,1,1,4,0,20,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Особые условия труда (код)',@iLINK_TABLE,1,1,5,0,20,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Исчисление страхового стажа - Основание (код)',@iLINK_TABLE,1,1,6,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Исчисление страхового стажа - Дополнительные сведения',@iLINK_TABLE,1,1,7,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Условия досрочного назначения трудовой пенсии - Основание (код)',@iLINK_TABLE,1,1,8,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Условия досрочного назначения трудовой пенсии - Дополнительные сведения',@iLINK_TABLE,1,1,9,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'СНИЛС',@iLINK_TABLE,1,1,10,0,14,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Номер',@iLINK_TABLE,1,0,11,0,0,1,NULL,NULL,NULL,NULL,8,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Тип сведений',@iLINK_TABLE,0,0,12,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Фамилия',@iLINK_TABLE,0,1,13,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Имя',@iLINK_TABLE,0,1,14,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 15,'Отчество',@iLINK_TABLE,0,1,15,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р6.8. Период работы за последние три месяца отчетн', @iLINK_FORM,21, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RSA_RSV_1_PERS_UCH_SZV @dateBeginPeriod, @dateEndPeriod, @depLink, 4, @LSF',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (1,1,1,1)
INSERT #R VALUES (1,2,0,1)
INSERT #R VALUES (3,2,0,1)
INSERT #R VALUES (4,2,0,1)
INSERT #R VALUES (5,2,0,1)
INSERT #R VALUES (6,2,1,1)
INSERT #R VALUES (7,2,0,1)
INSERT #R VALUES (8,2,1,1)
INSERT #R VALUES (11,2,0,1)
INSERT #R VALUES (12,2,0,1)
INSERT #R VALUES (13,2,0,1)
INSERT #R VALUES (14,2,0,1)
INSERT #R VALUES (16,2,0,1)
INSERT #R VALUES (2,2,0,1)
INSERT #R VALUES (10,2,1,1)
INSERT #R VALUES (15,2,1,1)
INSERT #R VALUES (1,3,0,1)
INSERT #R VALUES (2,3,0,1)
INSERT #R VALUES (3,3,0,1)
INSERT #R VALUES (4,3,0,1)
INSERT #R VALUES (5,3,1,1)
INSERT #R VALUES (6,3,0,1)
INSERT #R VALUES (7,3,0,1)
INSERT #R VALUES (8,3,0,1)
INSERT #R VALUES (9,3,0,1)
INSERT #R VALUES (10,3,0,1)
INSERT #R VALUES (11,3,0,1)
INSERT #R VALUES (12,3,0,1)
INSERT #R VALUES (13,3,0,1)
INSERT #R VALUES (14,3,2,1)
INSERT #R VALUES (15,3,0,1)
INSERT #R VALUES (1,4,0,1)
INSERT #R VALUES (2,4,0,1)
INSERT #R VALUES (3,4,0,1)
INSERT #R VALUES (4,4,0,1)
INSERT #R VALUES (5,4,1,1)
INSERT #R VALUES (6,4,0,1)
INSERT #R VALUES (7,4,0,1)
INSERT #R VALUES (8,4,0,1)
INSERT #R VALUES (9,4,0,1)
INSERT #R VALUES (10,4,0,1)
INSERT #R VALUES (11,4,0,1)
INSERT #R VALUES (12,4,0,1)
INSERT #R VALUES (13,4,0,1)
INSERT #R VALUES (14,4,0,1)
INSERT #R VALUES (15,4,2,1)
INSERT #R VALUES (1,5,0,1)
INSERT #R VALUES (2,5,0,1)
INSERT #R VALUES (3,5,1,1)
INSERT #R VALUES (4,5,0,1)
INSERT #R VALUES (5,5,0,1)
INSERT #R VALUES (6,5,0,1)
INSERT #R VALUES (7,5,0,1)
INSERT #R VALUES (8,5,0,1)
INSERT #R VALUES (10,5,0,1)
INSERT #R VALUES (9,5,2,1)
INSERT #R VALUES (1,6,0,1)
INSERT #R VALUES (2,6,0,1)
INSERT #R VALUES (3,6,0,1)
INSERT #R VALUES (5,6,0,1)
INSERT #R VALUES (6,6,0,1)
INSERT #R VALUES (7,6,0,1)
INSERT #R VALUES (9,6,0,1)
INSERT #R VALUES (10,6,0,1)
INSERT #R VALUES (11,6,0,1)
INSERT #R VALUES (12,6,0,1)
INSERT #R VALUES (14,6,0,1)
INSERT #R VALUES (15,6,0,1)
INSERT #R VALUES (16,6,0,1)
INSERT #R VALUES (17,6,0,1)
INSERT #R VALUES (19,6,0,1)
INSERT #R VALUES (20,6,0,1)
INSERT #R VALUES (21,6,0,1)
INSERT #R VALUES (22,6,0,1)
INSERT #R VALUES (24,6,0,1)
INSERT #R VALUES (25,6,0,1)
INSERT #R VALUES (4,6,1,1)
INSERT #R VALUES (8,6,2,1)
INSERT #R VALUES (13,6,3,1)
INSERT #R VALUES (18,6,4,1)
INSERT #R VALUES (23,6,5,1)
INSERT #R VALUES (1,7,0,1)
INSERT #R VALUES (2,7,0,1)
INSERT #R VALUES (3,7,0,1)
INSERT #R VALUES (5,7,0,1)
INSERT #R VALUES (6,7,0,1)
INSERT #R VALUES (7,7,0,1)
INSERT #R VALUES (9,7,0,1)
INSERT #R VALUES (10,7,0,1)
INSERT #R VALUES (11,7,0,1)
INSERT #R VALUES (12,7,0,1)
INSERT #R VALUES (14,7,0,1)
INSERT #R VALUES (15,7,0,1)
INSERT #R VALUES (16,7,0,1)
INSERT #R VALUES (17,7,0,1)
INSERT #R VALUES (19,7,0,1)
INSERT #R VALUES (20,7,0,1)
INSERT #R VALUES (21,7,0,1)
INSERT #R VALUES (22,7,0,1)
INSERT #R VALUES (24,7,0,1)
INSERT #R VALUES (25,7,0,1)
INSERT #R VALUES (4,7,1,1)
INSERT #R VALUES (8,7,2,1)
INSERT #R VALUES (13,7,3,1)
INSERT #R VALUES (18,7,4,1)
INSERT #R VALUES (23,7,5,1)
INSERT #R VALUES (1,10,0,1)
INSERT #R VALUES (2,10,0,1)
INSERT #R VALUES (3,10,1,1)
INSERT #R VALUES (4,10,0,1)
INSERT #R VALUES (5,10,0,1)
INSERT #R VALUES (7,10,0,1)
INSERT #R VALUES (8,10,0,1)
INSERT #R VALUES (6,10,2,1)
INSERT #R VALUES (9,10,3,1)
INSERT #R VALUES (1,11,0,1)
INSERT #R VALUES (2,11,0,1)
INSERT #R VALUES (3,11,1,1)
INSERT #R VALUES (4,11,0,1)
INSERT #R VALUES (5,11,0,1)
INSERT #R VALUES (1,12,0,1)
INSERT #R VALUES (2,12,0,1)
INSERT #R VALUES (3,12,0,1)
INSERT #R VALUES (4,12,0,1)
INSERT #R VALUES (5,12,0,1)
INSERT #R VALUES (6,12,0,1)
INSERT #R VALUES (7,12,0,1)
INSERT #R VALUES (8,12,0,1)
INSERT #R VALUES (9,12,0,1)
INSERT #R VALUES (10,12,0,1)
INSERT #R VALUES (11,12,1,1)
INSERT #R VALUES (12,12,0,1)
INSERT #R VALUES (2,13,0,1)
INSERT #R VALUES (3,13,1,1)
INSERT #R VALUES (1,13,0,1)
INSERT #R VALUES (4,13,0,1)
INSERT #R VALUES (5,13,0,1)
INSERT #R VALUES (6,13,0,1)
INSERT #R VALUES (7,13,0,1)
INSERT #R VALUES (8,13,1,1)
INSERT #R VALUES (1,16,0,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 141
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,1,1,'Показатель                                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (1,1,3,'РСВ1_14_ПФР_УСТАНОВКА() + РСВ1_ЗНАЧЕНИЕ(К.СТР.,1)')
INSERT #F VALUES (1,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,2)')
INSERT #F VALUES (2,1,1,'Остаток страховых взносов, подлежащих уплате на начало расчетного периода
(+) задолженность, (-) переплата                                                                                                                                                   ')
INSERT #F VALUES (2,2,1,'Начислено страховых взносов с начала расчетного периода                                                                                                                                                                                                       ')
INSERT #F VALUES (2,3,1,'в том числе за последние три месяца отчетного периода : 1 месяц                                                                                                                                                                                               ')
INSERT #F VALUES (2,4,1,'         2 месяц                                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,5,1,'         3 месяц                                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,6,1,'Итого подлежит уплате за последние 3 месяца (с.111 + с.112 + с.113)                                                                                                                                                                                           ')
INSERT #F VALUES (2,7,1,'Доначислено страховых взносов с начала расчетного периода                                                                                                                                                                                                     ')
INSERT #F VALUES (2,8,1,'В том числе с сумм, превышающих предельную величину базы для начисления страховых взносов                                                                                                                                                                     ')
INSERT #F VALUES (2,10,1,'Всего к уплате (с. 100 + с. 110 + с. 120)                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,11,1,'Уплачено с начала расчетного периода                                                                                                                                                                                                                          ')
INSERT #F VALUES (2,12,1,'в том числе за последние три месяца отчетного периода: 1 месяц                                                                                                                                                                                                ')
INSERT #F VALUES (2,13,1,'         2 месяц                                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,14,1,'        3 месяц                                                                                                                                                                                                                                               ')
INSERT #F VALUES (2,15,1,'        итого (с. 141 + с. 142 + с. 143)                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,16,1,'Остаток страховых взносов, подлежащих уплате
на конец отчетного периода (с.130 - с.140) (+) задолженность, (-) переплата                                                                                                                                     ')
INSERT #F VALUES (2,1,2,'100                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,2,2,'110                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,3,2,'111                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,4,2,'112                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,5,2,'113                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,6,2,'114                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,7,2,'120                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,8,2,'121                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,10,2,'130                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,11,2,'140                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,12,2,'141                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,13,2,'142                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,14,2,'143                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,15,2,'144                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,16,2,'150                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,11,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (2,12,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (2,13,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (2,14,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (2,1,4,'КТСН("_.303.10","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,2,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,3,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,4,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (2,12,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (2,13,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (2,14,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (2,1,5,'КТСН("_.303.11","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,2,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,3,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,4,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,5,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,8,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (2,12,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (2,13,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (2,14,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (2,1,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (2,8,6,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,6,'АДТКТ("_.303.09, КАУ =kau_RSV1_s1","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=НАЧ.ГОДА") + АДТКТ("_.303.09, КАУ =kau_RSV1_s1","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,12,6,'АДТКТ("_.303.09, КАУ =kau_RSV1_s1","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(1)") + АДТКТ("_.303.09, КАУ =kau_RSV1_s1","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,13,6,'АДТКТ("_.303.09, КАУ =kau_RSV1_s1","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(2)") + АДТКТ("_.303.09, КАУ =kau_RSV1_s1","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,14,6,'АДТКТ("_.303.09, КАУ =kau_RSV1_s1","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(3)") + АДТКТ("_.303.09, КАУ =kau_RSV1_s1","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,1,7,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,7)')
INSERT #F VALUES (2,8,7,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,7,'АДТКТ("_.303.09, КАУ =kau_RSV1_s2","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=НАЧ.ГОДА") + АДТКТ("_.303.09, КАУ =kau_RSV1_s2","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,12,7,'АДТКТ("_.303.09, КАУ =kau_RSV1_s2","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(1)") + АДТКТ("_.303.09, КАУ =kau_RSV1_s2","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,13,7,'АДТКТ("_.303.09, КАУ =kau_RSV1_s2","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(2)") + АДТКТ("_.303.09, КАУ =kau_RSV1_s2","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,14,7,'АДТКТ("_.303.09, КАУ =kau_RSV1_s2","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(3)") + АДТКТ("_.303.09, КАУ =kau_RSV1_s2","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,1,8,'КТСН("_.303.07","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,8,8,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,8,'АДТКТ("_.303.07","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=НАЧ.ГОДА") + АДТКТ("_.303.07","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,12,8,'АДТКТ("_.303.07","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(1)") + АДТКТ("_.303.07","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,13,8,'АДТКТ("_.303.07","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(2)") + АДТКТ("_.303.07","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,14,8,'АДТКТ("_.303.07","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(3)") + АДТКТ("_.303.07","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (3,1,1,'Сумма выплат и иных вознаграждений, на-численных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с международными договорами                                                            ')
INSERT #F VALUES (3,2,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с международными договорами                                                                                   ')
INSERT #F VALUES (3,3,1,'Сумма расходов, принимаемых к вычету в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                                       ')
INSERT #F VALUES (3,4,1,'Суммы выплат и иных вознаграждений, превышающие предельную величину базы для начисления страховых взносов                                                                                                                                                     ')
INSERT #F VALUES (3,5,1,'База для начисления страховых взносов на обязательное пенсионное страхование (с. 200 - с. 201 - с. 202 - с. 203)                                                                                                                                              ')
INSERT #F VALUES (3,6,1,'Начислено страховых взносов на обязательное пенсионное страхование:с сумм, не превышающих предельную базу для начисления страховых взносов                                                                                                                    ')
INSERT #F VALUES (3,15,1,'Начислено страховых взносов на обязательное медицинское страхование                                                                                                                                                                                           ')
INSERT #F VALUES (3,7,1,'с сумм, превышающих предельную величину базы для начисления страховых взносов                                                                                                                                                                                 ')
INSERT #F VALUES (3,8,1,'Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы в соответствии с тарифом страховых взносов, всего (чел.)                                                                                                         ')
INSERT #F VALUES (3,9,1,'в том числе количество физических лиц, выплаты и иные вознаграждения которым превысили предельную величину базы для начисления страховых взносов  (чел.)                                                                                                      ')
INSERT #F VALUES (3,10,1,'Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009г. 
№ 212-ФЗ и в соответствии с международными договорами                                                             ')
INSERT #F VALUES (3,11,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии с частями 1, 2 статьи 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с международными договорами                                                                        ')
INSERT #F VALUES (3,12,1,'Сумма расходов, принимаемых к вычету в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                                       ')
INSERT #F VALUES (3,13,1,'Суммы выплат и иных вознаграждений, превышающие предельную величину базы для начисления страховых взносов                                                                                                                                                     ')
INSERT #F VALUES (3,14,1,'База для начисления страховых взносов на обязательное медицинское страхование (с. 210 - с. 211 - с. 212 - с. 213)                                                                                                                                             ')
INSERT #F VALUES (3,1,2,'200                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,2,2,'201                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,3,2,'202                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,4,2,'203                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,5,2,'204                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,6,2,'205                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,15,2,'215                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,7,2,'206                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,8,2,'207                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,9,2,'208                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,10,2,'210                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,11,2,'211                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,12,2,'212                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,13,2,'213                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,14,2,'214                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,1,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,2,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,3,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,4,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,6,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,15,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,7,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,8,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,9,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,10,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,11,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,12,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,13,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,2,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,3,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,4,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,6,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,15,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,7,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,8,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,9,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,10,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,11,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,12,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,13,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,1,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,2,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,3,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,4,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,6,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,15,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,7,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,8,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,9,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,10,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,11,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,12,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,13,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,1,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,2,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,3,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,4,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,6,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,15,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,7,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,8,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,9,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,10,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,11,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,12,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,13,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,1,1,'Сумма выплат и иных вознаграждений, на-численных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с международными договорами                                                            ')
INSERT #F VALUES (4,2,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с международными договорами                                                                                   ')
INSERT #F VALUES (4,3,1,'Сумма расходов, принимаемых к вычету в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                                       ')
INSERT #F VALUES (4,4,1,'Суммы выплат и иных вознаграждений, превышающие предельную величину базы для начисления страховых взносов
от 24 июля 2009 г. № 212-ФЗ: 1966 г.р. и старше                                                                                                    ')
INSERT #F VALUES (4,5,1,'База для начисления страховых взносов на обязательное пенсионное страхование (с. 200 - с. 201 - с. 202 - с. 203)                                                                                                                                              ')
INSERT #F VALUES (4,6,1,'Начислено страховых взносов на обязательное пенсионное страхование:с сумм, не превышающих предельную базу для начисления страховых взносов                                                                                                                    ')
INSERT #F VALUES (4,7,1,'с сумм, превышающих предельную величину базы для начисления страховых взносов                                                                                                                                                                                 ')
INSERT #F VALUES (4,8,1,'Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы в соответствии с тарифом страховых взносов, всего (чел.)                                                                                                         ')
INSERT #F VALUES (4,9,1,'в том числе количество физических лиц, выплаты и иные вознаграждения которым превысили предельную величину базы для начисления страховых взносов  (чел.)                                                                                                      ')
INSERT #F VALUES (4,10,1,'Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009г. 
№ 212-ФЗ и в соответствии с международными договорами                                                             ')
INSERT #F VALUES (4,11,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии с частями 1, 2 статьи 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с международными договорами                                                                        ')
INSERT #F VALUES (4,12,1,'Сумма расходов, принимаемых к вычету в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                                       ')
INSERT #F VALUES (4,13,1,'Суммы выплат и иных вознаграждений, превышающие предельную величину базы для начисления страховых взносов                                                                                                                                                     ')
INSERT #F VALUES (4,15,1,'Начислено страховых взносов на обязательное медицинское страхование                                                                                                                                                                                           ')
INSERT #F VALUES (4,14,1,'База для начисления страховых взносов на обязательное медицинское страхование (с. 210 - с. 211 - с. 212 - с. 213)                                                                                                                                             ')
INSERT #F VALUES (4,1,2,'2000                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,2,2,'2010                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,3,2,'2020                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,4,2,'2030                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,5,2,'2040                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,6,2,'2050                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,7,2,'2060                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,8,2,'2070                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,9,2,'2080                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,10,2,'2100                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,11,2,'2110                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,12,2,'2120                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,13,2,'2130                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,15,2,'2150                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,14,2,'2140                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,1,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,2,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,3,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,4,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,6,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,7,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,8,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,9,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,10,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,11,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,12,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,13,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,15,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,2,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,3,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,4,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,6,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,7,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,8,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,9,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,10,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,11,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,12,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,13,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,15,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,1,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,2,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,3,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,4,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,6,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,7,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,8,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,9,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,10,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,11,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,12,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,13,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,15,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,1,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,2,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,3,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,4,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,6,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,7,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,8,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,9,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,10,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,11,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,12,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,13,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,15,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,1,1,'Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ  (по доп.тарифу 1)                                                                                        ')
INSERT #F VALUES (5,2,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. 
№ 212-ФЗ (по доп тарифу 1)                                                                                                            ')
INSERT #F VALUES (5,3,1,'База для начисления страховых взносов по дополнительному тарифу 1(с. 220 - с. 221)                                                                                                                                                                            ')
INSERT #F VALUES (5,4,1,'Начислено страховых взносов по дополнительному тарифу 1                                                                                                                                                                                                       ')
INSERT #F VALUES (5,5,1,'Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу 1 (чел.)                                                                                                                               ')
INSERT #F VALUES (5,6,1,'Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ (по доп тарифу 2)                                                                                         ')
INSERT #F VALUES (5,7,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ (по доп тарифу 2)                                                                                                              ')
INSERT #F VALUES (5,8,1,'База для начисления страховых взносов по дополнительному тарифу 2 (с. 230 - с. 231)                                                                                                                                                                           ')
INSERT #F VALUES (5,9,1,'Начислено страховых взносов по дополнительному тарифу 2                                                                                                                                                                                                       ')
INSERT #F VALUES (5,10,1,'Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу 2 (чел.)                                                                                                                               ')
INSERT #F VALUES (5,1,2,'220                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,2,2,'221                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,3,2,'223                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,4,2,'224                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,5,2,'225                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,6,2,'230                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,7,2,'231                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,8,2,'233                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,9,2,'234                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,10,2,'235                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,1,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,2,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,4,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,5,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,6,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,7,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,9,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,10,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,2,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,4,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,5,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,6,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,7,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,9,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,10,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,1,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,2,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,4,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,5,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,6,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,7,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,9,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,10,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,1,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,2,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,4,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,5,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,6,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,7,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,9,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,10,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,1,1,'4 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                         ')
INSERT #F VALUES (6,2,1,'4 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                              ')
INSERT #F VALUES (6,5,1,'4 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                               ')
INSERT #F VALUES (6,6,1,'3.4 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                       ')
INSERT #F VALUES (6,7,1,'3.4 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                            ')
INSERT #F VALUES (6,10,1,'3.4 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                             ')
INSERT #F VALUES (6,11,1,'3.3 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                       ')
INSERT #F VALUES (6,12,1,'3.3 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                            ')
INSERT #F VALUES (6,15,1,'3.3 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                             ')
INSERT #F VALUES (6,16,1,'3.2 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                       ')
INSERT #F VALUES (6,17,1,'3.2 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                            ')
INSERT #F VALUES (6,19,1,'3.2 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                              ')
INSERT #F VALUES (6,20,1,'3.2 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                             ')
INSERT #F VALUES (6,21,1,'3.1 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                       ')
INSERT #F VALUES (6,22,1,'3.1 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                            ')
INSERT #F VALUES (6,24,1,'3.1 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                              ')
INSERT #F VALUES (6,25,1,'3.1 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                             ')
INSERT #F VALUES (6,3,1,'4 База для начисления страховых взносов по дополнительному тарифу  (с. 240 - с. 241)                                                                                                                                                                          ')
INSERT #F VALUES (6,4,1,'4 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                                ')
INSERT #F VALUES (6,8,1,'3.4 База для начисления страховых взносов по дополнительному тарифу  (с. 246 - с. 247)                                                                                                                                                                        ')
INSERT #F VALUES (6,9,1,'3.4 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                              ')
INSERT #F VALUES (6,13,1,'3.3 База для начисления страховых взносов по дополнительному тарифу  (с. 252 - с. 253)                                                                                                                                                                        ')
INSERT #F VALUES (6,14,1,'3.3 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                              ')
INSERT #F VALUES (6,18,1,'3.2 База для начисления страховых взносов по дополнительному тарифу  (с. 258 - с. 259)                                                                                                                                                                        ')
INSERT #F VALUES (6,23,1,'3.1 База для начисления страховых взносов по дополнительному тарифу  (с. 264 - с. 265)                                                                                                                                                                        ')
INSERT #F VALUES (6,1,2,'240                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,2,2,'241                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,5,2,'245                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,6,2,'246                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,7,2,'247                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,10,2,'251                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,11,2,'252                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,12,2,'253                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,15,2,'257                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,16,2,'258                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,17,2,'259                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,19,2,'262                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,20,2,'263                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,21,2,'264                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,22,2,'265                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,24,2,'268                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,25,2,'269                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,3,2,'243                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,4,2,'244                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,8,2,'249                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,9,2,'250                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,13,2,'255                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,14,2,'256                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,18,2,'261                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,23,2,'267                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,1,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,2,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,5,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,6,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,7,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,10,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,11,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,12,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,15,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,16,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,17,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,19,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,20,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,21,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,22,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,24,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,25,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,4,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,9,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,14,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,2,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,5,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,6,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,7,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,10,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,11,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,12,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,15,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,16,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,17,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,19,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,20,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,21,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,22,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,24,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,25,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,4,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,9,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,14,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,1,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,2,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,5,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,6,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,7,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,10,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,11,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,12,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,15,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,16,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,17,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,19,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,20,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,21,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,22,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,24,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,25,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,4,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,9,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,14,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,1,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,2,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,5,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,6,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,7,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,10,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,11,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,12,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,15,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,16,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,17,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,19,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,20,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,21,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,22,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,24,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,25,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,4,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,9,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,14,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,1,1,'4 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                         ')
INSERT #F VALUES (7,2,1,'4 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                              ')
INSERT #F VALUES (7,5,1,'4 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                               ')
INSERT #F VALUES (7,6,1,'3.4 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                       ')
INSERT #F VALUES (7,7,1,'3.4 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                            ')
INSERT #F VALUES (7,10,1,'3.4 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                             ')
INSERT #F VALUES (7,11,1,'3.3 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                       ')
INSERT #F VALUES (7,12,1,'3.3 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                            ')
INSERT #F VALUES (7,15,1,'3.3 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                             ')
INSERT #F VALUES (7,16,1,'3.2 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                       ')
INSERT #F VALUES (7,17,1,'3.2 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                            ')
INSERT #F VALUES (7,19,1,'3.2 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                              ')
INSERT #F VALUES (7,20,1,'3.2 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                             ')
INSERT #F VALUES (7,21,1,'3.1 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                       ')
INSERT #F VALUES (7,22,1,'3.1 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                            ')
INSERT #F VALUES (7,24,1,'3.1 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                              ')
INSERT #F VALUES (7,25,1,'3.1 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                             ')
INSERT #F VALUES (7,3,1,'4 База для начисления страховых взносов по дополнительному тарифу  (с. 240 - с. 241)                                                                                                                                                                          ')
INSERT #F VALUES (7,4,1,'4 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                                ')
INSERT #F VALUES (7,8,1,'3.4 База для начисления страховых взносов по дополнительному тарифу  (с. 246 - с. 247)                                                                                                                                                                        ')
INSERT #F VALUES (7,9,1,'3.4 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                              ')
INSERT #F VALUES (7,13,1,'3.3 База для начисления страховых взносов по дополнительному тарифу  (с. 252 - с. 253)                                                                                                                                                                        ')
INSERT #F VALUES (7,14,1,'3.3 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                              ')
INSERT #F VALUES (7,18,1,'3.2 База для начисления страховых взносов по дополнительному тарифу  (с. 258 - с. 259)                                                                                                                                                                        ')
INSERT #F VALUES (7,23,1,'3.1 База для начисления страховых взносов по дополнительному тарифу  (с. 264 - с. 265)                                                                                                                                                                        ')
INSERT #F VALUES (7,1,2,'2400                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,2,2,'2410                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,5,2,'2450                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,6,2,'2460                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,7,2,'2470                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,10,2,'2510                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,11,2,'2520                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,12,2,'2530                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,15,2,'2570                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,16,2,'2580                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,17,2,'2590                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,19,2,'2620                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,20,2,'2630                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,21,2,'2640                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,22,2,'2650                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,24,2,'2680                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,25,2,'2690                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,3,2,'2430                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,4,2,'2440                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,8,2,'2490                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,9,2,'2500                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,13,2,'2550                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,14,2,'2560                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,18,2,'2610                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,23,2,'2670                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,1,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,2,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,5,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,6,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,7,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,10,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,11,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,12,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,15,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,16,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,17,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,19,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,20,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,21,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,22,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,24,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,25,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,4,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,9,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,14,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,2,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,5,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,6,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,7,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,10,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,11,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,12,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,15,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,16,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,17,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,19,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,20,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,21,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,22,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,24,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,25,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,4,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,9,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,14,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,1,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,2,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,5,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,6,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,7,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,10,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,11,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,12,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,15,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,16,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,17,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,19,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,20,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,21,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,22,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,24,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,25,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,4,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,9,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,14,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,1,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,2,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,5,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,6,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,7,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,10,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,11,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,12,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,15,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,16,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,17,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,19,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,20,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,21,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,22,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,24,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,25,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,4,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,9,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,14,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (10,1,1,'Численность членов организации, всего (чел.)                                                                                                                                                                                                                  ')
INSERT #F VALUES (10,2,1,'       из них:
численность инвалидов и их законных представителей (чел.)                                                                                                                                                                                     ')
INSERT #F VALUES (10,3,1,'Удельный вес численности инвалидов и их законных представителей в численности членов организации (%) (с. 322 / с. 321) х 100
(с. 322 / с. 321) х 100                                                                                                         ')
INSERT #F VALUES (10,4,1,'Среднесписочная численность физических лиц, всего (чел.)                                                                                                                                                                                                      ')
INSERT #F VALUES (10,5,1,'из них: среднесписочная численность инвалидов (чел.)                                                                                                                                                                                                          ')
INSERT #F VALUES (10,7,1,'Фонд оплаты труда, всего (в рублях)                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,8,1,'из них: заработная плата инвалидов (в рублях)                                                                                                                                                                                                                 ')
INSERT #F VALUES (10,6,1,'Удельный вес инвалидов в среднесписочной численности (%) (с. 332 / с. 331) х 100                                                                                                                                                                              ')
INSERT #F VALUES (10,9,1,'Удельный вес заработной платы инвалидов (%) (с. 335 / с. 334) х 100                                                                                                                                                                                           ')
INSERT #F VALUES (10,1,2,'321                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,2,2,'322                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,3,2,'323                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,4,2,'331                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,5,2,'332                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,7,2,'334                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,8,2,'335                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,6,2,'333                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,9,2,'336                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,4,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (10,5,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (10,4,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (10,5,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (10,4,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (10,5,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (10,4,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (10,5,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (11,1,1,'Сумма доходов, определяемая в соответствии со статьей 248 Налогового кодекса Российской Федерации*, всего (в рублях)                                                                                                                                          ')
INSERT #F VALUES (11,2,1,'      из них:сумма доходов, определяемая исходя из критериев, указанных в пункте 2 части 2.1 или пункте  2 части 2.2 статьи 57 Федерального закона от 24 июля 2009 г. № 212-ФЗ (в рублях)                                                                     ')
INSERT #F VALUES (11,3,1,'Доля доходов, определяемая в целях применения части 5 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%) (с. 342 / с. 341) х 100(с. 342 / с. 341) х 100                                                                                            ')
INSERT #F VALUES (11,4,1,'Средняя численность работников/среднесписочная численность работников (чел.)
среднесписочная численность работников**(чел.)                                                                                                                                  ')
INSERT #F VALUES (11,5,1,'Сведения из реестра аккредитованных организаций, осуществляющих деятельность в
области информационных технологий **                                                                                                                                          ')
INSERT #F VALUES (11,1,2,'341                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,2,2,'342                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,3,2,'343                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,4,2,'344                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,5,2,'345                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (11,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (11,1,5,'ЗАПРЕТ()')
INSERT #F VALUES (11,2,5,'ЗАПРЕТ()')
INSERT #F VALUES (11,3,5,'ЗАПРЕТ()')
INSERT #F VALUES (11,4,5,'ЗАПРЕТ()')
INSERT #F VALUES (11,1,6,'ЗАПРЕТ()')
INSERT #F VALUES (11,2,6,'ЗАПРЕТ()')
INSERT #F VALUES (11,3,6,'ЗАПРЕТ()')
INSERT #F VALUES (11,4,6,'ЗАПРЕТ()')
INSERT #F VALUES (12,1,1,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,2,1,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,3,1,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,4,1,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,5,1,'5                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,6,1,'6                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,7,1,'7                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,8,1,'8                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,9,1,'9                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,10,1,'10                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (12,12,1,'Сведения из реестра СМИ**                                                                                                                                                                                                                                     ')
INSERT #F VALUES (12,11,3,'Итого по всем видам деятельности')
INSERT #F VALUES (12,1,4,'350a                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,2,4,'350b                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,3,4,'350c                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,4,4,'350d                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,5,4,'350e                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,6,4,'350f                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,7,4,'350g                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,8,4,'350h                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,9,4,'350j                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,10,4,'350k                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,11,4,'350l                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,12,4,'351                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (12,12,5,'ЗАПРЕТ()')
INSERT #F VALUES (12,11,6,'ЗАПРЕТ()')
INSERT #F VALUES (12,12,6,'ЗАПРЕТ()')
INSERT #F VALUES (12,1,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,2,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,6,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,7,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,8,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,9,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,10,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,11,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,1,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,2,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,6,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,7,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,8,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,9,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,10,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,11,8,'ЗАПРЕТ()')
INSERT #F VALUES (13,1,1,'Сумма доходов, определяемая в соответствии со статьей 346.15 Налогового кодекса Российской Федерации, всего (в рублях)                                                                                                                                        ')
INSERT #F VALUES (13,2,1,'из них: сумма доходов, определяемая  в целях применения части 1.4 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (в рублях)                                                                                                                        ')
INSERT #F VALUES (13,3,1,'Доля доходов, определяемая  в целях применения части 1.4  статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%)
(с. 362 / с. 361) х 100                                                                                                              ')
INSERT #F VALUES (13,4,1,'Сумма доходов*, всего (в рублях)                                                                                                                                                                                                                              ')
INSERT #F VALUES (13,5,1,'из них:сумма доходов в виде целевых поступлений на содерж. некоммерч. орг. и ведение ими уставной деят-ти, поименованной в п.11 ч.1 ст.58 Федерального закона от 24.07.2009 г. №212-ФЗ,опред. в соответ. с п.2 ст.251  НК РФ (в рублях)                       ')
INSERT #F VALUES (13,6,1,'сумма доходов в виде грантов, получ. для осуществления деят-ти, поименованной в п.11 ч.1 ст.58 № 212-ФЗ от 24 июля 2009 г. определяемых в соответствии с подпунктом 14 пункта 1 статьи 251 НК РФ(в рублях)                                                    ')
INSERT #F VALUES (13,7,1,'сумма доходов от осуществления видов экономической деятельности, указанных в подпунктах «р» - «ф», «я.4» - «я.6» пункта 8 части 1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (в рублях)                                                        ')
INSERT #F VALUES (13,8,1,'Доля доходов, определяемая в целях применения части 5.1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%) (с. 372 + с. 373 + с.374) / с. 371 х 100                                                                                                ')
INSERT #F VALUES (13,1,2,'361                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,2,2,'362                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,3,2,'363                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,4,2,'371                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,5,2,'372                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,6,2,'373                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,7,2,'374                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,8,2,'375                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,4,3,'ЗАПРЕТ()')
INSERT #F VALUES (13,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (13,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (13,7,3,'ЗАПРЕТ()')
INSERT #F VALUES (13,8,3,'ЗАПРЕТ()')
INSERT #F VALUES (13,1,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,2,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,3,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,1,5,'ЗАПРЕТ()')
INSERT #F VALUES (13,2,5,'ЗАПРЕТ()')
INSERT #F VALUES (13,3,5,'ЗАПРЕТ()')
INSERT #F VALUES (16,1,1,'Сведения из реестра молодежных и детских общественных объединений, пользующихся государственной поддержкой                                                                                                                                                    ')
INSERT #F VALUES (16,1,2,'501                                                                                                                                                                                                                                                           ')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 677
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,7,0,0,0,'т.2стр.114гр.3 =  т.2стр.111гр.3 +  т.2стр.112гр.3 +  т.2стр.113гр.3',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(2,NULL,0,NULL,2,7,0,0,0,'т.2стр.114гр.6 =  т.2стр.111гр.6 +  т.2стр.112гр.6 +  т.2стр.113гр.6',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(3,NULL,0,NULL,3,7,0,0,0,'т.2стр.114гр.7 =  т.2стр.111гр.7 +  т.2стр.112гр.7 +  т.2стр.113гр.7',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(4,NULL,0,NULL,4,7,0,0,0,'т.2стр.114гр.8 =  т.2стр.111гр.8 +  т.2стр.112гр.8 +  т.2стр.113гр.8',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(5,NULL,0,NULL,5,7,0,0,0,'т.2стр.130гр.3 =  т.2стр.100гр.3 +  т.2стр.110гр.3 +  т.2стр.120гр.3',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(6,NULL,0,NULL,6,7,0,0,0,'т.2стр.130гр.4 =  т.2стр.100гр.4 +  т.2стр.110гр.4 +  т.2стр.120гр.4',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(7,NULL,0,NULL,7,7,0,0,0,'т.2стр.130гр.5 =  т.2стр.100гр.5 +  т.2стр.110гр.5 +  т.2стр.120гр.5',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(8,NULL,0,NULL,8,7,0,0,0,'т.2стр.130гр.6 =  т.2стр.100гр.6 +  т.2стр.110гр.6 +  т.2стр.120гр.6',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(9,NULL,0,NULL,9,7,0,0,0,'т.2стр.130гр.7 =  т.2стр.100гр.7 +  т.2стр.110гр.7 +  т.2стр.120гр.7',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(10,NULL,0,NULL,10,7,0,0,0,'т.2стр.130гр.8 =  т.2стр.100гр.8 +  т.2стр.110гр.8 +  т.2стр.120гр.8',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(11,NULL,0,NULL,11,7,0,0,0,'т.2стр.144гр.3 =  т.2стр.141гр.3 +  т.2стр.142гр.3 +  т.2стр.143гр.3',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(12,NULL,0,NULL,12,7,0,0,0,'т.2стр.144гр.4 =  т.2стр.141гр.4 +  т.2стр.142гр.4 +  т.2стр.143гр.4',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(13,NULL,0,NULL,13,7,0,0,0,'т.2стр.144гр.5 =  т.2стр.141гр.5 +  т.2стр.142гр.5 +  т.2стр.143гр.5',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(14,NULL,0,NULL,14,7,0,0,0,'т.2стр.144гр.5 =  т.2стр.141гр.5 +  т.2стр.142гр.5 +  т.2стр.143гр.5',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(15,NULL,0,NULL,15,7,0,0,0,'т.2стр.144гр.6 =  т.2стр.141гр.6 +  т.2стр.142гр.6 +  т.2стр.143гр.6',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(16,NULL,0,NULL,16,7,0,0,0,'т.2стр.144гр.7 =  т.2стр.141гр.7 +  т.2стр.142гр.7 +  т.2стр.143гр.7',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(17,NULL,0,NULL,17,7,0,0,0,'т.2стр.144гр.8 =  т.2стр.141гр.8 +  т.2стр.142гр.8 +  т.2стр.143гр.8',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(18,NULL,0,NULL,18,7,0,0,0,'т.2стр.150гр.3 =  т.2стр.130гр.3 -  т.2стр.140гр.3',1,12,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(19,NULL,0,NULL,19,7,0,0,0,'т.2стр.150гр.4 =  т.2стр.130гр.4 -  т.2стр.140гр.4',1,12,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(20,NULL,0,NULL,20,7,0,0,0,'т.2стр.150гр.5 =  т.2стр.130гр.5 -  т.2стр.140гр.5',1,12,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(21,NULL,0,NULL,21,7,0,0,0,'т.2стр.150гр.6 =  т.2стр.130гр.6 -  т.2стр.140гр.6',1,12,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(22,NULL,0,NULL,22,7,0,0,0,'т.2стр.150гр.7 =  т.2стр.130гр.7 -  т.2стр.140гр.7',1,12,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(23,NULL,0,NULL,23,7,0,0,0,'т.2стр.150гр.8 =  т.2стр.130гр.8 -  т.2стр.140гр.8',1,12,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(24,NULL,0,NULL,24,7,0,0,0,'т.2стр.110гр.3 =  т.3стр.205гр.3 +  т.3стр.206гр.3 +  т.4стр.2050гр.3 +  т.4стр.2060гр.3',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(25,NULL,0,NULL,25,7,0,0,0,'т.2стр.110гр.6 =  т.5стр.224гр.3 +  т.6стр.244гр.3 +  т.6стр.250гр.3 +  т.6стр.256гр.3 +  т.6стр.262гр.3 +  т.6стр.268гр.3',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(26,NULL,0,NULL,26,7,0,0,0,'т.2стр.110гр.7 =  т.5стр.234гр.3 +  т.7стр.2440гр.3 +  т.7стр.2500гр.3 +  т.7стр.2560гр.3 +  т.7стр.2620гр.3 +  т.7стр.2680гр.3',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(27,NULL,0,NULL,27,7,0,0,0,'т.2стр.110гр.8 =  т.3стр.215гр.3 +  т.4стр.2150гр.3',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(28,NULL,0,NULL,28,7,0,0,0,'т.2стр.111гр.3 =  т.3стр.205гр.4 +  т.3стр.206гр.4 +  т.4стр.2050гр.4 +  т.4стр.2060гр.4',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(29,NULL,0,NULL,29,7,0,0,0,'т.2стр.112гр.3 =  т.3стр.205гр.5 +  т.3стр.206гр.5 +  т.4стр.2050гр.5 +  т.4стр.2060гр.5',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(30,NULL,0,NULL,30,7,0,0,0,'т.2стр.113гр.3 =  т.3стр.205гр.6 +  т.3стр.206гр.6 +  т.4стр.2050гр.6 +  т.4стр.2060гр.6',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(31,NULL,0,NULL,31,7,0,0,0,'т.2стр.111гр.6 =  т.5стр.224гр.4 +  т.6стр.244гр.4 +  т.6стр.250гр.4 +  т.6стр.256гр.4 +  т.6стр.262гр.4 +  т.6стр.268гр.4',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(32,NULL,0,NULL,32,7,0,0,0,'т.2стр.112гр.6 =  т.5стр.224гр.5 +  т.6стр.244гр.5 +  т.6стр.250гр.5 +  т.6стр.256гр.5 +  т.6стр.262гр.5 +  т.6стр.268гр.5',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(33,NULL,0,NULL,33,7,0,0,0,'т.2стр.113гр.6 =  т.5стр.224гр.6 +  т.6стр.244гр.6 +  т.6стр.250гр.6 +  т.6стр.256гр.6 +  т.6стр.262гр.6 +  т.6стр.268гр.6',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(34,NULL,0,NULL,34,7,0,0,0,'т.2стр.111гр.7 =  т.5стр.234гр.4 +  т.7стр.2440гр.4 +  т.7стр.2500гр.4 +  т.7стр.2560гр.4 +  т.7стр.2620гр.4 +  т.7стр.2680гр.4',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(35,NULL,0,NULL,35,7,0,0,0,'т.2стр.112гр.7 =  т.5стр.234гр.5 +  т.7стр.2440гр.5 +  т.7стр.2500гр.5 +  т.7стр.2560гр.5 +  т.7стр.2620гр.5 +  т.7стр.2680гр.5',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(36,NULL,0,NULL,36,7,0,0,0,'т.2стр.113гр.7 =  т.5стр.234гр.6 +  т.7стр.2440гр.6 +  т.7стр.2500гр.6 +  т.7стр.2560гр.6 +  т.7стр.2620гр.6 +  т.7стр.2680гр.6',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(37,NULL,0,NULL,37,7,0,0,0,'т.2стр.111гр.8 =  т.3стр.215гр.4 +  т.4стр.2150гр.4',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(38,NULL,0,NULL,38,7,0,0,0,'т.2стр.112гр.8 =  т.3стр.215гр.5 +  т.4стр.2150гр.5',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(39,NULL,0,NULL,39,7,0,0,0,'т.2стр.113гр.8 =  т.3стр.215гр.6 +  т.4стр.2150гр.6',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(40,NULL,0,NULL,40,7,0,0,0,'т.3стр.204гр.3 =  т.3стр.200гр.3 -  т.3стр.201гр.3 -  т.3стр.202гр.3 -  т.3стр.203гр.3',1,0,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(41,NULL,0,NULL,41,7,0,0,0,'т.3стр.204гр.4 =  т.3стр.200гр.4 -  т.3стр.201гр.4 -  т.3стр.202гр.4 -  т.3стр.203гр.4',1,0,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(42,NULL,0,NULL,42,7,0,0,0,'т.3стр.204гр.5 =  т.3стр.200гр.5 -  т.3стр.201гр.5 -  т.3стр.202гр.5 -  т.3стр.203гр.5',1,0,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(43,NULL,0,NULL,43,7,0,0,0,'т.3стр.204гр.6 =  т.3стр.200гр.6 -  т.3стр.201гр.6 -  т.3стр.202гр.6 -  т.3стр.203гр.6',1,0,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(44,NULL,0,NULL,44,7,0,0,0,'т.4стр.2040гр.3 =  т.4стр.2000гр.3 -  т.4стр.2010гр.3 -  т.4стр.2020гр.3 -  т.4стр.2030гр.3',1,0,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(45,NULL,0,NULL,45,7,0,0,0,'т.4стр.2040гр.4 =  т.4стр.2000гр.4 -  т.4стр.2010гр.4 -  т.4стр.2020гр.4 -  т.4стр.2030гр.4',1,0,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(46,NULL,0,NULL,46,7,0,0,0,'т.4стр.2040гр.5 =  т.4стр.2000гр.5 -  т.4стр.2010гр.5 -  т.4стр.2020гр.5 -  т.4стр.2030гр.5',1,0,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(47,NULL,0,NULL,47,7,0,0,0,'т.4стр.2040гр.6 =  т.4стр.2000гр.6 -  т.4стр.2010гр.6 -  т.4стр.2020гр.6 -  т.4стр.2030гр.6',1,0,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(48,NULL,0,NULL,48,7,0,0,0,'т.3стр.214гр.3 =  т.3стр.210гр.3 -  т.3стр.211гр.3 -  т.3стр.212гр.3 -  т.3стр.213гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(49,NULL,0,NULL,49,7,0,0,0,'т.3стр.214гр.4 =  т.3стр.210гр.4 -  т.3стр.211гр.4 -  т.3стр.212гр.4 -  т.3стр.213гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(50,NULL,0,NULL,50,7,0,0,0,'т.3стр.214гр.5 =  т.3стр.210гр.5 -  т.3стр.211гр.5 -  т.3стр.212гр.5 -  т.3стр.213гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(51,NULL,0,NULL,51,7,0,0,0,'т.3стр.214гр.6 =  т.3стр.210гр.6 -  т.3стр.211гр.6 -  т.3стр.212гр.6 -  т.3стр.213гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(52,NULL,0,NULL,52,7,0,0,0,'т.4стр.2140гр.3 =  т.4стр.2100гр.3 -  т.4стр.2110гр.3 -  т.4стр.2120гр.3 -  т.4стр.2130гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(53,NULL,0,NULL,53,7,0,0,0,'т.4стр.2140гр.4 =  т.4стр.2100гр.4 -  т.4стр.2110гр.4 -  т.4стр.2120гр.4 -  т.4стр.2130гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(54,NULL,0,NULL,54,7,0,0,0,'т.4стр.2140гр.5 =  т.4стр.2100гр.5 -  т.4стр.2110гр.5 -  т.4стр.2120гр.5 -  т.4стр.2130гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(55,NULL,0,NULL,55,7,0,0,0,'т.4стр.2140гр.6 =  т.4стр.2100гр.6 -  т.4стр.2110гр.6 -  т.4стр.2120гр.6 -  т.4стр.2130гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(56,NULL,0,NULL,56,7,0,0,0,'т.5стр.223гр.3 =  т.5стр.220гр.3 -  т.5стр.221гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(57,NULL,0,NULL,57,7,0,0,0,'т.5стр.223гр.4 =  т.5стр.220гр.4 -  т.5стр.221гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(58,NULL,0,NULL,58,7,0,0,0,'т.5стр.223гр.5 =  т.5стр.220гр.5 -  т.5стр.221гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(59,NULL,0,NULL,59,7,0,0,0,'т.5стр.223гр.6 =  т.5стр.220гр.6 -  т.5стр.221гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(60,NULL,0,NULL,60,7,0,0,0,'т.5стр.233гр.3 =  т.5стр.230гр.3 -  т.5стр.231гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(61,NULL,0,NULL,61,7,0,0,0,'т.5стр.233гр.4 =  т.5стр.230гр.4 -  т.5стр.231гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(62,NULL,0,NULL,62,7,0,0,0,'т.5стр.233гр.5 =  т.5стр.230гр.5 -  т.5стр.231гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(63,NULL,0,NULL,63,7,0,0,0,'т.5стр.233гр.6 =  т.5стр.230гр.6 -  т.5стр.231гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(64,NULL,0,NULL,64,7,0,0,0,'т.6стр.243гр.3 =  т.6стр.240гр.3 -  т.6стр.241гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(65,NULL,0,NULL,65,7,0,0,0,'т.6стр.243гр.4 =  т.6стр.240гр.4 -  т.6стр.241гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(66,NULL,0,NULL,66,7,0,0,0,'т.6стр.243гр.5 =  т.6стр.240гр.5 -  т.6стр.241гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(67,NULL,0,NULL,67,7,0,0,0,'т.6стр.243гр.6 =  т.6стр.240гр.6 -  т.6стр.241гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(68,NULL,0,NULL,68,7,0,0,0,'т.6стр.249гр.3 =  т.6стр.246гр.3 -  т.6стр.247гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(69,NULL,0,NULL,69,7,0,0,0,'т.6стр.249гр.4 =  т.6стр.246гр.4 -  т.6стр.247гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(70,NULL,0,NULL,70,7,0,0,0,'т.6стр.249гр.5 =  т.6стр.246гр.5 -  т.6стр.247гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(71,NULL,0,NULL,71,7,0,0,0,'т.6стр.249гр.6 =  т.6стр.246гр.6 -  т.6стр.247гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(72,NULL,0,NULL,72,7,0,0,0,'т.6стр.255гр.3 =  т.6стр.252гр.3 -  т.6стр.253гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(73,NULL,0,NULL,73,7,0,0,0,'т.6стр.255гр.4 =  т.6стр.252гр.4 -  т.6стр.253гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(74,NULL,0,NULL,74,7,0,0,0,'т.6стр.255гр.5 =  т.6стр.252гр.5 -  т.6стр.253гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(75,NULL,0,NULL,75,7,0,0,0,'т.6стр.255гр.6 =  т.6стр.252гр.6 -  т.6стр.253гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(76,NULL,0,NULL,76,7,0,0,0,'т.6стр.261гр.3 =  т.6стр.258гр.3 -  т.6стр.259гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(77,NULL,0,NULL,77,7,0,0,0,'т.6стр.261гр.4 =  т.6стр.258гр.4 -  т.6стр.259гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(78,NULL,0,NULL,78,7,0,0,0,'т.6стр.261гр.5 =  т.6стр.258гр.5 -  т.6стр.259гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(79,NULL,0,NULL,79,7,0,0,0,'т.6стр.261гр.6 =  т.6стр.258гр.6 -  т.6стр.259гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(80,NULL,0,NULL,80,7,0,0,0,'т.6стр.267гр.3 =  т.6стр.264гр.3 -  т.6стр.265гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(81,NULL,0,NULL,81,7,0,0,0,'т.6стр.267гр.4 =  т.6стр.264гр.4 -  т.6стр.265гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(82,NULL,0,NULL,82,7,0,0,0,'т.6стр.267гр.5 =  т.6стр.264гр.5 -  т.6стр.265гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(83,NULL,0,NULL,83,7,0,0,0,'т.6стр.267гр.6 =  т.6стр.264гр.6 -  т.6стр.265гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(84,NULL,0,NULL,84,7,0,0,0,'т.7стр.2430гр.3 =  т.7стр.2400гр.3 -  т.7стр.2410гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(85,NULL,0,NULL,85,7,0,0,0,'т.7стр.2430гр.4 =  т.7стр.2400гр.4 -  т.7стр.2410гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(86,NULL,0,NULL,86,7,0,0,0,'т.7стр.2430гр.5 =  т.7стр.2400гр.5 -  т.7стр.2410гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(87,NULL,0,NULL,87,7,0,0,0,'т.7стр.2430гр.6 =  т.7стр.2400гр.6 -  т.7стр.2410гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(88,NULL,0,NULL,88,7,0,0,0,'т.7стр.2490гр.3 =  т.7стр.2460гр.3 -  т.7стр.2470гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(89,NULL,0,NULL,89,7,0,0,0,'т.7стр.2490гр.4 =  т.7стр.2460гр.4 -  т.7стр.2470гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(90,NULL,0,NULL,90,7,0,0,0,'т.7стр.2490гр.5 =  т.7стр.2460гр.5 -  т.7стр.2470гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(91,NULL,0,NULL,91,7,0,0,0,'т.7стр.2490гр.6 =  т.7стр.2460гр.6 -  т.7стр.2470гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(92,NULL,0,NULL,92,7,0,0,0,'т.7стр.2550гр.3 =  т.7стр.2520гр.3 -  т.7стр.2530гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(93,NULL,0,NULL,93,7,0,0,0,'т.7стр.2550гр.4 =  т.7стр.2520гр.4 -  т.7стр.2530гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(94,NULL,0,NULL,94,7,0,0,0,'т.7стр.2550гр.5 =  т.7стр.2520гр.5 -  т.7стр.2530гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(95,NULL,0,NULL,95,7,0,0,0,'т.7стр.2550гр.6 =  т.7стр.2520гр.6 -  т.7стр.2530гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(96,NULL,0,NULL,96,7,0,0,0,'т.7стр.2670гр.3 =  т.7стр.2640гр.3 -  т.7стр.2650гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(97,NULL,0,NULL,97,7,0,0,0,'т.7стр.2670гр.4 =  т.7стр.2640гр.4 -  т.7стр.2650гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(98,NULL,0,NULL,98,7,0,0,0,'т.7стр.2670гр.5 =  т.7стр.2640гр.5 -  т.7стр.2650гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(99,NULL,0,NULL,99,7,0,0,0,'т.7стр.2670гр.6 =  т.7стр.2640гр.6 -  т.7стр.2650гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(100,NULL,0,NULL,100,7,0,0,0,'т.10стр.323гр.3 =  т.10стр.322гр.3 /  т.10стр.321гр.3 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(101,NULL,0,NULL,101,7,0,0,0,'т.10стр.323гр.4 =  т.10стр.322гр.4 /  т.10стр.321гр.4 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(102,NULL,0,NULL,102,7,0,0,0,'т.10стр.323гр.5 =  т.10стр.322гр.5 /  т.10стр.321гр.5 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(103,NULL,0,NULL,103,7,0,0,0,'т.10стр.323гр.6 =  т.10стр.322гр.6 /  т.10стр.321гр.6 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(104,NULL,0,NULL,104,7,0,0,0,'т.10стр.333гр.3 =  т.10стр.332гр.3 /  т.10стр.331гр.3 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(105,NULL,0,NULL,105,7,0,0,0,'т.10стр.333гр.4 =  т.10стр.332гр.4 /  т.10стр.331гр.4 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(106,NULL,0,NULL,106,7,0,0,0,'т.10стр.333гр.5 =  т.10стр.332гр.5 /  т.10стр.331гр.5 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(107,NULL,0,NULL,107,7,0,0,0,'т.10стр.333гр.6 =  т.10стр.332гр.6 /  т.10стр.331гр.6 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(108,NULL,0,NULL,108,7,0,0,0,'т.10стр.336гр.3 =  т.10стр.335гр.3 /  т.10стр.334гр.3 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(109,NULL,0,NULL,109,7,0,0,0,'т.10стр.336гр.4 =  т.10стр.335гр.4 /  т.10стр.334гр.4 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(110,NULL,0,NULL,110,7,0,0,0,'т.10стр.336гр.5 =  т.10стр.335гр.5 /  т.10стр.334гр.5 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(111,NULL,0,NULL,111,7,0,0,0,'т.10стр.336гр.6 =  т.10стр.335гр.6 /  т.10стр.334гр.6 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(112,NULL,0,NULL,112,7,0,0,0,'т.11стр.343гр.3 =  т.11стр.342гр.3 /  т.11стр.341гр.3 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(113,NULL,0,NULL,113,7,0,0,0,'т.11стр.343гр.4 =  т.11стр.342гр.4 /  т.11стр.341гр.4 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(114,NULL,0,NULL,114,7,0,0,0,'т.13стр.363гр.3 =  т.13стр.362гр.3 /  т.13стр.361гр.3 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(115,NULL,0,NULL,115,7,0,0,0,'т.13стр.375гр.4 =  т.13стр.372гр.4 +  т.13стр.373гр.4 +  т.13стр.374гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(116,NULL,0,NULL,116,7,0,0,0,'т.13стр.375гр.4 =  т.13стр.375гр.4 /  т.13стр.371гр.4 *  100',1,2,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(117,NULL,0,NULL,117,7,0,0,0,'т.13стр.375гр.5 =  т.13стр.372гр.5 +  т.13стр.373гр.5 +  т.13стр.374гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(118,NULL,0,NULL,118,7,0,0,0,'т.13стр.375гр.5 =  т.13стр.375гр.5 /  т.13стр.371гр.5 *  100',1,2,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(119,NULL,0,NULL,119,7,0,0,0,'т.7стр.2610гр.3 =  т.7стр.2580гр.3 -  т.7стр.2590гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(120,NULL,0,NULL,120,7,0,0,0,'т.7стр.2610гр.4 =  т.7стр.2580гр.4 -  т.7стр.2590гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(121,NULL,0,NULL,121,7,0,0,0,'т.7стр.2610гр.5 =  т.7стр.2580гр.5 -  т.7стр.2590гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(122,NULL,0,NULL,122,7,0,0,0,'т.7стр.2610гр.6 =  т.7стр.2580гр.6 -  т.7стр.2590гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(123,NULL,0,NULL,123,7,0,0,0,'т.12стр.350lгр.5 =  т.12стр.350aгр.5 +  т.12стр.350bгр.5 +  т.12стр.350cгр.5 +  т.12стр.350dгр.5 +  т.12стр.350eгр.5 +  т.12стр.350fгр.5 +  т.12стр.350gгр.5 +  т.12стр.350jгр.5 +  т.12стр.350kгр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 123
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(4,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(5,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(8,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(9,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(10,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(11,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(12,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(13,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(14,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(15,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(16,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(17,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(18,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(19,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(20,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(21,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(22,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(23,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(24,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','205','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','206','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2050','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2060','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(25,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','224','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','244','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','250','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','256','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','262','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','268','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(26,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','234','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2440','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2500','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2560','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2620','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2680','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(27,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','215','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2150','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(28,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','205','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','206','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2050','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2060','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(29,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','205','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','206','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2050','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2060','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(30,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','205','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','206','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2050','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2060','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(31,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','224','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','244','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','250','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','256','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','262','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','268','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(32,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','224','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','244','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','250','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','256','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','262','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','268','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(33,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','224','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','244','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','250','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','256','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','262','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','268','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(34,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','234','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2440','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2500','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2560','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2620','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2680','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(35,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','234','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2440','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2500','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2560','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2620','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2680','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(36,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','234','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2440','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2500','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2560','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2620','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2680','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(37,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','215','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2150','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(38,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','215','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2150','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(39,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','215','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2150','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','204','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(40,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','200','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','203','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','204','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(41,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','200','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','203','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','204','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(42,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','200','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','203','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','204','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(43,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','200','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','203','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2040','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(44,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2000','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2010','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2020','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2030','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2040','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(45,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2000','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2010','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2020','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2030','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2040','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(46,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2000','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2010','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2020','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2030','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2040','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(47,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2000','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2010','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2020','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2030','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','214','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(48,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','210','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','213','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','214','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(49,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','210','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','213','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','214','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(50,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','210','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','213','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','214','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(51,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','210','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','213','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2140','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(52,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2100','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2110','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2120','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2130','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2140','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(53,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2100','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2110','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2120','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2130','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2140','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(54,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2100','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2110','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2120','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2130','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2140','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(55,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2100','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2110','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2120','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2130','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','223','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(56,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','220','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','221','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','223','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(57,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','220','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','221','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','223','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(58,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','220','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','221','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','223','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(59,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','220','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','221','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','233','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(60,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','230','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','231','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','233','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(61,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','230','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','231','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','233','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(62,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','230','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','231','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','233','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(63,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','230','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','231','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','243','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(64,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','240','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','241','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(65,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','243','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(65,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','240','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(65,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','241','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','243','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(66,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','240','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','241','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','243','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(67,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','240','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','241','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(68,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','249','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(68,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','246','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(68,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','247','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(69,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','249','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(69,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','246','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(69,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','247','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(70,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','249','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(70,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','246','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(70,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','247','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(71,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','249','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(71,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','246','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(71,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','247','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','255','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(72,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','252','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','253','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','255','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(73,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','252','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','253','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(74,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','255','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(74,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','252','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(74,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','253','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(75,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','255','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(75,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','252','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(75,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','253','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','261','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(76,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','258','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','259','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','261','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(77,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','258','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','259','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','261','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(78,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','258','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','259','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','261','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(79,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','258','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','259','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','267','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(80,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','264','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','265','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','267','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(81,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','264','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','265','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(82,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','267','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(82,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','264','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(82,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','265','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(83,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','267','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(83,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','264','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(83,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','265','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(84,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2430','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(84,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2400','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(84,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2410','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(85,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2430','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(85,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2400','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(85,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2410','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(86,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2430','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(86,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2400','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(86,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2410','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(87,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2430','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(87,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2400','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(87,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2410','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(88,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2490','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(88,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2460','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(88,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2470','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2490','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(89,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2460','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2470','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2490','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(90,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2460','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2470','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2490','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(91,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2460','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2470','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(92,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2550','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(92,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2520','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(92,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2530','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(93,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2550','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(93,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2520','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(93,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2530','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2550','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(94,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2520','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2530','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2550','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(95,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2520','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2530','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2670','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(96,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2640','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2650','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(97,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2670','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(97,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2640','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(97,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2650','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(98,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2670','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(98,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2640','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(98,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2650','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(99,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2670','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(99,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2640','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(99,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2650','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(100,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','323','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(100,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','322','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(100,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','321','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(100,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(101,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','323','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(101,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','322','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(101,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','321','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(101,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','323','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(102,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','322','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','321','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','323','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(103,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','322','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','321','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','333','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(104,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','332','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','331','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','333','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(105,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','332','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','331','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','333','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(106,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','332','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','331','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','333','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(107,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','332','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','331','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','336','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(108,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','335','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','334','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','336','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(109,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','335','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','334','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','336','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(110,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','335','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','334','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','336','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(111,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','335','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','334','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','343','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(112,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','342','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','341','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','343','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(113,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','342','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','341','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','363','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(114,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','362','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','361','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','375','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(115,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','372','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','373','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','374','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','375','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(116,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','375','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','371','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','375','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(117,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','372','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','373','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','374','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(118,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','375','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(118,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','375','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(118,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','371','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(118,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(119,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2610','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(119,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2580','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(119,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2590','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(120,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2610','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(120,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2580','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(120,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2590','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(121,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2610','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(121,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2580','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(121,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2590','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(122,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2610','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(122,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2580','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(122,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2590','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(123,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350l','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(123,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350a','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(123,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350b','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(123,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350c','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(123,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350d','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(123,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350e','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(123,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350f','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(123,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350g','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(123,9,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350j','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(123,10,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350k','12',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 484
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '3         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'3','Квартальные формы',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2014-04-22 15:06:34.013',121) WHERE [LINK_FORM]=@iLINK_FORM

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
ELSE BEGIN
	DECLARE @vcMessage VARCHAR(8000)
	SELECT @vcMessage = [CURRENT_DATE] FROM #tabStop
	IF @vcMessage = '2014-04-22 15:06:34.013'
	BEGIN
		SELECT @vcMessage = 'Форма РСВ-1 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма РСВ-1 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-04-22 15:06:34.013. Обновление отклонено.'
	END

	 IF OBJECT_ID('tempdb..#tabUpdateMessages') IS NOT NULL
	 BEGIN
		 INSERT #tabUpdateMessages([TXT]) VALUES (@vcMessage)
	 END
	 SELECT @vcMessage
END
GO

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL DROP TABLE #tabInfo
SELECT * FROM #tabErrorLog

IF EXISTS(SELECT * FROM #tabErrorLog)
BEGIN
   ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
END

DROP TABLE #tabErrorLog
DROP TABLE #tabStop

COMMIT TRANSACTION -- Фиксация транзакции.
GO


GO
EXEC X_SET_PROP 'VACATION_MOVE', 'SAVE_OBJECT_METHOD', 'U_SAVE_TABLE_PART(''KU_VACATION_SAVE'', m.cAlias," NUMBER, SQLNULL(DATE), TYPE_LINK, SQLNULL(PERIOD_BEGIN), SQLNULL(PERIOD_END), SQLNULL(DATE_BEGIN),  SQLNULL(DATE_END), null,REASON,null, EMPL_LINK, ORDER_LINK, null,null, VAC_LINK","VACATION")'
GO
GO
