
--BEFORE CODE 06.04.2014
-- Перенос данных табличной части (оборотная сторона) авансового отчета --
-- Изменение связей в таблицах --
DECLARE 
	@COUNT_REC	INT,
	@SQL_EXEC	VARCHAR (8000),
	@OBJ_AO_TAB	INT

SELECT
	@OBJ_AO_TAB = SO.LINK
FROM dbo.S_OBJECTS SO
WHERE SO.CODE = 'BV_DOC_AVANSE_TABLE'
	
SELECT 
	@COUNT_REC = COUNT (*)
FROM dbo.OUT_TABLE_ROW OTR
WHERE OTR.[OBJECT] = @OBJ_AO_TAB

IF @COUNT_REC = 0
BEGIN
	-- Удаляем связь на G_PROV --
	IF EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_G_AVANSE_TABLE_G_PROV]'))
		EXEC ('ALTER TABLE [dbo].[G_AVANSE_TABLE] DROP CONSTRAINT [FK_G_AVANSE_TABLE_G_PROV]')
	
	--Добавление рабочей колонки LINK_AVANSE_T таблицы OUT_TABLE_ROW
	IF COLUMNPROPERTY(object_id('[dbo].[OUT_TABLE_ROW]'), 'LINK_AVANSE_T', 'AllowsNull') is NULL
	   ALTER TABLE [dbo].[OUT_TABLE_ROW] ADD [LINK_AVANSE_T] int NULL 

	-- Вставка новых записей в OUT_TABLE_ROW --
	SET @SQL_EXEC = 
		'INSERT INTO dbo.OUT_TABLE_ROW (LINK_UP,[OBJECT],ORDERS,LINK_OPER,LINK_AVANSE_T)'
		+
		' SELECT GAT.LINK_UP,' + CONVERT (VARCHAR (30), @OBJ_AO_TAB) + ',GAT.NUMBER,NULL,GAT.LINK FROM dbo.G_AVANSE_TABLE GAT'
	EXEC (@SQL_EXEC)

	-- Обновление ссылок --
	SET @SQL_EXEC = 
	'UPDATE T1 SET LINK_UP = OTR.LINK FROM dbo.G_AVANSE_TABLE T1'
	+ ' INNER JOIN dbo.OUT_TABLE_ROW OTR ON (OTR.LINK_AVANSE_T = T1.LINK)'
	+ ' WHERE OTR.[OBJECT] = ' + CONVERT (VARCHAR (30), @OBJ_AO_TAB) 

--	SELECT @SQL_EXEC

	EXEC (@SQL_EXEC)

	-- Удаление рабочей колонки LINK_AVANSE_T таблицы OUT_TABLE_ROW
	IF COLUMNPROPERTY(object_id('[dbo].[OUT_TABLE_ROW]'), 'LINK_AVANSE_T', 'AllowsNull') is NOT NULL
	   EXEC ('ALTER TABLE [dbo].[OUT_TABLE_ROW] DROP COLUMN [LINK_AVANSE_T]')
	   
	-- Установка новой связи --
	IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_G_AVANSE_TABLE_OUT_TABLE_ROW]'))
		ALTER TABLE [dbo].[G_AVANSE_TABLE] WITH NOCHECK 
			ADD CONSTRAINT [FK_G_AVANSE_TABLE_OUT_TABLE_ROW] FOREIGN KEY ([LINK_UP]) REFERENCES [dbo].[OUT_TABLE_ROW] ([LINK])
		ALTER TABLE [dbo].[G_AVANSE_TABLE] NOCHECK CONSTRAINT [FK_G_AVANSE_TABLE_OUT_TABLE_ROW]
	
	-- Переформирование триггеров --
	EXEC dbo.X_UPDATE_DELETE_TRIGGERS	
END		--	IF @COUNT_REC = 0
GO





GO
--Добавление колонки uin_code таблицы finanse_pays
IF COLUMNPROPERTY(object_id('[dbo].[FINANSE_PAYS]'), 'UIN_CODE', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[FINANSE_PAYS] ADD [UIN_CODE] varchar(20) NOT NULL CONSTRAINT [DF_FINANSE_PAYS_UIN_CODE] DEFAULT ('')
GO


GO
--Добавление колонки DED_M таблицы SDOC_ESN_TABLE
IF COLUMNPROPERTY(object_id('[dbo].[SDOC_ESN_TABLE]'), 'PERC', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[SDOC_ESN_TABLE] ADD [PERC] numeric(18, 2) NOT NULL CONSTRAINT [DF_SDOC_ESN_TABLE_PERC] DEFAULT (0)
GO


--Добавление колонки STATUS таблицы SDOC_ESN_TABLE
IF COLUMNPROPERTY(object_id('[dbo].[SDOC_ESN_TABLE]'), 'TARIF', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[SDOC_ESN_TABLE] ADD [TARIF] tinyint NULL
GO

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


IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SDOC_ESN_TABLE_SPECO]'))
ALTER TABLE [dbo].[SDOC_ESN_TABLE] 
ADD CONSTRAINT [FK_SDOC_ESN_TABLE_SPECO] FOREIGN KEY ([SPECO]) REFERENCES [dbo].[SZV4_SPR] ([LINK])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_SDOC_ESN_TABLE_SPECO')
CREATE INDEX [IX_SDOC_ESN_TABLE_SPECO] ON [dbo].[SDOC_ESN_TABLE] ([SPECO]) ON [INDEX]
GO

--Добавление колонки STATUS таблицы CALCULATE_JURNAL
IF COLUMNPROPERTY(object_id('[dbo].[CALCULATE_JURNAL]'), 'TARIF', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[CALCULATE_JURNAL] ADD [TARIF] tinyint NULL
GO

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


IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_CALCULATE_JURNAL_SPECO]'))
ALTER TABLE [dbo].[CALCULATE_JURNAL] 
ADD CONSTRAINT [FK_CALCULATE_JURNAL_SPECO] FOREIGN KEY ([SPECO]) REFERENCES [dbo].[SZV4_SPR] ([LINK])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_CALCULATE_JURNAL_SPECO')
CREATE INDEX [IX_CALCULATE_JURNAL_SPECO] ON [dbo].[CALCULATE_JURNAL] ([SPECO]) ON [INDEX]
GO

GO
-- Авансовый отчет (BV_DOC_AVANSE_REP) --
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AVANSE_REP', 'Авансовый отчет', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DOCUMENTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AVANSE_REP', NAME = 'Авансовый отчет', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DOCUMENTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='BV_DOC_AVANSE_REP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_KBK_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_KBK_LINK', 'Ссылка на КБК', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_KBK_LINK', NAME = 'Ссылка на КБК', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_KBK_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_KBK_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_KBK_CODE', 'Код КБК', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_KBK_CODE', NAME = 'Код КБК', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_KBK_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_KBK_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_KBK_NAME', 'Наименование КБК', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_KBK_NAME', NAME = 'Наименование КБК', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_KBK_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_OTDEL_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_OTDEL_LINK', 'Ссылка на отдел', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_OTDEL_LINK', NAME = 'Ссылка на отдел', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_OTDEL_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_SUBDIV_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_SUBDIV_CODE', 'Код отдела', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_SUBDIV_CODE', NAME = 'Код отдела', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_SUBDIV_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_OTDEL_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_OTDEL_NAME', 'Отдел', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_OTDEL_NAME', NAME = 'Отдел', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_OTDEL_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_OPTION')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_OPTION', 'Сотрудник/физлицо', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_OPTION', NAME = 'Сотрудник/физлицо', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_OPTION'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_EMP_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_EMP_LINK', 'Ссылка на сотрудника', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_EMP_LINK', NAME = 'Ссылка на сотрудника', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_EMP_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_PERS_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_PERS_LINK', 'Ссылка на физ.лицо', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_PERS_LINK', NAME = 'Ссылка на физ.лицо', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_PERS_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_EMP_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_EMP_CODE', 'Код сотрудника', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_EMP_CODE', NAME = 'Код сотрудника', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_EMP_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_EMP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_EMP_NAME', 'ФИО Сотрудника', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_EMP_NAME', NAME = 'ФИО Сотрудника', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_EMP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TARGET')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TARGET', 'Назначение аванса', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TARGET', NAME = 'Назначение аванса', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TARGET'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_PREVSUMMA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_PREVSUMMA', 'Предыдущий аванс', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_PREVSUMMA', NAME = 'Предыдущий аванс', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_PREVSUMMA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_AVANSESUMMA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_AVANSESUMMA', 'Получен аванс', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_AVANSESUMMA', NAME = 'Получен аванс', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_AVANSESUMMA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_ITOG_SUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_ITOG_SUM', 'Итого получено', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_ITOG_SUM', NAME = 'Итого получено', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_ITOG_SUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_KTACCOUNT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_KTACCOUNT', 'кредит счета', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_KTACCOUNT', NAME = 'кредит счета', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_KTACCOUNT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_RASHOD_SUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_RASHOD_SUM', 'Израсходовано', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_RASHOD_SUM', NAME = 'Израсходовано', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_RASHOD_SUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_REST_SUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_REST_SUM', 'Остаток/перерасход', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_REST_SUM', NAME = 'Остаток/перерасход', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_REST_SUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_DOC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_DOC', 'Приложено документов', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_DOC', NAME = 'Приложено документов', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_DOC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_PAGES')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_PAGES', 'На листах', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_PAGES', NAME = 'На листах', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_PAGES'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_KOSUMMA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_KOSUMMA', 'Сумма по ордеру', 21, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_KOSUMMA', NAME = 'Сумма по ордеру', ORDERS = '21', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_KOSUMMA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_KONUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_KONUM', 'Номер ордера', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_KONUM', NAME = 'Номер ордера', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_KONUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_KODATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_KODATE', 'Дата ордера', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_KODATE', NAME = 'Дата ордера', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_KODATE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_KO_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_KO_LINK', 'Ссылка на КО', 24, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_KO_LINK', NAME = 'Ссылка на КО', ORDERS = '24', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_KO_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_KO_LINK_PKO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_KO_LINK_PKO', 'Ссылка на ПКО', 25, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_KO_LINK_PKO', NAME = 'Ссылка на ПКО', ORDERS = '25', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_KO_LINK_PKO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_KO_LINK_RKO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_KO_LINK_RKO', 'Ссылка на РКО', 26, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_KO_LINK_RKO', NAME = 'Ссылка на РКО', ORDERS = '26', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_KO_LINK_RKO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AVANSE_TABLE', 'Таблица авансового отчета', 27, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AVANSE_TABLE', NAME = 'Таблица авансового отчета', ORDERS = '27', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AVANSE_TABLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_OPTIONS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_OPTIONS', 'Настройки АО', 28, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_OPTIONS', NAME = 'Настройки АО', ORDERS = '28', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_OPTIONS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_TABLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_AO_RKO_TABLE', 'Документы на получение аванса', 30, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_AO_RKO_TABLE', NAME = 'Документы на получение аванса', ORDERS = '30', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_AO_RKO_TABLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_KO_TABLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_KO_TABLE', 'Список КО', 29, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_KO_TABLE', NAME = 'Список КО', ORDERS = '29', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_REP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='BV_DOC_AO_KO_TABLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_NUMBER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_NUMBER', 'Номер строки', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_NUMBER', NAME = 'Номер строки', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_NUMBER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_DATEDOC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_DATEDOC', 'Дата документа', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_DATEDOC', NAME = 'Дата документа', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_DATEDOC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_NUMDOC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_NUMDOC', 'Номер документа', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_NUMDOC', NAME = 'Номер документа', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_NUMDOC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_NAMEDOC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_NAMEDOC', 'Наименование документа', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_NAMEDOC', NAME = 'Наименование документа', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_NAMEDOC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_SUMREPORT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_SUMREPORT', 'Сумма расходов по отчету', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_SUMREPORT', NAME = 'Сумма расходов по отчету', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_SUMREPORT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_SUMACCEPTED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_SUMACCEPTED', 'Сумма расходов принятая', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_SUMACCEPTED', NAME = 'Сумма расходов принятая', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_SUMACCEPTED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_DTACCOUNT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_DTACCOUNT', 'Дебет субсчета', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_DTACCOUNT', NAME = 'Дебет субсчета', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_DTACCOUNT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_EKR_LINK_DT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_EKR_LINK_DT', 'Ссылка на ЭКР Дт', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_EKR_LINK_DT', NAME = 'Ссылка на ЭКР Дт', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_EKR_LINK_DT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_EKR_CODE_DT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_EKR_CODE_DT', 'Код ЭКР Дт', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_EKR_CODE_DT', NAME = 'Код ЭКР Дт', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_EKR_CODE_DT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_EKR_NAME_DT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_EKR_NAME_DT', 'Наименование ЭКР Дт', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_EKR_NAME_DT', NAME = 'Наименование ЭКР Дт', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_EKR_NAME_DT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_KTACCOUNT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_KTACCOUNT', 'Кредит субсчета', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_KTACCOUNT', NAME = 'Кредит субсчета', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_KTACCOUNT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_EKR_LINK_KT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_EKR_LINK_KT', 'Ссылка на ЭКР Кт', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_EKR_LINK_KT', NAME = 'Ссылка на ЭКР Кт', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_EKR_LINK_KT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_EKR_CODE_KT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_EKR_CODE_KT', 'Код ЭКР Кт', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_EKR_CODE_KT', NAME = 'Код ЭКР Кт', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_EKR_CODE_KT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_EKR_NAME_KT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_EKR_NAME_KT', 'Наименование ЭКР Кт', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_EKR_NAME_KT', NAME = 'Наименование ЭКР Кт', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_EKR_NAME_KT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_SUM_NDFL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_SUM_NDFL', 'Сумма НДФЛ', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_SUM_NDFL', NAME = 'Сумма НДФЛ', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_SUM_NDFL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_SUM_VZNOS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_SUM_VZNOS', 'Сумма взносов на страхование', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_SUM_VZNOS', NAME = 'Сумма взносов на страхование', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_SUM_VZNOS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_EMP_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_EMP_LINK', 'Ссылка на МОЛ', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_EMP_LINK', NAME = 'Ссылка на МОЛ', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_EMP_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_EMP_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_EMP_CODE', 'Код МОЛ', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_EMP_CODE', NAME = 'Код МОЛ', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_EMP_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_EMP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_EMP_NAME', 'ФИО МОЛ', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_EMP_NAME', NAME = 'ФИО МОЛ', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_EMP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_MZ_TYPE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_MZ_TYPE', 'Тип МЗ', 21, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_MZ_TYPE', NAME = 'Тип МЗ', ORDERS = '21', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_MZ_TYPE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_MZ_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_MZ_LINK', 'Ссылка на ОС', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_MZ_LINK', NAME = 'Ссылка на ОС', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_MZ_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_MZ_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_MZ_CODE', 'Код ОС', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_MZ_CODE', NAME = 'Код ОС', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_MZ_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_MZ_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_MZ_NAME', 'Наименование ОС', 24, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_MZ_NAME', NAME = 'Наименование ОС', ORDERS = '24', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_MZ_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_TABLE_QTY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_TABLE_QTY', 'Количество', 25, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_TABLE_QTY', NAME = 'Количество', ORDERS = '25', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AVANSE_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_TABLE_QTY'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_AO_OPT_TYP_LINK_PKO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_AO_OPT_TYP_LINK_PKO', 'Ссылка на операцию ПКО', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AO_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_AO_OPT_TYP_LINK_PKO', NAME = 'Ссылка на операцию ПКО', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AO_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_AO_OPT_TYP_LINK_PKO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_AO_OPT_TYP_NAME_PKO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_AO_OPT_TYP_NAME_PKO', 'Наим тип. опер. ПКО', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AO_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_AO_OPT_TYP_NAME_PKO', NAME = 'Наим тип. опер. ПКО', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AO_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_AO_OPT_TYP_NAME_PKO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_AO_OPT_TYP_LINK_RKO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_AO_OPT_TYP_LINK_RKO', 'Ссылка на операцию РКО', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AO_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_AO_OPT_TYP_LINK_RKO', NAME = 'Ссылка на операцию РКО', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AO_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_AO_OPT_TYP_LINK_RKO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_AO_OPT_TYP_NAME_RKO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_AO_OPT_TYP_NAME_RKO', 'Наим тип. опер. РКО', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AO_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_AO_OPT_TYP_NAME_RKO', NAME = 'Наим тип. опер. РКО', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AO_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_AO_OPT_TYP_NAME_RKO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_AO_OPT_PRN_TITLE_PROV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_AO_OPT_PRN_TITLE_PROV', 'На титульном листе печатать проводки на получение аванса', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AO_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_AO_OPT_PRN_TITLE_PROV', NAME = 'На титульном листе печатать проводки на получение аванса', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AO_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_AO_OPT_PRN_TITLE_PROV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_KO_TABLE_KO_TYPE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_KO_TABLE_KO_TYPE', 'Тип КО', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AO_KO_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_KO_TABLE_KO_TYPE', NAME = 'Тип КО', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AO_KO_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_KO_TABLE_KO_TYPE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BV_DOC_AO_KO_TABLE_KO_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BV_DOC_AO_KO_TABLE_KO_NAME', 'Вид документа', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AO_KO_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BV_DOC_AO_KO_TABLE_KO_NAME', NAME = 'Вид документа', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BV_DOC_AO_KO_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BV_DOC_AO_KO_TABLE_KO_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_T_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_AO_RKO_T_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_AO_RKO_T_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_AO_RKO_T_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_T_OSNOV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_AO_RKO_T_OSNOV', 'Ссылка на основание', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_AO_RKO_T_OSNOV', NAME = 'Ссылка на основание', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_AO_RKO_T_OSNOV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_T_NUMBER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_AO_RKO_T_NUMBER', 'Номер документа', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_AO_RKO_T_NUMBER', NAME = 'Номер документа', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_AO_RKO_T_NUMBER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_T_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_AO_RKO_T_DATE', 'Дата документа', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_AO_RKO_T_DATE', NAME = 'Дата документа', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_AO_RKO_T_DATE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_T_DATE_PROV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_AO_RKO_T_DATE_PROV', 'Дата проведения', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_AO_RKO_T_DATE_PROV', NAME = 'Дата проведения', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_AO_RKO_T_DATE_PROV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_T_DOC_TYPE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_AO_RKO_T_DOC_TYPE', 'Вид документа', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_AO_RKO_T_DOC_TYPE', NAME = 'Вид документа', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_AO_RKO_T_DOC_TYPE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_T_COMMENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_AO_RKO_T_COMMENT', 'Комментарий', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_AO_RKO_T_COMMENT', NAME = 'Комментарий', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_AO_RKO_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_AO_RKO_T_COMMENT'
GO
EXEC X_SET_PROP 'BV_DOC_AVANSE_REP', 'TITLE', 'Авансовый отчет'
GO
EXEC X_SET_PROP 'BV_DOC_AVANSE_REP', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS (m.cAlias,"BV_DOC_AVANSE_REP", "BV_DELETE_DOCUMENTS", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'BV_DOC_AVANSE_REP', 'SAVE_OBJECT_METHOD', 'X_SAVE(''X_SAVE_BV_DOC_AVANSE_REP'', m.cAlias,"NUMBER, SQLNULL(DATE), SQLNULL(DATE_PROV), SUMMA, COMMENT, SQLNULL(DEP_LINK), SQLNULL(KBK_LINK), SQLNULL(OTDEL_LINK), SQLNULL(EMP_LINK), TARGET, PREVSUMMA, AVANSESUMMA, ITOG_SUM, KTACCOUNT, RASHOD_SUM, REST_SUM, DOC, PAGES"+", KOSUMMA, KONUM, SQLNULL(KODATE), OPTION","BV_DOC_AVANSE_REP")'
GO
EXEC X_SET_PROP 'BV_DOC_AVANSE_REP', 'PRINT_OBJECT_METHOD', 'BK_PRINT_WITH_SQL_PROC ("dbo.BK_PRINTDOC_AVANSE_REP")'
GO
EXEC X_SET_PROP 'BV_DOC_AVANSE_REP', 'EDIT_OBJECT_METHOD', 'bdoc_brow(''BV_DOC_AVANSE_REP'')'
GO
EXEC X_SET_PROP 'BV_DOC_AVANSE_REP', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_LIST_ZB("BV_DOC_AVANSE_REP")'
GO
EXEC X_SET_PROP 'BV_DOC_AVANSE_REP', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST("BV_DOC_AVANSE_REP")'
GO
EXEC X_SET_PROP 'BV_DOC_AVANSE_REP', 'SNAME', 'Аванс. отч.'
GO
EXEC X_SET_PROP 'BV_DOC_AVANSE_REP', 'QUERY_REPMAKER', 'KirRepMakerMultiSheet.xls'
GO
EXEC X_SET_PROP 'BV_DOC_AVANSE_REP', 'QUERY_REPORT', 'AO_F0504049.XLT'
GO
EXEC X_SET_PROP 'BV_DOC_AVANSE_REP', 'OPTIONS_OBJECT_CODE', 'BV_DOC_AO_OPTIONS'
GO
EXEC X_SET_PROP 'BV_DOC_AVANSE_REP', 'HELP_TOPIC', '51'
GO
EXEC X_SET_PROP 'BV_DOC_AVANSE_REP', 'QUERY_ADD_MODULE', 'AO_F0504049.BAS'
GO
EXEC X_SET_PROP 'BV_DOC_AVANSE_REP', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'BV_DOC_AVANSE_REP', 'CREATE_PROV_SQL', 'BV_SAVE_G_PROV1_AVANSE_REP#КО!BB_DOC_AVANSE_KO(oForm)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_LINK', 'TITLE', 'КБК'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_LINK', 'STORAGE', 'KL_KBK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_LINK', 'REFERENCE_TO_DICT', 'BI_DICTION_KBK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_LINK', 'SHORT_CODE_OBJ', 'KBK_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_CODE', 'TITLE', 'Код КБК'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_CODE', 'EDIT_OBJECT_METHOD', 'X_VALID_HEAD_AP(A_VIBOR_01 ("BI_DICTION_KBK", oForm.ALIAS, "LINK,NAME,CODE", "KBK_LINK, KBK_NAME, KBK_CODE", "", "", "TYPE & 2 <> 2", .T., 1, oForm, oObj), oForm, oObj)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_CODE', 'CONTROLSOURCE', 'm.cAlias+''.KBK_CODE'''
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_CODE', 'STORAGE', 'KL_KBK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_CODE', 'REFERENCE_TO_DICT', 'BV_DOC_AO_KBK_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_CODE', 'TYPE_FIELD_DICT', 'varchar(21)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_CODE', 'SHORT_CODE_OBJ', 'KBK_CODE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.KBK_CODE'''
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_CODE', 'CONTROL_NAME_EDIT', 'ASel_Spr11'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_NAME', 'TITLE', 'КБК'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_NAME', 'CONTROLSOURCE', 'm.cAlias+".KBK_NAME"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_NAME', 'STORAGE', 'KL_KBK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_NAME', 'REFERENCE_TO_DICT', 'BV_DOC_AO_KBK_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_NAME', 'TYPE_FIELD_DICT', 'varchar(250)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_NAME', 'SHORT_CODE_OBJ', 'KBK_NAME'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".KBK_NAME"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_NAME', 'CONTROL_NAME_EDIT', 'ATXTN11'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KBK_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OTDEL_LINK', 'TITLE', 'Подразделение'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OTDEL_LINK', 'STORAGE', 'SUBDIV'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OTDEL_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_SUBDIVISION'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OTDEL_LINK', 'SHORT_CODE_OBJ', 'OTDEL_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OTDEL_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_SUBDIV_CODE', 'EDIT_OBJECT_METHOD', 'X_VALID_HEAD_AP(A_VIBOR_01 ("DICTIONARY_SUBDIVISION", oForm.ALIAS, "subdiv_link,NAME,CODE", "OTDEL_LINK, OTDEL_NAME, OTDEL_CODE", "", "", "", .T., 1, oForm, oObj), oForm, oObj)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_SUBDIV_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BV_DOC_AO_SUBDIV_CODE', 'CONTROLSOURCE', 'm.cAlias+''.OTDEL_CODE'''
GO
EXEC X_SET_PROP 'BV_DOC_AO_SUBDIV_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_SUBDIV_CODE', 'STORAGE', 'SUBDIV'
GO
EXEC X_SET_PROP 'BV_DOC_AO_SUBDIV_CODE', 'REFERENCE_TO_DICT', 'BV_DOC_AO_OTDEL_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_SUBDIV_CODE', 'TYPE_FIELD_DICT', 'varChar(5)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_SUBDIV_CODE', 'SHORT_CODE_OBJ', 'OTDEL_CODE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_SUBDIV_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.OTDEL_CODE'''
GO
EXEC X_SET_PROP 'BV_DOC_AO_SUBDIV_CODE', 'CONTROL_NAME_EDIT', 'ASel_Spr1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_SUBDIV_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OTDEL_NAME', 'TITLE', 'Отдел'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OTDEL_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OTDEL_NAME', 'CONTROLSOURCE', 'm.cAlias+".OTDEL_NAME"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OTDEL_NAME', 'STORAGE', 'SUBDIV'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OTDEL_NAME', 'REFERENCE_TO_DICT', 'BV_DOC_AO_OTDEL_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OTDEL_NAME', 'TYPE_FIELD_DICT', 'varchar(250)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OTDEL_NAME', 'SHORT_CODE_OBJ', 'OTDEL_NAME'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OTDEL_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".OTDEL_NAME"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OTDEL_NAME', 'CONTROL_NAME_EDIT', 'ATXTN1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OTDEL_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OPTION', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OPTION', 'CONTROLSOURCE', 'm.cAlias+''.OPTION'''
GO
EXEC X_SET_PROP 'BV_DOC_AO_OPTION', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OPTION', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OPTION', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OPTION', 'SHORT_CODE_OBJ', 'OPTION'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OPTION', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.OPTION'''
GO
EXEC X_SET_PROP 'BV_DOC_AO_OPTION', 'CONTROL_NAME_EDIT', 'OPTION9'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_LINK', 'TITLE', 'Сотрудник'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_LINK', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_LINK', 'STORAGE', 'EMPL'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_LINK', 'REFERENCE_TO_DICT', 'KU_EMPL_PLACING'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_LINK', 'SHORT_CODE_OBJ', 'EMP_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PERS_LINK', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PERS_LINK', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PERS_LINK', 'REFERENCE_TO_DICT', 'KU_EMPL_PLACING'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PERS_LINK', 'SHORT_CODE_OBJ', 'PERS_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PERS_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_CODE', 'TITLE', 'Сотрудник'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_CODE', 'EDIT_OBJECT_METHOD', 'bv_ao_valid_emp()'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_CODE', 'CONTROLSOURCE', 'm.cAlias+".EMP_CODE"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_CODE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_CODE', 'STORAGE', 'EMPL'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_CODE', 'REFERENCE_TO_DICT', 'BV_DOC_AO_EMP_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_CODE', 'TYPE_FIELD_DICT', 'Char(10)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_CODE', 'SHORT_CODE_OBJ', 'EMP_CODE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".EMP_CODE"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_CODE', 'CONTROL_NAME_EDIT', 'ASel_Spr2'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_CODE', 'REFERENCE_TO_FIELD', 'TAB'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_NAME', 'TITLE', 'Подотч. лицо'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_NAME', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_NAME', 'CONTROLSOURCE', 'm.cAlias+".EMP_NAME"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_NAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_NAME', 'STORAGE', 'EMPL'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_NAME', 'REFERENCE_TO_DICT', 'BV_DOC_AO_EMP_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_NAME', 'TYPE_FIELD_DICT', 'Varchar(100)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_NAME', 'SHORT_CODE_OBJ', 'EMP_NAME'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".EMP_NAME"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_NAME', 'CONTROL_NAME_EDIT', 'ATxtN2'
GO
EXEC X_SET_PROP 'BV_DOC_AO_EMP_NAME', 'REFERENCE_TO_FIELD', 'NAME_EMPL'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TARGET', 'TITLE', 'Назначение'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TARGET', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TARGET', 'CONTROLSOURCE', 'm.cAlias+".TARGET"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TARGET', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TARGET', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TARGET', 'TYPE_FIELD_DICT', 'varchar(100)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TARGET', 'SHORT_CODE_OBJ', 'TARGET'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TARGET', 'CONTROLSOURCE_EDIT', 'm.cAlias+".TARGET"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TARGET', 'CONTROL_NAME_EDIT', 'txtTarget3'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PREVSUMMA', 'TITLE', 'Пред. аванс'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PREVSUMMA', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PREVSUMMA', 'CONTROLSOURCE', 'm.cAlias+".PREVSUMMA"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PREVSUMMA', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PREVSUMMA', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PREVSUMMA', 'TYPE_FIELD_DICT', 'numeric(13,2)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PREVSUMMA', 'SHORT_CODE_OBJ', 'PREVSUMMA'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PREVSUMMA', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PREVSUMMA"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PREVSUMMA', 'CONTROL_NAME_EDIT', 'PrevSumma4'
GO
EXEC X_SET_PROP 'BV_DOC_AO_AVANSESUMMA', 'TITLE', 'Получен аванс'
GO
EXEC X_SET_PROP 'BV_DOC_AO_AVANSESUMMA', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BV_DOC_AO_AVANSESUMMA', 'CONTROLSOURCE', 'm.cAlias+".AVANSESUMMA"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_AVANSESUMMA', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_AVANSESUMMA', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_AVANSESUMMA', 'TYPE_FIELD_DICT', 'numeric(13,2)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_AVANSESUMMA', 'SHORT_CODE_OBJ', 'AVANSESUMMA'
GO
EXEC X_SET_PROP 'BV_DOC_AO_AVANSESUMMA', 'CONTROLSOURCE_EDIT', 'm.cAlias+".AVANSESUMMA"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_AVANSESUMMA', 'CONTROL_NAME_EDIT', 'AvanseSumma5'
GO
EXEC X_SET_PROP 'BV_DOC_AO_ITOG_SUM', 'TITLE', 'Итого получено'
GO
EXEC X_SET_PROP 'BV_DOC_AO_ITOG_SUM', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'BV_DOC_AO_ITOG_SUM', 'CONTROLSOURCE', 'm.cAlias+".ITOG_SUM"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_ITOG_SUM', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_ITOG_SUM', 'TYPE_FIELD_DICT', 'numeric(13,2)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_ITOG_SUM', 'SHORT_CODE_OBJ', 'ITOG_SUM'
GO
EXEC X_SET_PROP 'BV_DOC_AO_ITOG_SUM', 'CONTROLSOURCE_EDIT', 'm.cAlias+".ITOG_SUM"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_ITOG_SUM', 'CONTROL_NAME_EDIT', 'Atextbox13'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KTACCOUNT', 'TITLE', 'кредит счета'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KTACCOUNT', 'EDIT_OBJECT_METHOD', 'a_vibor_01("PLAN_ACCOUNTS_LIST", oForm.Alias, "ACCCODE", "KTACCOUNT", "LINK", "","dbo.AccountsHasNoChild(LINK)=1 AND ZABALANS = 0",  .T., 1, oForm, oObj,''lg_prov_notsbs()'')'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KTACCOUNT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KTACCOUNT', 'CONTROLSOURCE', 'm.cAlias + ".KTACCOUNT"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KTACCOUNT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KTACCOUNT', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KTACCOUNT', 'TYPE_FIELD_DICT', 'VARCHAR(13)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KTACCOUNT', 'SHORT_CODE_OBJ', 'KTACCOUNT'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KTACCOUNT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".KTACCOUNT"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KTACCOUNT', 'CONTROL_NAME_EDIT', 'Atextbox14'
GO
EXEC X_SET_PROP 'BV_DOC_AO_RASHOD_SUM', 'TITLE', 'Израсходовано'
GO
EXEC X_SET_PROP 'BV_DOC_AO_RASHOD_SUM', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'BV_DOC_AO_RASHOD_SUM', 'CONTROLSOURCE', 'm.cAlias+".RASHOD_SUM"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_RASHOD_SUM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_RASHOD_SUM', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_RASHOD_SUM', 'TYPE_FIELD_DICT', 'numeric(13,2)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_RASHOD_SUM', 'SHORT_CODE_OBJ', 'RASHOD_SUM'
GO
EXEC X_SET_PROP 'BV_DOC_AO_RASHOD_SUM', 'CONTROLSOURCE_EDIT', 'm.cAlias+".RASHOD_SUM"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_RASHOD_SUM', 'CONTROL_NAME_EDIT', 'Atextbox15'
GO
EXEC X_SET_PROP 'BV_DOC_AO_REST_SUM', 'TITLE', 'Остаток/перерасход'
GO
EXEC X_SET_PROP 'BV_DOC_AO_REST_SUM', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'BV_DOC_AO_REST_SUM', 'CONTROLSOURCE', 'm.cAlias+".REST_SUM"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_REST_SUM', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_REST_SUM', 'TYPE_FIELD_DICT', 'numeric(13,2)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_REST_SUM', 'SHORT_CODE_OBJ', 'REST_SUM'
GO
EXEC X_SET_PROP 'BV_DOC_AO_REST_SUM', 'CONTROLSOURCE_EDIT', 'm.cAlias+".REST_SUM"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_REST_SUM', 'CONTROL_NAME_EDIT', 'Atextbox16'
GO
EXEC X_SET_PROP 'BV_DOC_AO_DOC', 'TITLE', 'Документов'
GO
EXEC X_SET_PROP 'BV_DOC_AO_DOC', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BV_DOC_AO_DOC', 'CONTROLSOURCE', 'm.cAlias+".DOC"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_DOC', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_DOC', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_DOC', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'BV_DOC_AO_DOC', 'SHORT_CODE_OBJ', 'DOC'
GO
EXEC X_SET_PROP 'BV_DOC_AO_DOC', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DOC"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_DOC', 'CONTROL_NAME_EDIT', 'spnDOC7'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PAGES', 'TITLE', 'на листах'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PAGES', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PAGES', 'CONTROLSOURCE', 'm.cAlias+".PAGES"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PAGES', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PAGES', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PAGES', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PAGES', 'SHORT_CODE_OBJ', 'PAGES'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PAGES', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PAGES"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_PAGES', 'CONTROL_NAME_EDIT', 'spnPages8'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KOSUMMA', 'TITLE', 'Сумма по ордеру'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KOSUMMA', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KOSUMMA', 'CONTROLSOURCE', 'm.cAlias+".KOSUMMA"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KOSUMMA', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KOSUMMA', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KOSUMMA', 'TYPE_FIELD_DICT', 'numeric(13,2)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KOSUMMA', 'SHORT_CODE_OBJ', 'KOSUMMA'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KOSUMMA', 'CONTROLSOURCE_EDIT', 'm.cAlias+".KOSUMMA"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KOSUMMA', 'CONTROL_NAME_EDIT', 'KOSumma9'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KONUM', 'TITLE', 'Номер ордера'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KONUM', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KONUM', 'CONTROLSOURCE', 'm.cAlias+".KONUM"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KONUM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KONUM', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KONUM', 'TYPE_FIELD_DICT', 'varchar(25)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KONUM', 'SHORT_CODE_OBJ', 'KONUM'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KONUM', 'CONTROLSOURCE_EDIT', 'm.cAlias+".KONUM"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KONUM', 'CONTROL_NAME_EDIT', 'KONum'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KODATE', 'TITLE', 'Дата ордера'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KODATE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KODATE', 'CONTROLSOURCE', 'm.cAlias+".KODATE"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KODATE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KODATE', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KODATE', 'TYPE_FIELD_DICT', 'DateTime'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KODATE', 'SHORT_CODE_OBJ', 'KODATE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KODATE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".KODATE"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KODATE', 'CONTROL_NAME_EDIT', 'KODate'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK', 'TITLE', 'Ссылка на КО'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK', 'STORAGE', 'CALCULATE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK', 'SHORT_CODE_OBJ', 'KO_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK', 'CONTROL_NAME_EDIT', 'KO_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK', 'REFERENCE_TO_FIELD', 'dbo.BK_GetKOLinkByAO (LINK)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK_PKO', 'TITLE', 'Ссылка на ПКО'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK_PKO', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK_PKO', 'STORAGE', 'CALCULATE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK_PKO', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK_PKO', 'SHORT_CODE_OBJ', 'PKO_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK_PKO', 'CONTROL_NAME_EDIT', 'KO_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK_PKO', 'REFERENCE_TO_FIELD', 'dbo.BK_GetKOLinkByAO (LINK)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK_RKO', 'TITLE', 'Ссылка на РКО'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK_RKO', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK_RKO', 'STORAGE', 'CALCULATE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK_RKO', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK_RKO', 'SHORT_CODE_OBJ', 'RKO_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK_RKO', 'CONTROL_NAME_EDIT', 'KO_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_LINK_RKO', 'REFERENCE_TO_FIELD', 'dbo.BK_GetKOLinkByAO (LINK)'
GO
EXEC X_SET_PROP 'BV_DOC_AVANSE_TABLE', 'SAVE_OBJECT_METHOD', 'BV_AVANSE_SAVE_TABLE(m.cAlias, m.nLink)'
GO
EXEC X_SET_PROP 'BV_DOC_AVANSE_TABLE', 'SELECT_RECORDS_METHOD', 'BV_AVANSE_SELECT_TABLE(m.cAlias, m.nLink)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OPTIONS', 'TITLE', 'Настройки АО'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OPTIONS', 'SAVE_OBJECT_METHOD', 'X_SAVE_DOCUMENT_OPTIONS()'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OPTIONS', 'EDIT_OBJECT_METHOD', 'bdoc_brow(''bk_ao_doc_options'')'
GO
EXEC X_SET_PROP 'BV_DOC_AO_OPTIONS', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_OPTIONS(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_TABLE', 'TITLE', 'Документы на получение аванса'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_TABLE', 'SAVE_OBJECT_METHOD', 'X_SAVE(''X_SAVE_DOC_AO_RKO_TABLE'', m.cAlias,''SQLNULL(LINK_UP), ORDERS, OSNOV'',"DOC_AO_RKO_TABLE")'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_TABLE', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOC_TABLE_LIST ("DOC_AO_RKO_TABLE")'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_TABLE', 'SERVER_TABLE_NAME', 'OUT_TABLE_ROW'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_TABLE', 'TITLE', 'Список кассовых ордеров к авансовому отчету'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_TABLE', 'INIT_OBJECT_METHOD', 'BK_AO_SPISOK_KO (m.Obj_Code)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_TABLE', 'EDIT_OBJECT_METHOD', 'X_USER_DOC_CALL_DOCUMENT(m.nLink)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_TABLE', 'SELECT_RECORDS_METHOD', 'BK_AO_SELECT_LIST ()'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_TABLE', 'SELECT_RECORDS_METHOD_EDIT', 'BK_AO_SELECT_LIST ()'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_TABLE', 'SNAME', 'Список КО'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_TABLE', 'OPERATION_MASK', '8'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_CHECKED', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_CHECKED', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_CHECKED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_NUMBER', 'TITLE', 'Номер по
порядку'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_NUMBER', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_NUMBER', 'CONTROLSOURCE', 'm.cAlias + ".NUMBER"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_NUMBER', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_DATEDOC', 'TITLE', 'Дата'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_DATEDOC', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_DATEDOC', 'CONTROLSOURCE', 'm.cAlias + ".DATEDOC"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_DATEDOC', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_NUMDOC', 'TITLE', 'Номер
документа'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_NUMDOC', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_NUMDOC', 'CONTROLSOURCE', 'm.cAlias + ".NUMDOC"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_NUMDOC', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_NAMEDOC', 'TITLE', 'Кому, за что и по
какому документу'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_NAMEDOC', 'EDIT_OBJECT_METHOD', 'a_vibor_01("BD_OSNOV", oObj.parent.Parent.RECORDSOURCE, "LINK,TYPE,DATE,NUMBER", "OSNOV_LINK,NAMEDOC,DATEDOC,NUMDOC", "", "","",  .T., 0, oForm, oObj,,.T.)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_NAMEDOC', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_NAMEDOC', 'CONTROLSOURCE', 'm.cAlias + ".NAMEDOC"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_NAMEDOC', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_SUMREPORT', 'TITLE', 'Сумма расходов
по отчету'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_SUMREPORT', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_SUMREPORT', 'CONTROLSOURCE', 'm.cAlias + ".SUMREPORT"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_SUMREPORT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_SUMACCEPTED', 'TITLE', 'Сумма расходов
принятая к учету'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_SUMACCEPTED', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_SUMACCEPTED', 'CONTROLSOURCE', 'm.cAlias + ".SUMACCEPTED"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_SUMACCEPTED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_DTACCOUNT', 'TITLE', 'Дебет счета,
субсчета'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_DTACCOUNT', 'EDIT_OBJECT_METHOD', 'a_vibor_01("PLAN_ACCOUNTS_LIST", oObj.parent.Parent.RECORDSOURCE, "ACCCODE", "DTACCOUNT", "LINK", "","dbo.AccountsHasNoChild(LINK)=1 AND ZABALANS = 0",  .T., 1, oForm, oObj,''lg_prov_notsbs()'')'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_DTACCOUNT', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_DTACCOUNT', 'CONTROLSOURCE', 'm.cAlias + ".DTACCOUNT"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_DTACCOUNT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_LINK_DT', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_LINK_DT', 'REFERENCE_TO_DICT', 'DICTIONARY_ITEM'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_LINK_DT', 'SHORT_CODE_OBJ', 'EKR_LINK_DT'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_LINK_DT', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_DT', 'TITLE', 'ДТ ЭКР'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_DT', 'EDIT_OBJECT_METHOD', 'a_vibor_01("DICTIONARY_ITEM", oObj.parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "EKR_LINK_DT,EKR_CODE_DT,EKR_NAME_DT", "", "","",  .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_DT', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_DT', 'CONTROLSOURCE', 'm.cAlias + ".EKR_CODE_DT"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_DT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_DT', 'OPERATE_METHOD', 'X_EDIT_REC ("DICTIONARY_KOSGU", EVALUATE (m.cAliasOperate + ".EKR_LINK_DT"))'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_DT', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_DT', 'REFERENCE_TO_DICT', 'BV_DOC_AO_TABLE_EKR_LINK_DT'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_DT', 'TYPE_FIELD_DICT', 'char(6)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_DT', 'SHORT_CODE_OBJ', 'EKR_CODE_DT'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_DT', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_NAME_DT', 'TITLE', 'Наименование ЭКР Дт'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_NAME_DT', 'CONTROLSOURCE', 'm.cAlias + ".EKR_NAME_DT"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_NAME_DT', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_NAME_DT', 'REFERENCE_TO_DICT', 'BV_DOC_AO_TABLE_EKR_LINK_DT'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_NAME_DT', 'TYPE_FIELD_DICT', 'varchar(100)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_NAME_DT', 'SHORT_CODE_OBJ', 'EKR_NAME_DT'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_NAME_DT', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_KTACCOUNT', 'TITLE', 'Кредит счета,
субсчета'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_KTACCOUNT', 'EDIT_OBJECT_METHOD', 'a_vibor_01("PLAN_ACCOUNTS_LIST", oObj.parent.Parent.RECORDSOURCE, "ACCCODE", "KTACCOUNT", "LINK", "","dbo.AccountsHasNoChild(LINK)=1 AND ZABALANS = 0",  .T., 1, oForm, oObj,''lg_prov_notsbs()'')'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_KTACCOUNT', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_KTACCOUNT', 'CONTROLSOURCE', 'm.cAlias + ".KTACCOUNT"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_KTACCOUNT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_LINK_KT', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_LINK_KT', 'REFERENCE_TO_DICT', 'DICTIONARY_ITEM'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_LINK_KT', 'SHORT_CODE_OBJ', 'EKR_LINK_KT'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_LINK_KT', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_KT', 'TITLE', 'Кт ЭКР'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_KT', 'EDIT_OBJECT_METHOD', 'a_vibor_01("DICTIONARY_ITEM", oObj.parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "EKR_LINK_KT,EKR_CODE_KT,EKR_NAME_KT", "", "","",  .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_KT', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_KT', 'CONTROLSOURCE', 'm.cAlias + ".EKR_CODE_KT"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_KT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_KT', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_KT', 'REFERENCE_TO_DICT', 'BV_DOC_AO_TABLE_EKR_LINK_KT'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_KT', 'TYPE_FIELD_DICT', 'char(6)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_KT', 'SHORT_CODE_OBJ', 'EKR_CODE_KT'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_CODE_KT', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_NAME_KT', 'TITLE', 'Наименование ЭКР Кт'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_NAME_KT', 'CONTROLSOURCE', 'm.cAlias + ".EKR_NAME_KT"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_NAME_KT', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_NAME_KT', 'REFERENCE_TO_DICT', 'BV_DOC_AO_TABLE_EKR_LINK_KT'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_NAME_KT', 'TYPE_FIELD_DICT', 'varchar(100)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_NAME_KT', 'SHORT_CODE_OBJ', 'EKR_NAME_KT'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EKR_NAME_KT', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_SUM_NDFL', 'TITLE', 'Сумма НДФЛ'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_SUM_NDFL', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_SUM_NDFL', 'CONTROLSOURCE', 'm.cAlias + ".SUM_NDFL"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_SUM_NDFL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_SUM_VZNOS', 'TITLE', 'Сумма взносов
на страхование'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_SUM_VZNOS', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_SUM_VZNOS', 'CONTROLSOURCE', 'm.cAlias + ".SUM_VZNOS"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_SUM_VZNOS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_LINK', 'STORAGE', 'EMPL'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_LINK', 'REFERENCE_TO_DICT', 'KU_EMPL_PLACING'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_LINK', 'SHORT_CODE_OBJ', 'EMP_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_CODE', 'TITLE', 'МОЛ'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_CODE', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("KU_EMPL_PLACING", oObj.parent.Parent.RECORDSOURCE,"LINK, TAB, NAME_EMPL", "EMP_LINK, EMP_CODE, EMP_NAME", "", "", , .T., 1, oForm, oObj,"",.T.,"EMPL_GROUPS")'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_CODE', 'CONTROLSOURCE', 'm.cAlias + ".EMP_CODE"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_CODE', 'STORAGE', 'EMPL'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_CODE', 'REFERENCE_TO_DICT', 'BV_DOC_AO_TABLE_EMP_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_CODE', 'TYPE_FIELD_DICT', 'char(5)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_CODE', 'SHORT_CODE_OBJ', 'EMP_CODE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_NAME', 'TITLE', 'ФИО МОЛ'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_NAME', 'CONTROLSOURCE', 'm.cAlias + ".EMP_NAME"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_NAME', 'STORAGE', 'EMPL'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_NAME', 'REFERENCE_TO_DICT', 'BV_DOC_AO_TABLE_EMP_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_NAME', 'TYPE_FIELD_DICT', 'varchar(100)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_NAME', 'SHORT_CODE_OBJ', 'EMP_NAME'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_EMP_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_TYPE', 'TITLE', 'Тип МЗ'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_TYPE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_TYPE', 'CONTROLSOURCE', 'm.cAlias+''.MZ_TYPE'''
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_TYPE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_TYPE', 'ROWSOURCE', 'Номенклатура,Инвентарь'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_TYPE', 'STORAGE', 'STRING'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_TYPE', 'REFERENCE_TO_DICT', 'BV_NOMENCLATURE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_TYPE', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_TYPE', 'SHORT_CODE_OBJ', 'TYPE_INV'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_TYPE', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_LINK', 'TITLE', 'Материал'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_LINK', 'CONTROLSOURCE', 'm.cAlias+''.MZ_LINK'''
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_LINK', 'STORAGE', 'NOMENCLATURE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_LINK', 'REFERENCE_TO_DICT', 'BV_NOMENCLATURE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_LINK', 'SHORT_CODE_OBJ', 'MZ_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_CODE', 'TITLE', '№ МЗ'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_CODE', 'EDIT_OBJECT_METHOD', 'bv_ao_valid_mz()'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_CODE', 'CONTROLSOURCE', 'm.cAlias+''.MZ_CODE'''
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_CODE', 'STORAGE', 'NOMENCLATURE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_CODE', 'REFERENCE_TO_DICT', 'BV_DOC_AO_TABLE_MZ_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_CODE', 'TYPE_FIELD_DICT', 'CHAR(12)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_CODE', 'SHORT_CODE_OBJ', 'MZ_CODE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.MZ_CODE'''
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_NAME', 'TITLE', 'Наименование МЗ'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_NAME', 'CONTROLSOURCE', 'm.cAlias+''.MZ_NAME'''
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_NAME', 'STORAGE', 'NOMENCLATURE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_NAME', 'REFERENCE_TO_DICT', 'BV_DOC_AO_TABLE_MZ_LINK'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(80)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_NAME', 'SHORT_CODE_OBJ', 'MZ_NAME'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_MZ_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_QTY', 'TITLE', 'Количество'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_QTY', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_QTY', 'CONTROLSOURCE', 'm.cAlias + ".QTY"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_TABLE_QTY', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_LINK_PKO', 'TITLE', 'Ссылка на операцию ПКО'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_LINK_PKO', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_LINK_PKO', 'SHORT_CODE_OBJ', 'P_TYP_LINK'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_LINK_PKO', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_PKO', 'TITLE', 'Типовая операция (ПКО)'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_PKO', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "P_TYP_LINK", "P_TYP_NAME", "DOCUMENTS_PKO")'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_PKO', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_PKO', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_PKO', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_PKO', 'REFERENCE_TO_DICT', 'DOC_AO_OPT_TYP_LINK_PKO'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_PKO', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_PKO', 'SHORT_CODE_OBJ', 'P_TYP_NAME'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_PKO', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".P_TYP_NAME"'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_PKO', 'CONTROL_NAME_EDIT', 'Asel_spr1'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_PKO', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_LINK_RKO', 'TITLE', 'Ссылка на операцию РКО'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_LINK_RKO', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_LINK_RKO', 'SHORT_CODE_OBJ', 'R_TYP_LINK'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_LINK_RKO', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_RKO', 'TITLE', 'Типовая операция (РКО)'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_RKO', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "R_TYP_LINK", "R_TYP_NAME", "DOCUMENTS_RKO")'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_RKO', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_RKO', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_RKO', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_RKO', 'REFERENCE_TO_DICT', 'DOC_AO_OPT_TYP_LINK_RKO'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_RKO', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_RKO', 'SHORT_CODE_OBJ', 'R_TYP_NAME'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_RKO', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".R_TYP_NAME"'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_RKO', 'CONTROL_NAME_EDIT', 'Asel_spr2'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_TYP_NAME_RKO', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_PRN_TITLE_PROV', 'TITLE', 'На титульном листе печатать проводки на получение аванса'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_PRN_TITLE_PROV', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_PRN_TITLE_PROV', 'CONTROLSOURCE', 'm.cAlias + ".TITLE_PROV"'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_PRN_TITLE_PROV', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_PRN_TITLE_PROV', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_PRN_TITLE_PROV', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_PRN_TITLE_PROV', 'SHORT_CODE_OBJ', 'TITLE_PROV'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_PRN_TITLE_PROV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TITLE_PROV"'
GO
EXEC X_SET_PROP 'DOC_AO_OPT_PRN_TITLE_PROV', 'CONTROL_NAME_EDIT', 'aChk3'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_TABLE_KO_TYPE', 'TITLE', 'Тип КО'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_TABLE_KO_TYPE', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_TABLE_KO_TYPE', 'SHORT_CODE_OBJ', 'DOC_CODE'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_TABLE_KO_NAME', 'TITLE', 'Вид документа'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_TABLE_KO_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_TABLE_KO_NAME', 'CONTROLSOURCE', 'm.cAlias + ".DOC_NAME"'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_TABLE_KO_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_TABLE_KO_NAME', 'SHORT_CODE_OBJ', 'DOC_NAME'
GO
EXEC X_SET_PROP 'BV_DOC_AO_KO_TABLE_KO_NAME', 'SNAME', 'Вид документа'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_MARKER', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_MARKER', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_MARKER', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_OSNOV', 'TITLE', 'Ссылка на основание'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_OSNOV', 'STORAGE', 'OSNOV'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_OSNOV', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_OSNOV', 'SHORT_CODE_OBJ', 'OSNOV'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_OSNOV', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_NUMBER', 'TITLE', 'Номер'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_NUMBER', 'EDIT_OBJECT_METHOD', 'oForm.vibor_getdoc (oForm, oObj)'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_NUMBER', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_NUMBER', 'CONTROLSOURCE', 'm.cAlias + ".NUMBER"'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_NUMBER', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_NUMBER', 'OPERATE_METHOD', 'BK_EDIT_OSNOV_DOC (EVALUATE (m.cAliasOperate + ".OSNOV"))'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_NUMBER', 'STORAGE', 'OSNOV'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_NUMBER', 'REFERENCE_TO_DICT', 'DOC_AO_RKO_T_OSNOV'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_NUMBER', 'TYPE_FIELD_DICT', 'varchar(30)'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_NUMBER', 'SHORT_CODE_OBJ', 'NUMBER'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_NUMBER', 'REFERENCE_TO_FIELD', 'NUMBER'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DATE', 'TITLE', 'Дата'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DATE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DATE', 'CONTROLSOURCE', 'm.cAlias+''.DATE'''
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DATE', 'OPERATE_METHOD', 'BK_EDIT_OSNOV_DOC (EVALUATE (m.cAliasOperate + ".OSNOV"))'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DATE', 'STORAGE', 'OSNOV'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DATE', 'REFERENCE_TO_DICT', 'DOC_AO_RKO_T_OSNOV'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DATE', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DATE', 'SHORT_CODE_OBJ', 'DATE'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DATE', 'REFERENCE_TO_FIELD', 'DATE'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DATE_PROV', 'TITLE', 'Дата проведения'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DATE_PROV', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DATE_PROV', 'CONTROLSOURCE', 'm.cAlias+''.DATE_PROV'''
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DATE_PROV', 'OPERATE_METHOD', 'BK_EDIT_OSNOV_DOC (EVALUATE (m.cAliasOperate + ".OSNOV"))'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DATE_PROV', 'STORAGE', 'OSNOV'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DATE_PROV', 'REFERENCE_TO_DICT', 'DOC_AO_RKO_T_OSNOV'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DATE_PROV', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DATE_PROV', 'SHORT_CODE_OBJ', 'DATE_PROV'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DATE_PROV', 'REFERENCE_TO_FIELD', 'DATE_PROV'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DOC_TYPE', 'TITLE', 'Вид документа'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DOC_TYPE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DOC_TYPE', 'CONTROLSOURCE', 'm.cAlias+''.DOC_TYPE'''
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DOC_TYPE', 'OPERATE_METHOD', 'BK_EDIT_OSNOV_DOC (EVALUATE (m.cAliasOperate + ".OSNOV"))'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DOC_TYPE', 'STORAGE', 'OSNOV'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DOC_TYPE', 'REFERENCE_TO_DICT', 'DOC_AO_RKO_T_OSNOV'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DOC_TYPE', 'TYPE_FIELD_DICT', 'VARCHAR (254)'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DOC_TYPE', 'SHORT_CODE_OBJ', 'DOC_TYPE'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_DOC_TYPE', 'REFERENCE_TO_FIELD', 'TYPE'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_COMMENT', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_COMMENT', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_COMMENT', 'CONTROLSOURCE', 'm.cAlias+''.COMMENT'''
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_COMMENT', 'OPERATE_METHOD', 'BK_EDIT_OSNOV_DOC (EVALUATE (m.cAliasOperate + ".OSNOV"))'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_COMMENT', 'STORAGE', 'OSNOV'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_COMMENT', 'REFERENCE_TO_DICT', 'DOC_AO_RKO_T_OSNOV'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_COMMENT', 'TYPE_FIELD_DICT', 'VARCHAR (254)'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_COMMENT', 'SHORT_CODE_OBJ', 'COMMENT'
GO
EXEC X_SET_PROP 'DOC_AO_RKO_T_COMMENT', 'REFERENCE_TO_FIELD', 'COMMENT'
GO




GO
--Таблица SPEC_OCENKA_USLT_RUD
IF not exists(select * from sysobjects where id = object_id('[dbo].[SPEC_OCENKA_USLT_RUD]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[SPEC_OCENKA_USLT_RUD] (
	[LINK1] int NOT NULL ,
	[CODE] varchar(4) NOT NULL ,
	[YBEG] int NOT NULL ,
	[YEND] int NOT NULL ,
	[NAME] varchar(100) NOT NULL)
GO

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

--Расширенные свойства--
--Индексы
--Констрэйнты
--Триггеры



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


GO
--Добавление колонки [SpecO] в таблицу STAVKI_PF
IF COLUMNPROPERTY(object_id('[dbo].[STAVKI_PF]'), 'SpecO', 'AllowsNull') is null
	ALTER TABLE [dbo].[STAVKI_PF] ADD [SpecO] tinyint NOT NULL default (1)
GO



GO

-- Удаление констрейнта 'DF__STAVKI_PF__SpecO%' из таблицы [STAVKI_PF]
IF  EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid like  (SELECT id FROM SYSOBJECTS WHERE name LIKE ('DF__STAVKI_PF__SpecO%')))
BEGIN 
	DECLARE @con VARCHAR(100)
	SET @con = (SELECT NAME FROM SYSOBJECTS WHERE name LIKE ('DF__STAVKI_PF__SpecO%'))
	SET @con = LTRIM(RTRIM(@con))
	--Констрэинт
	exec ('ALTER TABLE [dbo].[STAVKI_PF]
	drop CONSTRAINT [' + @con + ']')
END 

GO

--Добавление колонки [SpecO] в таблицу STAVKI_PF
IF COLUMNPROPERTY(object_id('[dbo].[STAVKI_PF]'), 'SpecO', 'Precision') = 3
	ALTER TABLE [dbo].[STAVKI_PF] ALTER column [SpecO] int null

	UPDATE STAVKI_PF
	set  [SpecO] = null
	where [SpecO]  = 1

GO



GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_STAVKI_PF_SZV4_SPR]'))
	ALTER TABLE [dbo].[STAVKI_PF] WITH NOCHECK 
	ADD CONSTRAINT [FK_STAVKI_PF_SZV4_SPR] FOREIGN KEY ([SpecO]) REFERENCES [dbo].[SZV4_SPR] ([LINK])
	ALTER TABLE [dbo].[STAVKI_PF] NOCHECK CONSTRAINT [FK_STAVKI_PF_SZV4_SPR]

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

GO

CREATE TRIGGER dbo.SZV4_spr_XDELETE ON SZV4_spr
FOR DELETE 
AS
  IF @@ROWCOUNT>0
	BEGIN
		DELETE FROM dbo.STAVKI_PF WHERE [SpecO] IN (SELECT [link] FROM DELETED)
		DELETE FROM dbo.COND_REF WHERE [LINK_COND] IN (SELECT [link] FROM DELETED)
	END

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


GO
EXECUTE dbo.X_FORM_VIEW_OPTIONS 'BV_DOC_AO_OPTIONS'
GO


GO

--ОБЪЕКТЫ БД 06.04.2014
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[S_FILES_XDELETE]') AND OBJECTPROPERTY(id, N'IsTrigger') = 1)
DROP TRIGGER dbo.[S_FILES_XDELETE]

GO
CREATE TRIGGER dbo.S_FILES_XDELETE ON S_FILES
FOR DELETE 
AS
  IF @@ROWCOUNT>0
	BEGIN
		DELETE FROM dbo.S_FILEPARTS WHERE [File_ID] IN (SELECT [ID] FROM DELETED)
		DELETE FROM dbo.S_FILEPARTS_ WHERE [File_ID] IN (SELECT [ID] FROM DELETED)
	END

GO


GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





CREATE     
--Jun 23 2005  3:29PM           
VIEW dbo.DOCUMENTS_PAY_ADD
AS
SELECT 	
	F.LINK,
	[DOH_CODE] = K.Code,
	[DOH_LINK] = F.Link_Dohod,
	[DOH_NAME] = K.name,
	[SGU_CODE] = S.Code,
	[SGU_LINK] = F.Link_SGU,
	[SGU_NAME] = S.Name,
	F.OKATO,
	F.P_REASON,
	F.P_TYPE,
	[PERIOD] = F.Nal_PERIOD,
	F.STATUS,
	F.TREBDATE,
	F.TREBNUM,
	F.ZERODATE,
	F.UIN_CODE

FROM dbo.FINANSE_PAYS as F left join 
	kl_kbk K on F.link_dohod = K.link left join 
	kosgu S on F.link_sgu = S.link 



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_SZV4_STAZH]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[SA_SZV4_STAZH]

GO

CREATE  VIEW [dbo].SA_SZV4_STAZH
as

SELECT 
	link = S.link_up,
	link1 = S.link,
	orders,
	S.date1,
	S.date2,
	--Территориальные условия
	ter_usl,
	n_ter_usl = COALESCE(SPR1.[name],''), 
	ter_koef,
	f_ter_usl = COALESCE(S.[ter_usl],'') 
			+ (case when COALESCE(S.[ter_usl],'')  <> '' and coalesce(ter_koef,0) <> 0 then ',' + convert(varchar(20),coalesce(ter_koef,0)) else '' end),
	--Особые условия труда
	osob_usl,
	n_osob_usl = COALESCE(SPR2.[name],''),
	osob_k1, --По списку №1
	n_osob_k1 = COALESCE(SPR6.[name],''),
	osob_k2, --По списку №2
	n_osob_k2 = COALESCE(SPR7.[name],''),
	osob_spo, --Спец оценка условий труда
	n_osob_spo = COALESCE(SPR8.[name],''),
	osob_k3, --По списку №3
	n_osob_k3 = COALESCE(SPR9.[name],''),
	f_osob_usl = COALESCE(S.[osob_usl],'') 
			+ (case when COALESCE(S.[osob_usl],'') <> '' and COALESCE(S.[osob_k1],'') <> '' then ',' + COALESCE(S.[osob_k1],'') else '' end )
			+ (case when COALESCE(S.[osob_usl],'') <> '' and COALESCE(S.[osob_k2],'') <> '' then ',' + COALESCE(S.[osob_k2],'') else '' end )
			+ (case when COALESCE(S.[osob_usl],'') <> '' and COALESCE(S.[osob_k3],'') <> '' then ',' + COALESCE(S.[osob_k3],'') else '' end )
			+ (case when COALESCE(S.[osob_usl],'') <> '' and COALESCE(S.[osob_spo],'') <> '' then ',' + COALESCE(S.[osob_spo],'') else '' end ),
	-- Исчисление страхового стажа
	is_osnov,
	n_is_osnov = COALESCE(SPR3.[name],''),

	is_dop_m,
	is_dop_d,
	is_dop,
	n_is_dop = COALESCE(SPR4.[name],''),

	f_is_osnov = COALESCE(S.[is_osnov],'')
			+ (case when COALESCE(S.[is_osnov],'') <> '' and COALESCE(S.[is_dop_m],0) <> 0 and RTRIM(LTRIM(coalesce(spr3.par1code,''))) <> '' then ',' + Convert(Varchar(10),COALESCE(S.[is_dop_m],0)) + SPACE(1) + RTRIM(LTRIM(coalesce(spr3.par1code,''))) else '' end )
			+ (case when COALESCE(S.[is_osnov],'') <> '' and COALESCE(S.[is_dop_d],0) <> 0 and RTRIM(LTRIM(coalesce(spr3.par2code,''))) <> '' then (case when COALESCE(S.[is_dop_m],0) <> 0 then '' else ',' end)
						+ Convert(varchar(10),COALESCE(S.[is_dop_d],0)) + SPACE(1) + RTRIM(LTRIM(coalesce(spr3.par2code,''))) else '' end )
			+ (case when COALESCE(S.[is_dop],'') <> '' then COALESCE(S.[is_dop],'') else '' end ),

	f_is_dop = (case when COALESCE(S.[is_osnov],'') <> '' and COALESCE(S.[is_dop_m],0) <> 0 and RTRIM(LTRIM(coalesce(spr3.par1code,''))) <> '' then Convert(Varchar(10),COALESCE(S.[is_dop_m],0)) + SPACE(1) + RTRIM(LTRIM(coalesce(spr3.par1code,''))) else '' end )
			+ (case when COALESCE(S.[is_osnov],'') <> '' and COALESCE(S.[is_dop_d],0) <> 0 and RTRIM(LTRIM(coalesce(spr3.par2code,''))) <> '' then (case when COALESCE(S.[is_dop_m],0) <> 0 then ',' else '' end)
						+ Convert(varchar(10),COALESCE(S.[is_dop_d],0)) + SPACE(1) +RTRIM(LTRIM(coalesce(spr3.par2code,''))) else '' end)
			+ (case when COALESCE(S.[is_dop],'') <> '' then COALESCE(S.[is_dop],'') else '' end ),

	-- 	Условия для досрочного назначения пенсии
	ud_osnov,
	n_ud_osnov = COALESCE(SPR5.[name],''),

	ud_dop_m,
	ud_dop_d,
	ud_dop_k,
	f_ud_osnov = COALESCE(S.[ud_osnov],'')
			+ (case when COALESCE(S.[ud_osnov],'') <> '' and COALESCE(S.[ud_dop_m],0) <> 0 and RTRIM(LTRIM(coalesce(spr5.par1code,''))) <> '' then  ',' + Convert(Varchar(10),COALESCE(S.[ud_dop_m],0)) + SPACE(1) + RTRIM(LTRIM(coalesce(spr5.par1code,''))) else '' end )
			+ (case when COALESCE(S.[ud_osnov],'') <> '' and COALESCE(S.[ud_dop_d],0) <> 0 and RTRIM(LTRIM(coalesce(spr5.par2code,''))) <> '' then (case when COALESCE(S.[ud_dop_m],0) <> 0 then '' else ',' end)
						+ Convert(varchar(10),COALESCE(S.[ud_dop_d],0)) + SPACE(1) + RTRIM(LTRIM(coalesce(spr5.par2code,'')))  else '' end )
			+ (case when COALESCE(S.[ud_osnov],'') <> '' and COALESCE(S.[ud_dop_k],0) <> 0 then (case when (COALESCE(S.[ud_dop_m],0) <> 0 or COALESCE(S.[ud_dop_d],0) <> 0) then ',' else '' end) 
					+ Convert(Varchar(10),COALESCE(S.[ud_dop_k],0)) else '' end ),

	f_ud_dop = (case when COALESCE(S.[ud_osnov],'') <> '' and COALESCE(S.[ud_dop_m],0) <> 0 and RTRIM(LTRIM(coalesce(spr5.par1code,''))) <> '' then  Convert(Varchar(10),COALESCE(S.[ud_dop_m],0)) + SPACE(1) + RTRIM(LTRIM(coalesce(spr5.par1code,''))) else '' end )
			+ (case when COALESCE(S.[ud_osnov],'') <> '' and COALESCE(S.[ud_dop_d],0) <> 0 and RTRIM(LTRIM(coalesce(spr5.par2code,''))) <> '' then (case when COALESCE(S.[ud_dop_m],0) <> 0 then ',' else '' end)
						+ Convert(varchar(10),COALESCE(S.[ud_dop_d],0)) + SPACE(1) + RTRIM(LTRIM(coalesce(spr5.par2code,''))) else '' end )
			+ (case when COALESCE(S.[ud_osnov],'') <> '' and COALESCE(S.[ud_dop_k],0) <> 0 then (case when COALESCE(S.[ud_dop_d],0) <> 0 or COALESCE(S.[ud_dop_m],0) <> 0 then  ',' else '' end)
					+ Convert(Varchar(10),COALESCE(S.[ud_dop_k],0)) else '' end )

from dbo.SZV4_stazh S
	left join dbo.szv4_spr spr1 on spr1.spr_code = 'TERR_USL' and spr1.code = S.ter_usl
	left join dbo.szv4_spr spr2 on spr2.spr_code = 'OSOB_USL_TRUDA' and spr2.code = S.osob_usl
	left join dbo.szv4_spr spr3 on spr3.spr_code = 'ISCHISL_STAZH_OSNOV' and spr3.code = S.is_osnov
	left join dbo.szv4_spr spr4 on spr4.spr_code = 'ISCHISL_STAZH_DOP_SV' and spr4.code = S.is_dop
	left join dbo.szv4_spr spr5 on spr5.spr_code = 'DOSR_NAZN_PEN_OSNOV' and spr5.code = S.ud_osnov
	left join dbo.szv4_spr spr6 on spr6.spr_code = 'SPISOK1' and spr6.code = S.osob_k1
	left join dbo.szv4_spr spr7 on spr7.spr_code = 'SPISOK2' and spr7.code = S.osob_k2
	left join dbo.szv4_spr spr8 on spr8.spr_code = 'SPO_USL_TRUDA' and spr8.code = S.osob_spo
	left join dbo.szv4_spr spr9 on spr9.spr_code = 'LGOT_PROFES' and spr9.code = S.osob_k3

GO


GRANT SELECT ON dbo.[SA_SZV4_STAZH] 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
	
	-- Формат выгрузки РСВ-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.[SA_SZV4_SPR_SPR]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[SA_SZV4_SPR_SPR]

GO



CREATE view [dbo].SA_SZV4_SPR_SPR 
AS
	SELECT CODE = 'TERR_USL', NAME = 'Территориальные условия'
UNION	SELECT CODE = 'OSOB_USL_TRUDA', NAME = 'Особые условия труда'
UNION	SELECT CODE = 'ISCHISL_STAZH_OSNOV', NAME = 'Основания для исчисления стр.стажа'
UNION	SELECT CODE = 'ISCHISL_STAZH_DOP_SV', NAME = 'Доп.сведения для исчисления трудового стажа'
UNION	SELECT CODE = 'DOSR_NAZN_PEN_OSNOV', NAME = 'Основание для досрочного назначения тр.пенсии'
UNION	SELECT CODE = 'SPISOK1', NAME = 'Список №1'
UNION	SELECT CODE = 'SPISOK2', NAME = 'Список №2'
UNION	SELECT CODE = 'SPO_USL_TRUDA', NAME = 'Специальная оценка условий труда'
UNION	SELECT CODE = 'LGOT_PROFES', NAME = 'Профессии для досрочной пенсии'


GO


GRANT SELECT ON dbo.[SA_SZV4_SPR_SPR] TO PUBLIC

GO




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

GO

CREATE   FUNCTION dbo.DocTypOper()
RETURNS TABLE 
AS
	RETURN
	SELECT DISTINCT
		S.LINK AS DOC_TYPE,
		T1.LINK_OPER,
		G1.ORDERS
	FROM dbo.XD_DOC_NASTR DN, DOC_NASTR_T1 T1,S_OBJECTS S,G_PROV1 G1
	WHERE  S.CODE = DN.CODE AND DN.LINK = T1.LINK_UP AND  
		  T1.LINK_OPER = G1.LINK

GO

GRANT SELECT ON dbo.[DocTypOper] TO PUBLIC

GO


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


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

GO

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

CREATE FUNCTION dbo.ku_EmplsInPeriod0 (
	@BDate datetime,
	@EDate	datetime,
	@iDep_Link int = NULL,
	@analit tinyint, -- 0 - все, 1 - женщины
	@vn_sovm tinyint = 0 -- Исключить внешних совместителей
	)
RETURNS @empl TABLE (date datetime, empl_link int, [status] tinyint, sch numeric(5,2), ssch numeric(5,2), comment varchar(100))
AS  ---Получение списочной численности за период
BEGIN 

	SET @iDep_Link = COALESCE(@iDep_Link,(SELECT TOP 1 DEP_LINK FROM dbo.USER_DEP))

	DECLARE @empl_in_otpusk TABLE (date_begin datetime, date_end datetime, empl_Link int)
	
	INSERT @empl_in_otpusk
	SELECT 
		(case when V.date_begin<=@BDate then @BDate else V.date_begin end),
		(case when isnull(coalesce(DATE_BREAK,V.date_end), @EDate) <= @EDate then isnull(coalesce(DATE_BREAK,V.date_end), @EDate) else @EDate end),
		v.empl_link  
	FROM orders o inner join dbo.item_vacation V on o.link = V.order_link
		inner join dbo.vacation_vid VV on V.type_link = VV.link
		inner join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK
		left join item_vacation_break ivb on ivb.vac_link = v.link
	WHERE 
		(
			d.WORK_D = 7 --Дети
			or (d.WORK_D = 5 AND VV.NO_SAL = 1) --Учебный отпуск
		) 
		and v.active=1
		and V.date_begin <= @EDate 
		and isnull(V.date_end, @EDate) >= @BDate		
			and o.dep_link = @iDep_Link

	--Отпуска по уходу или учебный	
	insert into @empl ([date], empl_link, [STATUS], sch, ssch, comment)
	SELECT 
		D.[DATE], 
		EMPL_LINK, 
		[status] = 0, 
		sch = 1,
		ssch = 0,
		com = 'отпуск по уходу или учебный без сохранения з/п'  
	FROM 
		@empl_in_otpusk M
		inner join dbo.days_ex(@BDate,@EDate) D on D.[DATE] between M.DATE_BEGIN AND ISNULL(M.DATE_END,D.[DATE])
	WHERE 
		M.DATE_BEGIN <= @EDate
		and isnull(M.DATE_END, @EDate) >= @BDate

	--Периоды работы
	insert into @empl ([date], empl_link, [STATUS], sch, ssch, comment)
	SELECT 
		D.[DATE], 
		EMPL_LINK, 
		[status], 
		sch = case when [status] = 2 or @vn_sovm = 1 then 0 else 1 end,
		ssch = case when [status] = 2 or @vn_sovm = 1 then 0 else NUM_STAKE end,
		com = case [status] when 3 then 'внешний совместитель' when 2 then 'совместитель' else '' end  
	FROM 
		dbo.EMPL E
		inner join dbo.sa_empl_move(default) M on E.link = M.empl_link
		inner join dbo.days_ex(@BDate,@EDate) D on D.[DATE] between M.DATE_BEGIN AND ISNULL(M.DATE_END,D.[DATE])
	WHERE 
		M.DATE_BEGIN <= @EDate
		and isnull(M.DATE_END, @EDate) >= @BDate
		and E.dep_link = @iDep_Link
		and not exists (select empl_link from @empl_in_otpusk O where O.empl_link = e.link and D.[DATE] between O.DATE_BEGIN AND ISNULL(O.DATE_END,D.[DATE]) )

	RETURN
END




GO


GRANT SELECT ON dbo.[ku_EmplsInPeriod0] TO PUBLIC

GO


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


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

CREATE VIEW dbo.BB_ZAYAVKA_KR
AS

SELECT	G.LINK,
		G.NUMBER,
		SUMMA		= G.SUMMA,
		SUMMA_P		= ISNULL(dbo.CalcDocSumma(G.LINK), G.SUMMA),
		SUMMA_NDS	= P.SUMMA_NDS,--ISNULL(dbo.CalcDocSumma(G.LINK), G.SUMMA) * isnull(P.NDS,0) / (100.0 + isnull(P.NDS,0)),
		G.COMMENT,
		G.DATE, 
		G.DATE_PROV,
		FLAG_JC		= CASE WHEN G.DATE_PROV IS NULL THEN 0 ELSE 1 END,
		DEP_LINK	= G.DEP,
		DEP_CODE	= SD.CODE,
		DEP_B_CODE	= SD.BUDG,
		DEP_UBP		= SD.CODE_UBP,
		DEP_NAME	= SD.NAME,
		DEP_FNAME	= left(rtrim(SD.prefix) + rtrim(SD.FULL_NAME) + case when charindex('(',SD.prefix,0) > 0 then ')' else '' end,254),
		DEP_TYPE	= SD.BUH_TYPE,
		GRBS_NAME	= VED.NAME,
		GRBS_CODE	= VED.CODE,
		BUDG_NAME	= BUDG.NAME,
		FO_NAME		= FO.FULL_NAME,
		FO_CODE		= FO.CODE,
		FO_OKPO		= FO.OKPO,
		ACC_LINK	= G.ACC,
		ACC_CODE	= SA.CODE,		
		ACC_NAME	= SA.ANAME,	
		TOFK_NAME	= SA.KAZN_F_NAME,
		TOFK_CODE	= SA.KAZN_CODE,
		UCHR_NAME	= UCHR.NAME,
		

		DBANK_LINK		= DA.ref_link_b,
		KOR_CODE		= DD.CODE,
		KOR_ACC_LINK	= P.D_Acc,
		KOR_ACC_CODE	= DA.code,
		KOR_LACC		= case DA.type when 1 then '' else DA.code end,
		KOR_RACC		= case DA.type when 1 then DA.code else TA.code end,
		KOR_BANK		= rtrim(isnull(DA.BANK_FNAME,TA.BANK_FNAME)) + case ZO.BANK_CITY when 1 then ' ' + isnull(DA.BANK_CITY,TA.BANK_CITY) else '' end,
		KOR_BIK			= isnull(DA.BANK_CODE,TA.BANK_CODE),
		KOR_KS			= DA.BANK_KS,
		KOR_ANAME		= DA.aname,
		KOR_FNAME		= left(rtrim(DD.prefix) + rtrim(DD.FULL_NAME) + case when charindex('(',DD.prefix,0) > 0 then ')' else '' end,254),
		KOR_INN			= DD.INN,
		KOR_KPP			= DD.KPP,
		KOR_LINK		= DD.Link,
		KOR_NAME		= DD.NAME,
		KBK_CODE		= KBK.CODE,  		
		P.AVANSE,	
		P.BK_IN_TGT,
		P.KIND,
		[ORDER]			= P.Order_Pay,
		P.PRINT_KPP,
		P.SROK,
		P.NDS,
		P.NDS_LINK,
		NDS_NAME	=	CONVERT(VARCHAR(50), NDS.NAME),
		NDS_SHABLON	=	CONVERT(VARCHAR(250), NDS.SHABLON),
		P.TARGETTEXT,
		OSN_NUM		= CONVERT (VARCHAR (25), GD.Number),
		OSN_DATE	= GD.DATE,
		OSN_NAME	= CONVERT (VARCHAR (254), GD.INFO),
		OSN_LINK	= GD.DOC_LINK,
		OSN_COM		= GD.COMMENT,
		OSN_VID		= GD.[TYPE],
		
		BO_NUM		= P.BO_NUM,

		TITLE		= 'Заявка №' + RTRIM(CONVERT(VARCHAR(25),G.NUMBER)) + ' от ' + CONVERT(VARCHAR(10),G.[DATE], 104),
		S_TARGET	= CONVERT(VARCHAR(100),LEFT(TARGETTEXT,100)),
		DOH_CODE_L	= case isnull(ZO.KBK_DEL,0) when 0 then rtrim(K.Code) + '.' + S.Code else replace(rtrim(K.Code) + '.' + S.Code,'.','') end,
		[DOH_CODE] = K.Code,
		[DOH_LINK] = P.Link_Dohod,
		[DOH_NAME] = K.name,
		[SGU_CODE] = S.Code,
		[SGU_LINK] = P.Link_SGU,
		[SGU_NAME] = S.Name,
		P.OKATO,
		P.P_REASON,
		P.P_TYPE,
		[PERIOD] = P.Nal_PERIOD,
		P.STATUS,
		P.TREBDATE,
		P.TREBNUM,
		P.ZERODATE,
		P.SHORT,
		P.REG,
		P.UIN_CODE
		
FROM  dbo.G_PROV G 
left join dbo.FINANSE_PAYS P WITH (NOLOCK) on P.link = G.link
left join dbo.DICTIONARY_ACCOUNTS SA WITH (NOLOCK) on G.Acc = SA.link
left join dbo.DICTIONARY_ACCOUNTS DA WITH (NOLOCK) on P.D_Acc = DA.link
left join dbo.DICTIONARY_K_ACCOUNTS TA WITH (NOLOCK) on DA.K_Acc_LINK = TA.link
left join dbo.DEPARTMENTS SD WITH (NOLOCK) on G.DEP = SD.link
left join dbo.DEPARTMENTS FO WITH (NOLOCK) on SD.FO_LINK = FO.LINK
left join dbo.DEPARTMENTS UCHR WITH (NOLOCK) on SD.UCHR_LINK = UCHR.LINK
left join dbo.KL_ADMIN_BS VED WITH (NOLOCK) on VED.LINK = SD.VED_LINK
left join dbo.KL_BUDG_TYPE BUDG WITH (NOLOCK) on VED.Link_Budg = BUDG.LINK
left join dbo.DEPARTMENTS DD WITH (NOLOCK) on DA.REF_LINK_D = DD.link
left join dbo.BD_OSNOV GD on GD.link = P.link_dogovor 
left join dbo.G_PROV GD1 on P.link_invoice = GD1.link
left join dbo.kl_kbk K on P.link_dohod = K.link 
left join dbo.kosgu S on P.link_sgu = S.link
left join dbo.DICTIONARY_PAY_NDS NDS on P.NDS_Link = NDS.LINK
left join (select max(LINK_KBK) as LINK_KBK, LINK_UP from dbo.ZAYAVKA_KR_TABLE group by LINK_UP) ZT on ZT.LINK_UP = G.LINK
left join dbo.KL_KBK KBK on KBK.LINK = ZT.LINK_KBK 
left join dbo.BB_ZAYAVKA_KR_OPTIONS ZO on 1=1

WHERE G.OBJECT = (select link from s_objects where code = 'BB_ZAYAVKA_KR')




GO

grant all on BB_ZAYAVKA_KR to public
GO

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

GO

/*  select * from DICTIONARY_RANGE_PF where date = '20140101' order by  way_calc ,tarif
© Кейсистемс (Keysystems), 2005
*/
CREATE  VIEW [dbo].DICTIONARY_RANGE_PF
AS 
SELECT 
[LINK] = S.LINK,
[DATE] = S.[DATE],
[COMMENT] = S.COMMENT,
[PREDEL] = S.PREDEL,
[PERCENT1] = S.[PERCENT1],
[PERCENT2] = S.[PERCENT2],
[PERCENT3] = S.[PERCENT3],
[LINK_PAYS] = S.LINK_PAYS,
[CODE_PAYS] = P.CODE,
[NAME_PAYS] = P.[NAME],
[WAY_CALC] = P.WAY_CALC,
S.TARIF,
NTARIF = K.NAME2 + ' (' + RTRIM(K.CODE) + ')',
[SpecO] = (case when P.WAY_CALC in (10,11)then S.SpecO ELSE null END),
[NSpecO] = (case when P.WAY_CALC in (10,11) then (ISNULL(RTRIM(SP.CODE), '')) ELSE '' END ),
[SpecO_NAME] = (case when P.WAY_CALC in (10,11) then (ISNULL(RTRIM(SP.NAME), '')) ELSE '' END )
FROM 
	dbo.PAYS P 
	INNER JOIN dbo.STAVKI_PF S ON P.LINK = S.LINK_PAYS
	INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK2 = S.TARIF AND YEAR(S.[DATE]) BETWEEN K.YBEG AND K.YEND
	LEFT JOIN dbo.SA_SZV4_SPR SP ON SP.LINK = S.SpecO AND sp.spr_code = 'SPO_USL_TRUDA'
	

GO


GRANT SELECT ON dbo.[DICTIONARY_RANGE_PF] TO PUBLIC

GO



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

GO
/*
© Кейсистемс (Keysystems), 2005
*/
CREATE   FUNCTION dbo.DOP_VZNOS_GET_ADDRESS()
RETURNS @varKSRES TABLE(
	LINK_FACE INT,
	LINK_ADDR INT,
	IND_ADR VARCHAR(10),
	REGION VARCHAR(4),
	RAION VARCHAR(254),
	GOROD VARCHAR(254),
	NASEL VARCHAR(254),
	STREET VARCHAR(254),
	HOUSE VARCHAR(20),
	KORP VARCHAR(10),
	FLAT VARCHAR(10)
)
AS BEGIN

	DECLARE 	
		@varKSLINK_FACE INT,
		@varKSLINK_ADDR INT,
		@varKSIND_ADR VARCHAR(10),
		@varKSREGION VARCHAR(4),
		@varKSRAION VARCHAR(254),
		@varKSGOROD VARCHAR(254),
		@varKSNASEL VARCHAR(254),
		@varKSSTREET VARCHAR(254),
		@varKSHOUSE VARCHAR(20),
		@varKSKORP VARCHAR(10),
		@varKSFLAT VARCHAR(10)

	DECLARE @varKSCUR_FACE CURSOR 
	SET @varKSCUR_FACE = CURSOR LOCAL FAST_FORWARD FOR 
		SELECT 
			P.LINK, ADR_OFIC_LINK, 
			ISNULL(HOUSE_OFIC, ''), 
			ISNULL(CORP_OFIC, ''),
			ISNULL(FLAT_OFIC, '')
		FROM PERSON P
--		INNER JOIN KU_EMPL_PLACING EP ON (P.LINK = EP.PERS_LINK AND EP.STATUS <> 2)
--		INNER JOIN USER_INFO UI ON UI.DEP_LINK = EP.DEP_LINK
		INNER JOIN dbo.BufferGetTableById('SPRDOPVZNOS') B ON B.LINK = P.LINK

	OPEN @varKSCUR_FACE
	FETCH @varKSCUR_FACE INTO @varKSLINK_FACE, @varKSLINK_ADDR, @varKSHOUSE, @varKSKORP, @varKSFLAT
	WHILE @@FETCH_STATUS = 0
	BEGIN
		INSERT INTO @varKSRES
		SELECT 
			@varKSLINK_FACE, @varKSLINK_ADDR, 
			PINDEX, REGCODE, RAION, GOROD, NASEL, STREET,
			@varKSHOUSE, @varKSKORP, @varKSFLAT			
		FROM dbo.GetAddressPartsByKladr(@varKSLINK_ADDR, DEFAULT)	

		FETCH @varKSCUR_FACE INTO @varKSLINK_FACE, @varKSLINK_ADDR, @varKSHOUSE, @varKSKORP, @varKSFLAT
	END
	CLOSE @varKSCUR_FACE
	DEALLOCATE @varKSCUR_FACE
	
	
	RETURN

END




GO


GRANT SELECT ON dbo.[DOP_VZNOS_GET_ADDRESS] TO PUBLIC

GO



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

GO


CREATE FUNCTION [dbo].[SA_ESN_VIEW] (@nYEAR int, @nMONTH3 int, @DEP_LINK int = null, @PERS_LINK INT = 0) 
/*
Вывод сведений о расчете ЕСН за год @nYEAR по месяц @nMONTH3 для организации @DEP_LINK
в нормализованном виде. Если @PERS_LINK = 0, то по организации иначе по физлицу в организации
*/
RETURNS @SPR_ESN table (LINK_VKR int, [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, KATEG TINYINT,	SPECO INT)
AS
BEGIN

Set @PERS_LINK = isnull(@PERS_LINK,0)
Set @DEP_LINK = isnull(@DEP_LINK, (select top 1 DEP_LINK from dbo.USER_DEP))

declare @SPR_ESN_SRC1 table (LINK_VKR int, [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, SUMMA_BASE_M numeric(12,2) default 0.00, SPECO INT default 0.00)
declare @SPR_ESN_SRC table (LINK_VKR int, [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, SUMMA_BASE_M numeric(12,2) default 0.00, SPECO INT default 0.00)
declare @SPR_ESN_SRC2 table (LINK_VKR int, [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, SUMMA_BASE_M numeric(12,2) default 0.00, SPECO INT default 0.00)
declare @SPR_ESN1 table (LINK_VKR int, [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, SUMMA_BASE_M numeric(12,2) default 0.00, SPECO INT default 0.00)

insert into @SPR_ESN_SRC (LINK_VKR, [MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, SUMMA_BASE_M, SPECO)
select ST.LINK_VKR, MONTH(S.DATE_CALC), SUM(ST.TOTAL_SUM), SUM(ST.DED_M), SUM(ST.INV_M), SUM(ST.SUMMA), P.WAY_CALC,  E.PERS_LINK, SUM(ST.SUMMA_BASE), ISNULL(ST.SPECO,0)
FROM 
	dbo.SDOC S 
	inner join dbo.SDOC_ESN SD on S.LINK = SD.LINK_UP
	inner join dbo.SDOC_ESN_TABLE ST ON ST.LINK_UP = S.LINK
	INNER JOIN dbo.EMPL E ON ST.LINK_EMPL = E.LINK
	INNER JOIN dbo.PAYS P ON P.LINK  = ST.LINK_PAY
WHERE 
	S.FLAG_JC = 1
	AND WAY_CALC <> 5
	AND YEAR(S.DATE_CALC) = @nYEAR
	AND MONTH(S.DATE_CALC) <= @nMONTH3
	AND S.LINK_DEP = @DEP_LINK
	and (E.PERS_LINK = @PERS_LINK OR @PERS_LINK = 0)
GROUP BY 
	E.PERS_LINK, ST.LINK_VKR, P.WAY_CALC, MONTH(S.DATE_CALC), ST.SPECO

------------
Declare @MaxMonth int
Set @MaxMonth = isnull((Select Max([MONTH_BASE]) from @SPR_ESN_SRC),0)

declare @Vkr table (link int)
declare @Way_Calc table (link int)
declare @Link_Pers table (link int)
declare @Link_SPECO table (link int)

insert into @Link_Pers Select distinct REF_PHYS_PERS from @SPR_ESN_SRC 

DECLARE @Cur CURSOR
SET @Cur = CURSOR FORWARD_ONLY
For Select link from @Link_Pers
declare @PersLink int
open @Cur
fetch next from @Cur into @PersLink
while (@@fetch_status <> -1)
begin
	if (@@fetch_status <> -2)
	Begin
		delete from @SPR_ESN_SRC1
		Insert into @SPR_ESN_SRC1 Select * from @SPR_ESN_SRC where REF_PHYS_PERS = @PersLink

		delete from @Vkr
		insert into @Vkr Select distinct LINK_VKR from @SPR_ESN_SRC1 where REF_PHYS_PERS = @PersLink

		delete from @Way_Calc
		insert into @Way_Calc Select distinct WAY_CALC from @SPR_ESN_SRC1 where REF_PHYS_PERS = @PersLink

		DELETE FROM @Link_SPECO		
		insert into @Link_SPECO Select distinct SPECO from @SPR_ESN_SRC1 where REF_PHYS_PERS = @PersLink

		insert into @SPR_ESN_SRC (LINK_VKR, [MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, SUMMA_BASE_M, SPECO)
		Select Vkr.link, M.Num, 
				Base = isnull( 
					(Select Sum(isnull(SUMMA_BASE,0)) from @SPR_ESN_SRC1 S 
						where 
							S.WAY_CALC=WC.link 
							AND S.SPECO = SO.LINK
							and S.[MONTH_BASE] = 
							(Select max([MONTH_BASE]) 
								from @SPR_ESN_SRC1 S1
								 where 
		 							S1.WAY_CALC = S.WAY_CALC 
		 							AND S1.SPECO = S.SPECO
									and isnull(S1.MONTH_BASE,0) <> 0
									and s1.MONTH_BASE < M.Num) 
						) ,0 ), 
				0, 0, 0, WC.link, @PersLink,
				Base_M = isnull( 
					(Select Sum(isnull(SUMMA_BASE_M,0)) from @SPR_ESN_SRC1 S 
						where 
							S.WAY_CALC=WC.link 
							AND S.SPECO = SO.LINK
							and S.[MONTH_BASE] = M.Num 
						) ,0 )
				,SO.LINK						
		
		from 
			@Vkr Vkr, @Way_Calc WC, @Link_SPECO SO, dbo.Months M
		where   
			not exists (select * from @SPR_ESN_SRC1 SES where SES.[MONTH_BASE]=M.num and SES.WAY_CALC=WC.link and SES.SPECO=SO.link) --and Vkr.link = SES.LINK_VKR)
			and M.Num <= @MaxMonth
		order by 
			Vkr.link, WC.link, SO.LINK, M.Num 		

	End
	fetch next from @Cur into @PersLink
end
close @Cur
deallocate @Cur

insert into @SPR_ESN_SRC (LINK_VKR, [MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, SUMMA_BASE_M, SPECO)
select  D.LINK_VKR, M.NUM, 0, 0, 0, 0, D.WAY_CALC, D.REF_PHYS_PERS, 0, D.SPECO
from dbo.Months M inner join (select distinct REF_PHYS_PERS, LINK_VKR, WAY_CALC, SPECO from @SPR_ESN_SRC) D on 1=1
--where not exists (select REF_PHYS_PERS from @SPR_ESN_SRC2 T WHERE T.REF_PHYS_PERS = D.REF_PHYS_PERS AND T.LINK_VKR = D.LINK_VKR AND T.MONTH_BASE = M.NUM AND T.WAY_CALC = D.WAY_CALC)

-------------------------------
insert into @SPR_ESN_SRC2 (LINK_VKR, [MONTH_BASE], WAY_CALC, SUMMA_BASE, SUMMA, DED_M, INV_M, REF_PHYS_PERS, SUMMA_BASE_M, SPECO)
Select LINK_VKR,[MONTH_BASE], WAY_CALC, SUM(SUMMA_BASE), SUM(SUMMA), SUM(DED_M), SUM(INV_M), REF_PHYS_PERS, SUM(SUMMA_BASE_M), SPECO
from @SPR_ESN_SRC
GROUP BY LINK_VKR,[MONTH_BASE], WAY_CALC, REF_PHYS_PERS, SPECO
order by [MONTH_BASE], WAY_CALC, SPECO

DECLARE @TMP_MIN_BASE TABLE (LINK_VKR INT,REF_PHYS_PERS INT,WAY_CALC TINYINT, MIN_MONTH TINYINT, SPECO INT)
INSERT INTO @TMP_MIN_BASE(LINK_VKR,REF_PHYS_PERS,WAY_CALC,MIN_MONTH, SPECO)
SELECT LINK_VKR,REF_PHYS_PERS,WAY_CALC,MIN(MONTH_BASE), SPECO FROM @SPR_ESN_SRC2 GROUP BY LINK_VKR,REF_PHYS_PERS,WAY_CALC, SPECO

INSERT INTO @SPR_ESN1 (LINK_VKR,[MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, SPECO)
Select 
	SRC.LINK_VKR,SRC.[MONTH_BASE], 
	BASE = (isnull(SRC.SUMMA_BASE,0)
	-
	isnull(T2.SUMMA_BASE,0)
	), 
	SRC.DED_M, SRC.INV_M,
	SRC.SUMMA,  SRC.WAY_CALC, SRC.REF_PHYS_PERS,
	SRC.SPECO
from 
	@SPR_ESN_SRC2 SRC 
	INNER JOIN @SPR_ESN_SRC2 T2 ON SRC.LINK_VKR = T2.LINK_VKR AND SRC.REF_PHYS_PERS = T2.REF_PHYS_PERS AND SRC.WAY_CALC = T2.WAY_CALC AND SRC.SPECO = T2.SPECO AND (SRC.MONTH_BASE - 1) = T2.MONTH_BASE	
where 
	isnull(SRC.SUMMA_BASE,0) <> 0 OR ISNULL(SRC.SUMMA,0) <> 0 OR ISNULL(SRC.SUMMA_BASE_M,0) <> 0 
UNION ALL
Select 
	SRC.LINK_VKR,SRC.[MONTH_BASE], 
	BASE = isnull(SRC.SUMMA_BASE,0),
	SRC.DED_M, SRC.INV_M,
	SRC.SUMMA,  SRC.WAY_CALC, SRC.REF_PHYS_PERS,
	SRC.SPECO
from 
	@SPR_ESN_SRC2 SRC 
	INNER JOIN @TMP_MIN_BASE M ON SRC.LINK_VKR = M.LINK_VKR AND SRC.REF_PHYS_PERS = M.REF_PHYS_PERS AND SRC.WAY_CALC = M.WAY_CALC AND SRC.SPECO = M.SPECO AND SRC.MONTH_BASE = M.MIN_MONTH
where 
	isnull(SRC.SUMMA_BASE,0) <> 0 OR ISNULL(SRC.SUMMA,0) <> 0 OR ISNULL(SRC.SUMMA_BASE_M,0) <> 0 
-------------------------------

INSERT INTO @SPR_ESN (LINK_VKR, [MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG, SPECO)
Select 
	LINK_VKR, [MONTH_BASE], SUMMA_BASE= SUM(SUMMA_BASE), DED_M= SUM(DED_M), INV_M= SUM(INV_M), SUMMA= SUM(SUMMA), WAY_CALC, REF_PHYS_PERS,
	KATEG = (CASE WHEN I.LINK IS NULL THEN (F.ENVD + 1) ELSE 3 END),
	SPECO
from 
	@SPR_ESN1 E
	INNER JOIN dbo.SAL_SFIN F ON F.LINK = E.LINK_VKR
	LEFT JOIN dbo.pers_invalid I ON E.REF_PHYS_PERS = I.PERS_LINK AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,E.[MONTH_BASE],@nYEAR)) BETWEEN I.DATE_BEGIN AND COALESCE(I.DATE_END,'29990101')
Group by 
	LINK_VKR, [MONTH_BASE], WAY_CALC, REF_PHYS_PERS, SPECO, (CASE WHEN I.LINK IS NULL THEN (F.ENVD + 1) ELSE 3 END)

RETURN 
END



GO


GRANT SELECT ON dbo.[SA_ESN_VIEW] TO PUBLIC

GO


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

GO
CREATE FUNCTION dbo.BK_DOC_TABLE_AO_FN
	(@DOC_LINK	INT = NULL)
RETURNS TABLE
AS
RETURN 
	SELECT
		OTR.LINK,
		OTR.LINK_UP,
		OTR.LINK_OPER,
		
		T.NUMBER,
		
		NUMDOC = CASE WHEN T.OSNOV IS NOT NULL AND T.OSNOV > 0 THEN OSNOV.NUMBER ELSE T.NUMDOC END,
		DATEDOC = CASE WHEN T.OSNOV IS NOT NULL AND T.OSNOV > 0 THEN OSNOV.[DATE] ELSE T.DATEDOC END,
		NAMEDOC = CASE WHEN T.OSNOV IS NOT NULL AND T.OSNOV > 0 THEN OSNOV.[TYPE] ELSE T.NAMEDOC END,

		SUMREPORT, SUMACCEPTED, QTY,
		SA1.LINK AS DT,
		SA1.CODE AS DTACCOUNT,
		SA2.LINK AS KT,
		SA2.CODE AS KTACCOUNT,
		SUM_NDFL, SUM_VZNOS,
		EKR_LINK_DT = DID.LINK,
		EKR_CODE_DT = DID.CODE,
		EKR_NAME_DT = DID.[NAME],
		EKR_LINK_KT = DIK.LINK,
		EKR_CODE_KT = DIK.CODE,
		EKR_NAME_KT = DIK.[NAME],
		EMP_LINK = T.EMP,
		EMP_CODE = E.TAB,
		EMP_NAME = E.NAME_EMPL,

		[OSNOV_LINK] = T.OSNOV,

		[MZ_TYPE] = CASE WHEN T.INV IS NOT NULL AND T.INV > 0 THEN 1 ELSE 2 END,
		[MZ_LINK] = CASE WHEN T.INV IS NOT NULL AND T.INV > 0 THEN T.INV ELSE T.NOMEN END,
		[MZ_CODE] = CASE WHEN T.INV IS NOT NULL AND T.INV > 0 THEN INV.CODE ELSE NOM.CODE END,
		[MZ_NAME] = CASE WHEN T.INV IS NOT NULL AND T.INV > 0 THEN INV.[NAME] ELSE NOM.[NAME] END

	FROM dbo.OUT_TABLE_ROW OTR
	INNER JOIN dbo.S_OBJECTS SO ON (SO.LINK = OTR.[OBJECT]
		AND SO.CODE = 'BV_DOC_AVANSE_TABLE')
	LEFT JOIN dbo.G_AVANSE_TABLE T ON (T.LINK_UP = OTR.LINK)
	LEFT JOIN dbo.S_ACCOUNTS SA1 ON T.DTACCOUNT = SA1.LINK
	LEFT JOIN dbo.S_ACCOUNTS SA2 ON T.KTACCOUNT = SA2.LINK
	LEFT JOIN dbo.DICTIONARY_ITEM DID ON T.EKR_DT = DID.LINK
	LEFT JOIN dbo.DICTIONARY_ITEM DIK ON T.EKR_KT = DIK.LINK
	LEFT JOIN dbo.KU_EMPL_PLACING E ON T.EMP = E.LINK

	LEFT JOIN dbo.BD_OSNOV OSNOV ON T.OSNOV = OSNOV.LINK
	LEFT JOIN INVENTORY INV ON T.INV = INV.LINK
	LEFT JOIN NOMENCLATURE NOM ON T.NOMEN = NOM.LINK
	WHERE @DOC_LINK IS NULL
		OR OTR.LINK_UP = @DOC_LINK

GO

GRANT SELECT ON dbo.[BK_DOC_TABLE_AO_FN] TO PUBLIC

GO

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


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

GO

CREATE FUNCTION [dbo].FB_RESTRICT_ASSIGN
	(@varKSintFYear	int,	   
	 @varKSdDate 	datetime, 
	 @varKSintLink 	INT, 
	 @varKSintRest	int = 0,
	 @varKSintVKR	int = NULL,	   
	 @varKSintEKR	int = NULL,
	 @varKSintDOP_CL	int = NULL,
	 @iReg int = null, 
	 @varKSintRbsAcc	int = NULL)	   
	 	
RETURNS @varKSRestrictTable 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)

AS
BEGIN

IF @varKSintFYear = 0
	SET @varKSintFYear = (SELECT YEAR(WorkDate) FROM USER_INFO)

DECLARE @varKSRestrObj	int, 
	@varKSRestrSObj	int,
	@varKSintTypePer tinyint

SELECT	@varKSintTypePer = max(FIN_SMETA_PER) FROM WorkMode
 

-- Остаток
if @varKSintRest = 1
INSERT INTO @varKSRestrictTable
	select SA.vkr, SA.ekr, SA.dop_cl, SA.REG, SA.P1-ISNULL(A.p1,0) as p1, SA.P2-ISNULL(A.p2,0) as p2, SA.P3-ISNULL(A.p3,0) as p3,
				SA.P4-ISNULL(A.p4,0) as p4, SA.P5-ISNULL(A.p5,0) as p5, SA.P6-ISNULL(A.p6,0) as p6, 
				SA.P7-ISNULL(A.p7,0) as p7, SA.P8-ISNULL(A.p8,0) as p8, SA.P9-ISNULL(A.p9,0) as p9, 
				SA.P10-ISNULL(A.p10,0) as p10, SA.P11-ISNULL(A.p11,0) as p11, SA.P12-ISNULL(A.p12,0) as p12,
				SA.Y2-ISNULL(A.Y2,0) as Y2, SA.Y3-ISNULL(A.Y3,0) as Y3
	FROM FB_REST_FINANS(@varKSintFYear, @varKSdDate,0 , 1, @varKSintLink, 'FINANS_ASSIGN_SVOD',@varKSintTypePer,'1',DEFAULT) SA
	LEFT JOIN (select vkr, ekr, dop_cl, reg, sum(p1) as p1, sum(p2) as p2, sum(p3) as p3, sum(p4) as p4, sum(p5) as p5, sum(p6) as p6,
			sum(p7) as p7, sum(p8) as p8, sum(p9) as p9, sum(p10) as p10, sum(p11) as p11, sum(p12) as p12, sum(y2) as y2, sum(y3) as y3 
			from FB_REST_FINANS(@varKSintFYear, @varKSdDate, 0, 1, @varKSintLink, 'FINANS_ASSIGN',@varKSintTypePer,'1',1)
			where RBS_ACC = @varKSintRbsAcc
			group by vkr, ekr, dop_cl, reg) A 
	ON 	(SA.VKR = A.VKR OR (SA.VKR IS NULL AND A.VKR IS NULL)) AND 
		(SA.EKR = A.EKR OR (SA.EKR IS NULL AND A.EKR IS NULL)) AND 
		(SA.DOP_CL = A.DOP_CL OR (SA.DOP_CL IS NULL AND A.DOP_CL IS NULL))
	where SA.RBS_ACC = @varKSintRbsAcc AND 
		(SA.VKR = @varKSintVKR OR (SA.VKR IS NULL AND @varKSintVKR = 0) OR @varKSintVKR IS NULL) AND 
		(SA.EKR = @varKSintEKR OR (SA.EKR IS NULL AND @varKSintEKR = 0)OR @varKSintEKR IS NULL) AND 
		(SA.DOP_CL = @varKSintDOP_CL OR (SA.DOP_CL IS NULL AND @varKSintDOP_CL = 0) OR @varKSintDOP_CL IS NULL)
else 
	INSERT INTO @varKSRestrictTable
	SELECT SA.VKR, SA.EKR, SA.dop_cl, SA.REG,  
		isnull(SA.P1,0) as P1, isnull(SA.P2,0) as P2, isnull(SA.P3,0) as P3,
		isnull(SA.P4,0) as P4, isnull(SA.P5,0) as P5, isnull(SA.P6,0) as P6,
		isnull(SA.P7,0) as P7, isnull(SA.P8,0) as P8, isnull(SA.P9,0) as P9,
		isnull(SA.P10,0) as P10, isnull(SA.P11,0) as P11, isnull(SA.P12,0) as P12,
		ISNULL(SA.Y2,0) as Y2, ISNULL(SA.Y3,0) as Y3
		FROM dbo.FB_REST_FINANS(@varKSintFYear, @varKSdDate, 0, 1, @varKSintLink, 'FINANS_ASSIGN_SVOD',@varKSintTypePer,'1',DEFAULT) SA
		where SA.RBS_ACC = @varKSintRbsAcc AND
			(SA.VKR = @varKSintVKR OR (SA.VKR IS NULL AND @varKSintVKR = 0) OR @varKSintVKR IS NULL) AND 
			(SA.EKR = @varKSintEKR OR (SA.EKR IS NULL AND @varKSintEKR = 0)OR @varKSintEKR IS NULL) AND 
			(SA.DOP_CL = @varKSintDOP_CL OR (SA.DOP_CL IS NULL AND @varKSintDOP_CL = 0) OR @varKSintDOP_CL IS NULL) AND 
			(SA.REG = @iReg OR (SA.REG IS NULL AND @iReg = 0) OR @iReg IS NULL)
	
	 
RETURN 
END

GO

GRANT SELECT ON dbo.[FB_RESTRICT_ASSIGN] TO PUBLIC

GO

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


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

CREATE  VIEW dbo.DOCUMENTS_ESN_G_TABLE
AS
SELECT
	[LINK]			= S.LINK_UP,
	[ORDERS]		= S.ORDERS,
	[TAB_NUMER]	 	= E.TAB,
	[NAME_EMPL]	 	= RTRIM(FM) + ' ' + SUBSTRING(RTRIM(IM),1,1) + '.' + SUBSTRING(RTRIM(OT),1,1) + '.',
	[REF_PHYS_PERS] 	= E.PERS_LINK,
	[REF_EMPL] 		= S.LINK_EMPL,
	[SUMMA_BASE]		= S.SUMMA_BASE,
	[CALC_TAX]		= S.CALC_TAX,
	[DED_M]			= S.DED_M,
	[INV_M]			= S.INV_M,
	[SUM_DED]		= S.SUM_DED,
	[SUMMA]			= S.SUMMA,
	[TOTAL_DED]		= S.TOTAL_DED,
	[TOTAL_SUM]		= S.TOTAL_SUM,
	[TOTAL_TAX]		= S.TOTAL_TAX,
	[CODE_PAY]		= P.CODE,
	[NAME_PAY]		= P.[NAME],
	[REF_PAY]		= S.LINK_PAY,
	[STATUS]		= (CASE WHEN S.STATUS = 1 THEN 'наемный рабочий' ELSE 'инвалид' END),
	[LINK_VKR] 		=  S.LINK_VKR,
	[NAME_VKR]		= F.CODE,
	[WAY_CALC]		= P.WAY_CALC,
	[SUBDIV_NAME],
	[POST_NAME],
	S.LINK_EKR,
	CODE_EKR = EKR.CODE,
	S.PERC,
	S.TARIF,
	S.SPECO,
	NSPECO = SPR.CODE
FROM 
	dbo.SDOC_ESN_TABLE S 
	INNER JOIN dbo.SD_EMPL E ON S.LINK_EMPL = E.LINK
	INNER JOIN dbo.PAYS P ON P.LINK  = S.LINK_PAY
	INNER JOIN dbo.KOSGU EKR ON EKR.LINK = S.LINK_EKR
	LEFT JOIN dbo.SAL_SFIN F ON F.LINK = S.LINK_VKR
	LEFT JOIN dbo.SZV4_SPR SPR ON SPR.LINK = S.SPECO
GO

GRANT SELECT ON dbo.[DOCUMENTS_ESN_G_TABLE] TO PUBLIC

GO


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

GO


CREATE    FUNCTION dbo.DICTIONARY_STAFF_FN(@dDATE DATETIME = null) 
RETURNS @RES TABLE
(
	link INT, 
	staff_link INT,
	dep_link INT,
	subdiv_link INT,
	subdiv_code VARCHAR(5),
	subdiv_name VARCHAR(254),
	post_link INT,
	post_code VARCHAR(10),
	post_name VARCHAR(254),
	num_stake NUMERIC(5,2),
	free_stakes NUMERIC(6,2), 
	oklad NUMERIC(18,2),
	ets_razr INT,
	ets_razr2 INT,
	kat_link INT,	
	kat_CODE VARCHAR(3),
	kat_name VARCHAR(50),
	gossl TINYINT,
	post_type_name VARCHAR(254),
	fin INT, 
	fin_fond INT, 
	kat_gos_link INT,
	[kat_gos_CODE] VARCHAR(2),
	[kat_gos_name] VARCHAR(50),
	gr_gos_link INT,
	[gr_gos_CODE] VARCHAR(1),
	[gr_gos_name] VARCHAR(60),
	date_begin DATETIME,
	date_end DATETIME,
	[deleted] TINYINT,
	LINK_KBK INT,
	CODE_KBK VARCHAR(20),
	NAME_KBK VARCHAR(120),
	--
	DEL_SUBDIV TINYINT,
	date_begin_s DATETIME,
	SUB_PARENT VARCHAR(254),

	-- ПЕРСОНИФИЦИРОВАННЫЙ УЧЕТ
	[TERR_USL] INT,
	[TERR_USL_N] VARCHAR(30),
	TERR_RK NUMERIC(3,2),
	[OSOB_USL] INT,
	[OSOB_USL_N] VARCHAR(30),
	[POS_SP] INT,
	[POS_SP_N] VARCHAR(30),
	[POS_SP2] INT,
	[POS_SP2_N] VARCHAR(30),
	[SPO_UT] INT,
	[SPO_UT_N] VARCHAR(30),
	[DOS_USL] INT,
	[DOS_USL_N] VARCHAR(30),
	[PED_MED] NUMERIC(3,2),
	[COD_PROF] INT,
	[COD_PROF_N] VARCHAR(30),
	[OSN_STRAH] INT,
	[OSN_STRAH_N] VARCHAR(30),
	[CAT_NZP_LINK] INT,
	[CAT_NZP_CODE] varchar(3),
	[CAT_NZP_NAME] VARCHAR(254),
	[SPHERE_LINK] INT,
	[SPHERE_NAME]  VARCHAR(30)
)

BEGIN

--@sa_dict_pays_staff
DECLARE @sa_dict_pays_staff TABLE (LINK_UP INT, SUMMA NUMERIC(18,2) )
INSERT INTO @sa_dict_pays_staff (LINK_UP, SUMMA)
SELECT LINK_UP, sum(SUMMA) FROM dbo.sa_dict_pays_staff(@dDATE,0) WHERE Actual = 1 and isOklad = 1 GROUP BY LINK_UP

--@SUBDIVISION
DECLARE @SUBDIVISION TABLE (LINK INT, CODE VARCHAR(5), NAME VARCHAR(254), deleted TINYINT, PARENT_NAME VARCHAR(254))
INSERT INTO @SUBDIVISION (LINK, CODE, NAME, deleted, PARENT_NAME)
SELECT LINK, CODE, NAME, deleted, PARENT_NAME FROM SUBDIVISION(@dDATE)


SET @dDate = isnull(@dDate, (select workdate from user_info) )

INSERT INTO @RES
SELECT 
	sh.link, 
	[staff_link] = s.link, sh.dep_link,
	s.subdiv_link,
	[subdiv_code] = ISNULL(sd.code,''),
	[subdiv_name] = ISNULL(SD.NAME,''),
	s.post_link,
	[post_code] = ISNULL(P.CODE,''),
	[post_name] = ISNULL(P.NAME,''),
	s.num_stake,
	[free_stakes_new] = FS.FREE_STAKES,
	oklad = COALESCE(Oklad.SUMMA,0),
	s.ets_razr,
	s.ets_razr2,
	s.kat_link,	
	[kat_CODE] = K.CODE,
	[kat_name] = K.name,
	s.gossl,
	[post_type_name] = pt.name,
	s.fin, s.fin_fond, 
	s.kat_gos_link,
	[kat_gos_CODE] = KG.CODE,
	[kat_gos_name] = KG.name,
	s.gr_gos_link,
	[gr_gos_CODE] = GG.CODE,
	[gr_gos_name] = GG.name,
	date_begin = (SELECT min(date_begin) FROM staff WHERE link_up=sh.link),
	date_end = (SELECT max(date_end) FROM staff WHERE link_up=sh.link),
	[deleted] = case when @dDate between s.date_begin and s.date_end then 0 else 1 end,
	LINK_KBK 	= KBK.LINK,
	CODE_KBK	= KBK.CODE,
	NAME_KBK	= KBK.[NAME],
	--
	DEL_SUBDIV	= SD.deleted,
	date_begin_s = s.date_begin,
	SUB_PARENT = SD.PARENT_NAME,

	-- ПЕРСОНИФИЦИРОВАННЫЙ УЧЕТ
	[TERR_USL] = S.TERR_USL_TRUD,
	[TERR_USL_N] = (SELECT TOP 1 code FROM SA_SZV4_SPR WHERE SPR_CODE = 'TERR_USL' AND LINK = S.TERR_USL_TRUD),
	S.TERR_RK,
	[OSOB_USL] = S.OSOB_USL_TRUD,
	[OSOB_USL_N] = (SELECT TOP 1 code FROM SA_SZV4_SPR WHERE SPR_CODE = 'OSOB_USL_TRUDA' AND LINK = S.OSOB_USL_TRUD),
	[POS_SP] = S.COD_POS_SPISOK,
	[POS_SP_N] = (SELECT TOP 1 code FROM SA_SZV4_SPR WHERE SPR_CODE LIKE 'SPISOK1' AND LINK = S.COD_POS_SPISOK),
	[POS_SP2] = S.COD_POS_SPISOK2,
	[POS_SP2_N] = (SELECT TOP 1 code FROM SA_SZV4_SPR WHERE SPR_CODE LIKE 'SPISOK2' AND LINK = S.COD_POS_SPISOK2),
	[SPO_UT] = S.COD_SPO_USL_TRUD,
	[SPO_UT_N] = (SELECT TOP 1 code FROM SA_SZV4_SPR WHERE SPR_CODE LIKE 'SPO_USL_TRUDA' AND LINK = S.COD_SPO_USL_TRUD),
	[DOS_USL] = S.USL_DOSROCH_PENS,
	[DOS_USL_N] = (SELECT TOP 1 code FROM SA_SZV4_SPR WHERE SPR_CODE = 'DOSR_NAZN_PEN_OSNOV' AND LINK = S.USL_DOSROCH_PENS),
	[PED_MED] = S.STAVKA_PED_MED,
	[COD_PROF] = S.COD_PROF,
	[COD_PROF_N] = (SELECT TOP 1 code FROM SA_SZV4_SPR WHERE SPR_CODE = 'LGOT_PROFES' AND LINK = S.COD_PROF),
	[OSN_STRAH] = S.OSNOVANIE,
	[OSN_STRAH_N] = (SELECT TOP 1 code FROM SA_SZV4_SPR WHERE SPR_CODE = 'ISCHISL_STAZH_OSNOV' AND LINK = S.OSNOVANIE),
	[CAT_NZP_LINK] = s.CAT_NZP_LINK ,
	[CAT_NZP_CODE] = (case when isnull(s.CAT_NZP_LINK,0) <> 0 then  (select CODE from PERS_CATEGORY_BY_SPHERE where link =  s.CAT_NZP_LINK) else null end),
	[CAT_NZP_NAME] = (case when isnull(s.CAT_NZP_LINK,0) <> 0 then  (select NAME_CAT from PERS_CATEGORY_BY_SPHERE where link =  s.CAT_NZP_LINK) else '' end),
	[SPHERE_LINK] =  s.SPHERE_LINK, 
	[SPHERE_NAME] = (case when isnull(s.SPHERE_LINK,0) <> 0 then  (select NAME from STO_SPHERES where link =  s.SPHERE_LINK) else '' end)
	
FROM 
	dbo.user_info ui
	INNER JOIN dbo.staff_head sh ON sh.dep_link = ui.dep_link or ui.code_task = 'KADRY'
	INNER JOIN dbo.staff s ON s.link_up=sh.link and
		s.date_begin=isnull((SELECT max(date_begin) FROM staff WHERE link_up=s.link_up and @dDate>=date_begin),
					(SELECT min(date_begin) FROM staff WHERE link_up=s.link_up and @dDate <=date_begin))
	INNER JOIN dbo.post_types pt ON s.gossl=pt.link
	LEFT JOIN @sa_dict_pays_staff Oklad ON sh.link = Oklad.LINK_UP
	LEFT OUTER JOIN @SUBDIVISION SD ON SD.LINK = s.subdiv_link
	LEFT OUTER JOIN POST P ON P.LINK = s.post_link 
	LEFT OUTER JOIN KATEG K ON K.LINK = s.KAT_link
	LEFT OUTER JOIN KAT_GOS KG ON KG.LINK = S.kat_gos_link
	LEFT OUTER JOIN GR_GOS GG ON GG.LINK = S.gr_gos_link
	LEFT JOIN dbo.SAL_SFIN KBK on KBK.LINK = S.LINK_KBK
	LEFT JOIN DBO.KJ_GET_FREE_STAKES_STAFF(@dDate, -1) FS ON FS.STAFF_LINK = sh.LINK

RETURN

END




GO


GRANT SELECT ON dbo.[DICTIONARY_STAFF_FN] TO PUBLIC

GO




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

GO

CREATE  VIEW [dbo].DICTIONARY_STAFF_ALL
AS
SELECT s.link, s.link_up, 
	s.subdiv_link,
	[subdiv_code] = (SELECT top 1 code FROM subdiv WHERE link_up = s.subdiv_link and (s.date_begin between date_begin and date_end or s.date_begin < date_begin and s.date_end > date_end or s.date_end between date_begin and date_end)),
	[subdiv_name] = (SELECT top 1 [name] FROM subdiv WHERE link_up = s.subdiv_link and (s.date_begin between date_begin and date_end or s.date_begin < date_begin and s.date_end > date_end or s.date_end between date_begin and date_end)),
	s.post_link,
	[post_code] =	DP.CODE,
	[post_name] = DP.NAME,
	s.num_stake,
	[con_stake] = s.num_stake,
--	s.oklad, 
	oklad = COALESCE(Oklad.SUMMA,0),
	s.ets_razr,
	s.ets_razr2,
	s.kat_link,
	[kat_CODE] = convert(varchar(3), K.CODE),
	[kat_name] = convert(varchar(50), K.name),
	s.gossl,
	[post_type_name] = pt.name,
	s.fin, s.fin_fond, 
	s.kat_gos_link,
	[kat_gos_CODE] = convert(varchar(2), KG.CODE),
	[kat_gos_name] = convert(varchar(50), KG.name),
	s.gr_gos_link,
	[gr_gos_CODE] = convert(varchar(2), GG.CODE),
	[gr_gos_name] = convert(varchar(100), GG.name),
	s.date_begin, s.date_end,
	LINK_KBK 	= KBK.LINK,
	CODE_KBK	= KBK.CODE,
	NAME_KBK	= KBK.[NAME],
	-- ПЕРСОНИФИЦИРОВАННЫЙ УЧЕТ
	[TERR_USL] = S.TERR_USL_TRUD,
	[TERR_USL_N] = (SELECT TOP 1 code FROM SA_SZV4_SPR WHERE SPR_CODE = 'TERR_USL' AND LINK = S.TERR_USL_TRUD),
	S.TERR_RK,
	[OSOB_USL] = S.OSOB_USL_TRUD,
	[OSOB_USL_N] = (SELECT TOP 1 code FROM SA_SZV4_SPR WHERE SPR_CODE = 'OSOB_USL_TRUDA' AND LINK = S.OSOB_USL_TRUD),
	[POS_SP] = S.COD_POS_SPISOK,
	[POS_SP_N] = (SELECT TOP 1 code FROM SA_SZV4_SPR WHERE SPR_CODE LIKE 'SPISOK1' AND LINK = S.COD_POS_SPISOK),
	[POS_SP2] = S.COD_POS_SPISOK2,
	[POS_SP2_N] = (SELECT TOP 1 code FROM SA_SZV4_SPR WHERE SPR_CODE LIKE 'SPISOK2' AND LINK = S.COD_POS_SPISOK2),
	[SPO_UT] = S.COD_SPO_USL_TRUD,
	[SPO_UT_N] = (SELECT TOP 1 code FROM SA_SZV4_SPR WHERE SPR_CODE LIKE 'SPO_USL_TRUDA' AND LINK = S.COD_SPO_USL_TRUD),
	[DOS_USL] = S.USL_DOSROCH_PENS,
	[DOS_USL_N] = (SELECT TOP 1 code FROM SA_SZV4_SPR WHERE SPR_CODE = 'DOSR_NAZN_PEN_OSNOV' AND LINK = S.USL_DOSROCH_PENS),
	[PED_MED] = S.STAVKA_PED_MED,
	[COD_PROF] = S.COD_PROF,
	[COD_PROF_N] = (SELECT TOP 1 code FROM SA_SZV4_SPR WHERE SPR_CODE = 'LGOT_PROFES' AND LINK = S.COD_PROF),
	[OSN_STRAH] = S.OSNOVANIE,
	[OSN_STRAH_N] = (SELECT TOP 1 code FROM SA_SZV4_SPR WHERE SPR_CODE = 'ISCHISL_STAZH_OSNOV' AND LINK = S.OSNOVANIE),
	[CAT_NZP_LINK] = s.CAT_NZP_LINK ,
	[SPHERE_LINK]  = s.SPHERE_LINK
FROM dbo.staff_head sh
INNER JOIN dbo.staff s ON s.link_up=sh.link
INNER JOIN dbo.post_types pt ON s.gossl=pt.link
LEFT JOIN (select LINK_UP, sum(SUMMA) as SUMMA from dbo.sa_dict_pays_staff(default,0) where Actual = 1 and isOklad = 1 GROUP BY LINK_UP) Oklad ON sh.link = Oklad.LINK_UP
LEFT OUTER JOIN DICTIONARY_POST DP ON DP.LINK = s.post_link 
LEFT OUTER JOIN KATEG K ON K.LINK = s.KAT_link
LEFT OUTER JOIN KAT_GOS KG ON KG.LINK = S.kat_gos_link
LEFT OUTER JOIN GR_GOS GG ON GG.LINK = S.gr_gos_link
LEFT JOIN dbo.SAL_SFIN KBK on KBK.LINK = S.LINK_KBK





GO


GRANT SELECT ON dbo.[DICTIONARY_STAFF_ALL] TO PUBLIC

GO



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

GO

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

CREATE        FUNCTION dbo.PrintDoc_GetDepData2(@varKSnLinkDep INT)
RETURNS @varKSRET TABLE 
	(DEP_LINK INT, longname varchar (2000), ORGNAME VARCHAR(254), GLBUH VARCHAR(250),
		CHIEF VARCHAR(250), CHIEF_DIV VARCHAR(250), CHIEF_FIN VARCHAR(250), CHIEF_POST VARCHAR(120), okpo varchar(40),okato varchar(14), OKTMO VARCHAR(14),
		sono char(4),REGION VARCHAR(254),
		OKVED VARCHAR (10), OKVED1 VARCHAR (10),DEP_FULL_NAME varchar(2000),VED varchar(3), VED_NAME VARCHAR(250),
        [isp] VARCHAR(250),
        [isp_post] VARCHAR(250),
        [isp_tel] VARCHAR(250),
        cb_name VARCHAR(250),
        cb_ogrn VARCHAR(250),
        cb_inn VARCHAR(250),
        cb_kpp VARCHAR(250),
        cb_address VARCHAR(250),
        ul_fio VARCHAR(250),
        ul_post VARCHAR(250))
AS BEGIN
	DECLARE @varKSGLBUH VARCHAR(250), @varKSCHIEF VARCHAR(250), @varKSCHIEF_POST VARCHAR(120),
		@boss_div varchar(250), @boss_fin_econ varchar(250)

	SELECT 
		@varKSGLBUH = GLBUH.SHORT_NAME
	FROM dbo.GetOtvFaceData(@varKSnLinkDep, 'Главный бухгалтер') GLBUH 
	WHERE GLBUH.link_dep = @varKSnLinkDep

	SELECT 
		@varKSCHIEF = CHIEF.SHORT_NAME,
		@varKSCHIEF_POST = CHIEF.POST_NAME
	FROM dbo.GetOtvFaceData(@varKSnLinkDep, 'Руководитель') chief 
	WHERE chief.link_dep = @varKSnLinkDep

	if isnull(@varKSGLBUH,'') = ''
	begin
		select @varKSGLBUH = BUH from report_dict_web_print where link_org = @varKSnLinkDep
	end

	if isnull(@varKSCHIEF,'') = ''
	begin
		select @varKSCHIEF = BOSS from report_dict_web_print where link_org = @varKSnLinkDep
	end

	select @boss_div = boss_div, @boss_fin_econ = boss_fin_econ
	from report_dict_web_print where link_org = @varKSnLinkDep

	INSERT INTO @varKSRET
	SELECT DD1.LINK,
		CONVERT(VARCHAR(254),DD1.FULL_NAME) AS FULL_NAME, CONVERT(VARCHAR(254),DD1.NAME) AS NAME,
		@varKSGLBUH,
		@varKSCHIEF,
		@boss_div,
		@boss_fin_econ,
		@varKSCHIEF_POST,
		DD1.OKPO,
		DD1.OKATO,
		DD1.OKTMO,
		convert(varchar(4), DD1.NALOG),
		(SELECT RTRIM(LTRIM(NAME)) + ' ' + LTRIM(RTRIM(SOCR)) FROM DICTIONARY_KLADR WHERE CODE = LEFT(DD1.NALOG, 2) + REPLICATE('0', 11)),
		DD1.OKVED,
		REPLACE (DD1.OKVED, '.', ''),
        CONVERT(VARCHAR(2000),DD1.FULL_NAME),
        left(DD1.VED,3),
        DD1.[VED_NAME],
        W.[isp],
        W.[isp_post],
        W.[isp_tel],
        W.cb_name,
        W.cb_ogrn,
        W.cb_inn,
        W.cb_kpp,
        W.cb_address,
        W.ul_fio,
        W.ul_post
	FROM DICTIONARY_DEPARTMENT DD1 LEFT JOIN dbo.report_dict_web_print W ON DD1.[LINK] = W.[link_org]
	WHERE DD1.LINK = @varKSnLinkDep
	RETURN
   
END


GO


GRANT SELECT ON dbo.[PrintDoc_GetDepData2] TO PUBLIC

GO




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

GO

CREATE VIEW [dbo].DICTIONARY_STAFF
AS


SELECT *
FROM dbo.DICTIONARY_STAFF_FN(default)



GO


GRANT SELECT ON dbo.[DICTIONARY_STAFF] TO PUBLIC

GO



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

GO

CREATE  FUNCTION dbo.PrintFSSRep_GetDpData(@varKSnLinkDep int)
RETURNS TABLE 
AS
	RETURN 
	SELECT 
		DD1.OKPO AS OKPO1, 
		DD1.INN AS INN1, DD1.KPP AS KPP1, DD1.FULL_NAME, 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,
		RTRIM(CHIEF.FM) + ' ' + LEFT(CHIEF.IM, 1) + '. ' + LEFT(CHIEF.OT,1) + '.' AS CHIEF_FIO,
		RTRIM(CHIEF.PHONE) AS CH_PHONE,
		RTRIM(GLBUH.FM) + ' ' + LEFT(GLBUH.IM, 1) + '. ' + LEFT(GLBUH.OT,1) + '.' AS GLBUH_FIO,
		replace(replace(replace(REPLACE(RTRIM(GLBUH.PHONE),'-',''),' ',''),'(',''),')','') AS GL_PHONE,
		DD1.OGRN,
		(CASE WHEN ( convert(varchar(5),(select value from S_OPTIONS where object = (select top 1 link from s_objects where code = 'NASTR_USE_OKATO_OKTMO'))) = '1' 
				  or convert(varchar(5),(select value from S_OPTIONS where object = (select top 1 link from s_objects where code = 'NASTR_USE_OKATO_OKTMO'))) = 'ОКАТО') then DD1.OKATO ELSE '' END) AS 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, DA.REGION, DA.REGCODE, DA.RAION, DA.GOROD, DA.NASEL, DA.STREET, DA.HOUSE, DA.KORP, DA.FLAT,
		TFOMS_RNUM = DD1.TFOMS_REG_NUM,
		TFOMS_KT = DD1.TFOMS_KT,
		DD1.FSS_KP_PC1, DD1.FSS_KP_PC2, DD1.FSS_KP_PC3
	FROM DICTIONARY_DEPARTMENT DD1 
		LEFT OUTER JOIN DICTIONARY_DEPARTMENT DD2 ON DD1.IMNS_LINK = DD2.LINK
		LEFT OUTER JOIN dbo.GetOtvFaceData(@varKSnLinkDep, 'Руководитель') chief on chief.link_dep = dd1.link
		LEFT OUTER JOIN dbo.GetOtvFaceData(@varKSnLinkDep, 'Главный бухгалтер') GLBUH ON GLBUH.link_dep = dd1.link
		LEFT JOIN DBO.DEP_ADRESS(@varKSnLinkDep) DA ON 1=1
	WHERE DD1.LINK = @varKSnLinkDep





GO


GRANT SELECT ON dbo.[PrintFSSRep_GetDpData] TO PUBLIC

GO



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

GO

-- ФУНКЦИЯ ДЛЯ РАСЧЕТА ОСТАТКОВ ПО АВАНСОВОМУ ОТЧЕТУ -- 
CREATE  FUNCTION [dbo].BK_AO_GetTableRest (@parm_intLINK_AO INT)
RETURNS @TABLE_REST_ALL TABLE ([ACCOUNT] [INT],
			[cSOURCE] [CHAR] (1),
			[cANALIT] [CHAR] (2),
			[cUSER] [CHAR] (4),
		 	[EKR] [INT],
			[SUMMA] [NUMERIC] (28,4),
			[TYPE_SUM] [SMALLINT])

AS
BEGIN
	DECLARE @intLINK_EMPL	INT,
		@intLINK_SUB	INT,
		@dDATE_AO	DATETIME,
		@dDATE_PROV_AO	DATETIME,
		@intLINK_KBK	INT,
		@intDEP_LINK	INT,
		@intACC_LINK	INT,
		@dDATE_REST	DATETIME,
		@intAC208	INT
	
	SELECT
		@intLINK_EMPL	=	AO.EMP_LINK,
		@intLINK_SUB	=	AO.OTDEL_LINK,
		@dDATE_AO	=	AO.DATE,
		@intLINK_KBK	=	AO.KBK_LINK,
		@intDEP_LINK	=	G.DEP, 
		@intACC_LINK	=	G.ACC,
		@dDATE_PROV_AO	=	G.DATE_PROV
	FROM dbo.BV_DOC_AVANSE_REP AO
	INNER JOIN dbo.G_PROV	G ON (G.LINK = AO.LINK)
	WHERE AO.LINK = @parm_intLINK_AO
	
	-- Считаем остатки по сотруднику на 208 счете -- 
	SET @dDATE_REST = @dDATE_AO + 1
	SELECT @intAC208 = LINK FROM dbo.S_ACCOUNTS WHERE CODE = '208'
	
	DECLARE @TABLE_REST TABLE (ACCOUNT INT, cSOURCE CHAR (1), cANALIT CHAR (2), cUSER CHAR (4),
			 EKR INT, SUMMA NUMERIC (28,4))
		
	INSERT INTO @TABLE_REST
	SELECT
		T1.ACCOUNT,
		SA.cSOURCE,
		SA.cANALIT,
		SA.cUSER,
		T1.EKR,
		CASE 
			WHEN SA.S_ACTIVE = 1 THEN T1.D_SUMMA
			ELSE T1.K_SUMMA
		END AS SUMREST
	FROM dbo.ARestTableByDate (@dDATE_REST, @intAC208) T1
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = T1.ACCOUNT)
	WHERE T1.EMP = @intLINK_EMPL
		AND T1.DEP_LINK = @intDEP_LINK
		AND (@intLINK_KBK IS NULL OR T1.KBK = @intLINK_KBK)
		AND (SA.AP_SUB = 0 OR @intLINK_SUB IS NULL OR T1.SUB = @intLINK_SUB)
	
	-- Если АО не проведен, считаем расходы по АО (табличная часть) -- 
	DECLARE @TAB_AVANSE TABLE (ACCOUNT INT, cSOURCE CHAR (1), cANALIT CHAR (2), cUSER CHAR (4),
			 EKR INT, SUMMA NUMERIC (28,4))
	
	IF @dDATE_PROV_AO IS NULL
		INSERT INTO @TAB_AVANSE
		SELECT
			SA.LINK,
			SA.cSOURCE,
			SA.cANALIT,
			SA.cUSER,
			G.EKR_LINK_KT,
			CASE 
				WHEN SA.S_ACTIVE = 1 THEN SUM (G.SUMACCEPTED)
				ELSE -SUM (G.SUMACCEPTED)
			END AS SUMREST
		FROM dbo.BK_DOC_TABLE_AO_FN (@parm_intLINK_AO) G
		INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = G.KT)
		GROUP BY
			SA.LINK,
			SA.cSOURCE,
			SA.cANALIT,
			SA.cUSER,
			G.EKR_LINK_KT,
			SA.S_ACTIVE 
	
	-- Собираем итоговые остатки ()--
	INSERT INTO @TABLE_REST_ALL
	SELECT
		ISNULL (R.ACCOUNT, A.ACCOUNT) AS ACCOUNT,
		ISNULL (R.cSOURCE, A.cSOURCE) AS cSOURCE,
		ISNULL (R.cANALIT, A.cANALIT) AS cANALIT,
		ISNULL (R.cUSER, A.cUSER) AS cUSER,
		ISNULL (R.EKR, A.EKR) AS EKR,
		ISNULL (R.SUMMA, 0) - ISNULL (A.SUMMA, 0),
		0
	FROM @TABLE_REST R
	FULL JOIN @TAB_AVANSE A ON (A.ACCOUNT = R.ACCOUNT
		AND A.EKR = R.EKR)

	UPDATE @TABLE_REST_ALL SET TYPE_SUM = CASE 
							WHEN SUMMA > 0 THEN 1
							WHEN SUMMA < 0 THEN -1
							ELSE TYPE_SUM
						END

	RETURN
END

GO

GRANT SELECT ON dbo.[BK_AO_GetTableRest] TO PUBLIC

GO


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


GO

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


CREATE	procedure dbo.BB_EXPORT_HEAD (@iModelLink int)
as
begin

-- Блок KS
DECLARE @varKSstr 	VARCHAR(40), 
	@varKSS 	VARCHAR(15), 
	@varKSV1 	VARCHAR(5), 
	@varKSV2 	VARCHAR(5), 
	@varKSR 	VARCHAR(5), 
	@varKSF 	VARCHAR(5)
EXEC X_GET_PROP 'PROJECT','SIGNATURE', @varKSS OUTPUT 
EXEC X_GET_PROP 'PROJECT','VERSION_MAJOR', @varKSV1 OUTPUT 
EXEC X_GET_PROP 'PROJECT','VERSION_MINOR', @varKSV2 OUTPUT 
EXEC X_GET_PROP 'PROJECT','VERSION_RELEASE', @varKSR OUTPUT 
EXEC X_GET_PROP 'PROJECT','VERSION_FIX', @varKSF OUTPUT 
SET @varKSstr = @varKSV1 + '.' + @varKSV2 + '.' + @varKSF 

SELECT	NUM_VER = MODEL_VER, 
	FORMER	= 'SMETA-KS', 
	FORM_VER = @varKSstr, 
	NORM_DOC,
	0 as link,
	0 as link_up
from dbo.EXPORT_MODELS
where LINK_MODEL = @iModelLink

END

GO

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

GO
CREATE PROCEDURE DBO.[SS_DOP_VZNOS_PLAT] (@PERIOD_BEG DATETIME, @PERIOD_END DATETIME, @DEP_LINK INT, @SUMMA NUMERIC(18,2) OUTPUT)
--Перечисленная сумма НДФЛ по организации за период с учётом остатка на начало года
AS
BEGIN

	IF @PERIOD_BEG IS NOT NULL AND @PERIOD_END IS NOT NULL BEGIN

		exec dbo.BufferClear 'DT'
		exec dbo.BufferClear 'KT'

		INSERT INTO BUFFER (link, id)
		select link, 'DT' from s_accounts where cSinth = '304' and cAnalit = '03'

		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')

		select  @SUMMA = 
			ISNULL(
					(SELECT SUM(P.SUMMA)
					from 
						dbo.AProvByBufferConditionsShortDate('19900101', '20991231', '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
					WHERE
						P.DEP_LINK = @DEP_LINK
						AND
						G.DEP = @DEP_LINK
						AND
						PA.SGU_CODE = '160'
						AND
						CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.')) BETWEEN MONTH(@PERIOD_BEG) AND MONTH(@PERIOD_END)
						AND
						CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,3,'.')) = YEAR(@PERIOD_BEG)					
						),
					0)	

		exec dbo.BufferClear 'DT'
		exec dbo.BufferClear 'KT'
	

	END
	
END
RETURN 0	






GO


GRANT EXECUTE ON dbo.[SS_DOP_VZNOS_PLAT] TO PUBLIC

GO


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

GO

CREATE  PROCEDURE [dbo].X_UPDATE_STAVKI_PF
	@varKSintLINK	int	OUTPUT,
	@varKSintLinkPays int,
	@varKSdatDATE	datetime,
	@varKSchrCOMMENT	varchar(50),
	@varKSnumPREDEL	numeric(15,2),
	@varKSnumPERCENT1	numeric(6,2),
	@varKSnumPERCENT2	numeric(6,2),
	@varKSnumPERCENT3	numeric(6,2),
	@TARIF TINYINT = 1,
	@SPECO INT = null
AS
DECLARE @varKSRowCount	int,
			@varKSSQLError	int,
			@varKStrancount	int
SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
	IF @varKSintLINK is null OR @varKSintLINK = 0
	BEGIN
		INSERT INTO STAVKI_PF WITH (ROWLOCK) (LINK_PAYS,[DATE],COMMENT,PREDEL,PERCENT1,PERCENT2,PERCENT3,TARIF,SPECO )
		 VALUES (@varKSintLinkPays,@varKSdatDATE,@varKSchrCOMMENT,@varKSnumPREDEL,@varKSnumPERCENT1,@varKSnumPERCENT2,@varKSnumPERCENT3,@TARIF, @SPECO )
		SELECT @varKSSQLError = @@ERROR, @varKSintLINK = @@IDENTITY
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	ELSE
	BEGIN
		UPDATE STAVKI_PF WITH (ROWLOCK) 
		SET [LINK_PAYS] = @varKSintLinkPays, [DATE] =@varKSdatDATE, [COMMENT]=@varKSchrCOMMENT,PREDEL = @varKSnumPREDEL,
				PERCENT1 = @varKSnumPERCENT1,PERCENT2 = @varKSnumPERCENT2,PERCENT3 = @varKSnumPERCENT3, TARIF = @TARIF, SPECO = @SPECO 
		WHERE LINK=@varKSintLINK
		SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END
IF @@TRANCOUNT > @varKStrancount  
	COMMIT TRAN
RETURN 0

GO


GRANT EXECUTE ON dbo.[X_UPDATE_STAVKI_PF] TO PUBLIC

GO


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

GO
CREATE    PROCEDURE [dbo].[SD_REP_1NDFL2009]
	@varKScYear VARCHAR(4),
	@varKSnLinkEmpl INT = NULL,
	@varKSnLinkPers INT = NULL
AS BEGIN

	DECLARE @varKSnYear INT
	SET @varKSnYear = CAST(@varKScYear AS INT)
	--DECLARE @varKSnLinkPers int
	

	IF @varKSnLinkPers IS NULL
		SET @varKSnLinkPers = (SELECT TOP 1 PERS_LINK FROM dbo.EMPL WHERE LINK = @varKSnLinkEmpl)

	DECLARE @WORKDATE DATETIME, @DEP_LINK INT
	SELECT @WORKDATE = WORKDATE, @DEP_LINK = DEP_LINK FROM dbo.USER_INFO
	
	DECLARE @Today INT
	SET  @Today = CASE WHEN YEAR(@WORKDATE) = @varKSnYear THEN MONTH(@WORKDATE) ELSE 12 END
		
	SELECT 
		ISNULL((SELECT TOP 1 CONVERT(VARCHAR(10), DD3.CODE) FROM dbo.DEPARTMENTS DD3 WHERE DD3.LINK = DD.IMNS_LINK), '') AS NALOG,
		ISNULL(INN, '') AS INN,
		ISNULL(KPP, '') AS KPP,
		ISNULL(OKATO, '') AS OKATO,
		ISNULL(OKTMO, '')AS OKTMO,
		CONVERT(VARCHAR (254),(ISNULL(FULL_NAME, ''))) AS FULL_NAME
	INTO #DEP
	FROM dbo.DEPARTMENTS DD
	WHERE DD.link = @DEP_LINK

CREATE TABLE #RES0 (
	LINK_FACE INT,
	INNFIZ VARCHAR(20),
	NUMB_SERT VARCHAR(20),
	STATUS VARCHAR(1),
	FM VARCHAR(254),
	IM VARCHAR(254),
	OT VARCHAR(254),
	KDVD VARCHAR(4),
	SERNOM VARCHAR(254), 
	BIRTH DATETIME,
	GRAZD VARCHAR(3),
	KSTR VARCHAR(3),
	LINK_ADR INT,
	IND_ADR VARCHAR(10),
	REGION VARCHAR(4),
	RAION VARCHAR(254),
	GOROD VARCHAR(254),
	NASEL VARCHAR(254),
	STREET VARCHAR(254),
	HOUSE VARCHAR(20),
	KORP VARCHAR(10),
	FLAT VARCHAR(10),
	HAS_VICHET TINYINT,

	/*HAS103 TINYINT,
	HAS104 TINYINT,
	HAS105 TINYINT,
	HAS108 TINYINT,
	HAS109 TINYINT,
	HAS110 TINYINT,
	HAS111 TINYINT,
	HAS112 TINYINT,
	HAS113 TINYINT,
	*/
	STR_MD varchar(100),
	STR_RCH varchar(180),
	CHILDREN INT,
	DOLG_NP NUMERIC(20,2),
	DOLG_NA NUMERIC(20,2),
	OLD13 NUMERIC(20,2),
	DATE_BEG DATETIME,
	SNN NUMERIC(8,0), SNU NUMERIC(8,0),
	DOLG_NPEND NUMERIC(8,0), DOLG_NAEND NUMERIC(8,0) 
)

EXEC dbo.BufferClear
exec dbo.BufferPush @varKSnLinkPers, 'REP2NDFL'

----
CREATE TABLE #EMPL (LINK INT, PERS_LINK INT, DATE_BEGIN DATETIME, )
INSERT INTO #EMPL (LINK, PERS_LINK, DATE_BEGIN)
SELECT LINK, PERS_LINK, DATE_BEGIN FROM dbo.SD_EMPL_FN(@varKSnLinkEmpl,DEFAULT,DEFAULT,@DEP_LINK)

----- >>>>>
CREATE TABLE  #DEDS ( RECNO INT IDENTITY(1,1) , ref_ded INT,  CODE_DED INT, [type] TINyINT, SUMMA numeric(18,2), for_child TINyINT) 
INSERT INTO #DEDS (ref_ded, CODE_DED, [type], SUMMA, for_child)
SELECT  t1.REF_PAY, t1.CODE, T1.[type], t1.SUMMA , for_child = (case when EXISTS(select * from dbo.DICTIONARY_MROT_TABLE1 where code = t1.code and [type] = T1.[type] and name like('%ребенка%')) then 2 else 1 end)
FROM 
	dbo.DICTIONARY_MROT_TABLE1 t1
WHERE
	t1.link_minrot = (SELECT TOP 1 link FROM dbo.DICTIONARY_MROT ss WHERE year(ss.period) <= @varKSnYear ORDER BY ss.period DESC)
ORDER BY t1.CODE
----- >>>>>

---

INSERT INTO #RES0 (
	LINK_FACE,
	INNFIZ,
	NUMB_SERT,
	STATUS,
	FM, IM, OT,
	KDVD,
	SERNOM, 
	BIRTH,
	GRAZD,
	KSTR,
	LINK_ADR,
	IND_ADR,
	REGION,
	RAION,
	GOROD,
	NASEL,
	STREET,
	HOUSE,
	KORP,
	FLAT,
	HAS_VICHET,

/*	HAS103,
	HAS104,
	HAS105,
	HAS108,
	HAS109,
	HAS110,
	HAS111,
	HAS112,
	HAS113,
	
*/	
	STR_MD,
	STR_RCH,
	CHILDREN,
	DOLG_NP, DOLG_NA,
	DATE_BEG)


SELECT P.LINK, P.INN, P.INSUR_NUM, 
	CASE 
		WHEN P.RESIDENT IS NULL THEN ''
		WHEN P.RESIDENT = 1 THEN '1'
		WHEN P.RESIDENT = 0 THEN '2'
	END,
	RTRIM(P.FM), RTRIM(P.IM), RTRIM(P.OT),
	[KDVD] = (SELECT TOP 1 CODE FROM FACE_DOCUMENT WHERE LINK = P.DOC_LINK),
	P.DOC_NUM,
	P.BIRTHDATE,
	(SELECT TOP 1 CODE FROM CITIZENSHIP WHERE LINK = P.CITIZ_LINK),
	CASE WHEN P.RESIDENT IS NULL OR P.RESIDENT = 1 THEN ''
		ELSE ISNULL((SELECT TOP 1 CODE FROM CITIZENSHIP WHERE LINK = P.CITIZ_LINK), '1')
	END,
	ADR.LINK_ADDR,
	ADR.IND_ADR,
	ADR.REGION,
	ADR.RAION,
	ADR.GOROD,
	ADR.NASEL,
	ADR.STREET,
	ADR.HOUSE,
	ADR.KORP,
	ADR.FLAT, 
	0,
	/*0, 0, 0, 0, 0, 0, 0, 0, 0,*/
	'',
	'',
	[CHILDREN] = (SELECT COUNT(*) FROM KU_PERS_FAMILY 
				WHERE LINK = @varKSnLinkPers
			AND FAMILY_NAME IN ('Сын', 'Дочь', 'Пасынок', 'Падчерица')
			and datediff(yy, BIRTHDATE, dbo.ConvertDMY2Date(1,1,@varKSnYear)) <18),
	[DOLG_NP] = 0,
	[DOLG_NA] = (SELECT SUM(NDFL) FROM DICTIONARY_SAL_REMAIN 
			WHERE YEAR_SAL = @varKSnYear AND LINK_EMPL = E.LINK),
	[DATE_BEG] = E.date_begin
FROM
	dbo.PERSON P
	LEFT JOIN #EMPL E ON P.LINK = E.PERS_LINK
	LEFT JOIN dbo.NDFL_GET_ADDRESS() ADR ON P.LINK = ADR.LINK_FACE
WHERE 
	P.LINK = @varKSnLinkPers


	DECLARE @varKSStatus VARCHAR(1)
	Set @varKSStatus = COALESCE((SELECT TOP 1 STATUS FROM #RES0),1) /*резидент, не резидент*/


	UPDATE #RES0 SET DOLG_NP = -DOLG_NA, DOLG_NA = 0 WHERE DOLG_NA < 0
	IF (SELECT TOP 1 YEAR(DATE_BEG) FROM #RES0 ) = @varKSnYear
		UPDATE #RES0 SET OLD13 = ISNULL((SELECT SUM(SUMMA_TYP_INCOMS) FROM dbo.SD_EMPL_PREV_DOHOD WHERE LINK_EMPL = (SELECT TOP 1 LINK FROM dbo.EMPL WHERE DEP_LINK = @DEP_LINK AND PERS_LINK = @varKSnLinkPers AND dbo.ku_getemplstatus(LINK, DEFAULT) = 1)), 0)
	ELSE
		UPDATE #RES0 SET OLD13 = 0
---->>>>>>------

	DECLARE @CNT INT
	SELECT @CNT = COUNT(DISTINCT CODE_DED) FROM #DEDS
	
	DECLARE @I INT, @SQLS VARCHAR(4000), @FIELD VARCHAR(1000)
	SET @I=1
	WHILE @I <= @CNT BEGIN

		SET @FIELD= 'HAS' + RTRIM(LTRIM(STR((select CODE_DED from #DEDS where RECNO = @I and [TYPE] = 1) )))
		SET @SQLS= ' ALTER TABLE #RES0 ADD '+@FIELD+ ' TINYINT null ' 
		EXEC (@SQLS)

		SET @SQLS= ' UPDATE #RES0 SET '+@FIELD+ ' = 0  WHERE ' + @FIELD+ '  IS  NULL ' 
		EXEC (@SQLS)

		SET @FIELD= 'SUM' + RTRIM(LTRIM(STR((select CODE_DED from #DEDS where RECNO = @I and [TYPE] = 1) )))
		SET @SQLS= ' ALTER TABLE #RES0 ADD '+@FIELD+ ' numeric(18,2) null ' 
		EXEC (@SQLS)

		SET @SQLS= ' UPDATE #RES0 SET '+@FIELD+ ' = 0  WHERE ' + @FIELD+ '  IS  NULL ' 
		EXEC (@SQLS)



		SET @I=@I+1
	END		

---->>>>>>------
	-----	Подготовка данных
	Declare @isPrevPreiod tinyint
	--Суммы начислений включать в базу расчета в том месяце, в котором он был начислен.                   
	Set @isPrevPreiod = dbo.sa_get_option_by_code('NDFL_OPT6')
	Declare @SJC table (LINK_FACE int,PERS_LINK int, link_empl int, link_pays int, link_vkr int, link_ekr int, typ_per tinyint, typ_oper tinyint, summa numeric(18,2), period_begin datetime, date1 datetime, link_dep int, CODE_INC varchar(5))

	Insert into @SJC (LINK_FACE, PERS_LINK, link_empl, link_pays, link_vkr, link_ekr, typ_per, typ_oper, summa, period_begin, date1, link_dep, CODE_INC)
	Select 
		E.PERS_LINK, JC.PERS_LINK, JC.LINK_EMPL, P.LINK, link_vkr, COALESCE(JC.LINK_EKR,P.LINK_EKR), P.TYP_PER, P.OBJECT, summa, 
		period_begin = (case when @isPrevPreiod = 0 then JC.period_begin 
				else (Case 
						when JC.DATE_BEGIN < JC.period_begin and year(JC.DATE_BEGIN) = year(JC.period_begin) and d.code = 'DOCUMENTS_ADD_TABEL'
						then JC.DATE_BEGIN else JC.period_begin 
					end) 
				end),
		JC.DATE_BEGIN,
		JC.LINK_DEP,
		CODE_INC = CONVERT(VARCHAR(5), (SELECT DA.VALUE FROM DICTION_APP DA WHERE DA.LINK_UP = P.LINK_INC AND 
	        da.OBJECT =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'COLUMN_CODE_T_INC')))
	from 
		dbo.CALCULATE_JURNAL JC 
		INNER JOIN dbo.NDFL_GroupTax() T ON JC.LINK_PAYS=T.LINK_PAYS
		INNER JOIN dbo.EMPL E ON JC.LINK_EMPL = E.LINK
		INNER JOIN dbo.PAYS P ON JC.LINK_PAYS = P.LINK
		LEFT JOIN (Select d.link, o.code from sdoc d inner join dbo.s_objects o on d.object = o.link) d on jc.LINK_DOC = d.link
	where
		 (
				(@isPrevPreiod = 0 or coalesce(d.code,'') <> 'DOCUMENTS_ADD_TABEL') and 12 >= month(JC.PERIOD_BEGIN) and @varKSnYear = year(JC.PERIOD_BEGIN)
				or 
				@isPrevPreiod = 1 and coalesce(d.code,'') = 'DOCUMENTS_ADD_TABEL'
				and (12 >= month(JC.DATE_BEGIN) or 12 >= month(JC.PERIOD_BEGIN) )
				and (@varKSnYear = year(JC.DATE_BEGIN) or @varKSnYear = year(JC.PERIOD_BEGIN) )

			)
		AND JC.LINK_DEP = @DEP_LINK
		AND E.PERS_LINK = @varKSnLinkPers
	UNION ALL -- Информация по внештатнику	 
	Select 
		JC.PERS_LINK, JC.PERS_LINK, JC.LINK_EMPL, P.LINK, link_vkr, COALESCE(JC.LINK_EKR,P.LINK_EKR), P.TYP_PER, P.OBJECT, summa, 
		period_begin = (case when @isPrevPreiod = 0 then JC.period_begin 
				else (Case 
						when JC.DATE_BEGIN < JC.period_begin and year(JC.DATE_BEGIN) = year(JC.period_begin) and d.code = 'DOCUMENTS_ADD_TABEL'
						then JC.DATE_BEGIN else JC.period_begin 
					end) 
				end),
		JC.DATE_BEGIN,
		JC.LINK_DEP,
		CODE_INC = CONVERT(VARCHAR(5), (SELECT DA.VALUE FROM DICTION_APP DA WHERE DA.LINK_UP = P.LINK_INC AND 
	        da.OBJECT =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'COLUMN_CODE_T_INC')))
	from 
		dbo.CALCULATE_JURNAL JC
		INNER JOIN dbo.NDFL_GroupTax() T ON JC.LINK_PAYS=T.LINK_PAYS 
		INNER JOIN dbo.PAYS P ON JC.LINK_PAYS = P.LINK
		LEFT JOIN (Select d.link, o.code from sdoc d inner join dbo.s_objects o on d.object = o.link) d on jc.LINK_DOC = d.link
	where
		 (
				(@isPrevPreiod = 0 or coalesce(d.code,'') <> 'DOCUMENTS_ADD_TABEL') and 12 >= month(JC.PERIOD_BEGIN) and @varKSnYear = year(JC.PERIOD_BEGIN)
				or 
				@isPrevPreiod = 1 and coalesce(d.code,'') = 'DOCUMENTS_ADD_TABEL'
				and (12 >= month(JC.DATE_BEGIN) or 12 >= month(JC.PERIOD_BEGIN) )
				and (@varKSnYear = year(JC.DATE_BEGIN) or @varKSnYear = year(JC.PERIOD_BEGIN) )

			)
		AND JC.LINK_DEP = @DEP_LINK 
		AND JC.PERS_LINK = @varKSnLinkPers		


	-------
	CREATE TABLE #PAYS0 (MODE INT, CODE VARCHAR(10), 
		SM01 NUMERIC(20,2), SM02 NUMERIC(20,2), SM03 NUMERIC(20,2), SM04 NUMERIC(20,2), 
		SM05 NUMERIC(20,2), SM06 NUMERIC(20,2), SM07 NUMERIC(20,2), SM08 NUMERIC(20,2), 
		SM09 NUMERIC(20,2), SM10 NUMERIC(20,2), SM11 NUMERIC(20,2), SM12 NUMERIC(20,2), SM13 NUMERIC(20,2)
	)

	INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12)
	SELECT 1, CODE_INC,
		SUM( CASE WHEN MONTH(CASE WHEN TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN TYP_PER = 2 THEN SJC.DATE1 END) = 1 THEN SUMMA ELSE 0.00 END),
		SUM( CASE WHEN MONTH(CASE WHEN TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN TYP_PER = 2 THEN SJC.DATE1 END) = 2 THEN SUMMA ELSE 0.00 END),
		SUM( CASE WHEN MONTH(CASE WHEN TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN TYP_PER = 2 THEN SJC.DATE1 END) = 3 THEN SUMMA ELSE 0.00 END),
		SUM( CASE WHEN MONTH(CASE WHEN TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN TYP_PER = 2 THEN SJC.DATE1 END) = 4 THEN SUMMA ELSE 0.00 END),
		SUM( CASE WHEN MONTH(CASE WHEN TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN TYP_PER = 2 THEN SJC.DATE1 END) = 5 THEN SUMMA ELSE 0.00 END),
		SUM( CASE WHEN MONTH(CASE WHEN TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN TYP_PER = 2 THEN SJC.DATE1 END) = 6 THEN SUMMA ELSE 0.00 END),
		SUM( CASE WHEN MONTH(CASE WHEN TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN TYP_PER = 2 THEN SJC.DATE1 END) = 7 THEN SUMMA ELSE 0.00 END),
		SUM( CASE WHEN MONTH(CASE WHEN TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN TYP_PER = 2 THEN SJC.DATE1 END) = 8 THEN SUMMA ELSE 0.00 END),
		SUM( CASE WHEN MONTH(CASE WHEN TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN TYP_PER = 2 THEN SJC.DATE1 END) = 9 THEN SUMMA ELSE 0.00 END),
		SUM( CASE WHEN MONTH(CASE WHEN TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN TYP_PER = 2 THEN SJC.DATE1 END) = 10 THEN SUMMA ELSE 0.00 END),
		SUM( CASE WHEN MONTH(CASE WHEN TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN TYP_PER = 2 THEN SJC.DATE1 END) = 11 THEN SUMMA ELSE 0.00 END),
		SUM( CASE WHEN MONTH(CASE WHEN TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN TYP_PER = 2 THEN SJC.DATE1 END) = 12 THEN SUMMA ELSE 0.00 END)
	FROM 
		@SJC SJC 
	WHERE
		SJC.LINK_FACE = @varKSnLinkPers
		AND YEAR(CASE WHEN TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN TYP_PER = 2 THEN SJC.DATE1 END) = @varKSnYear
		AND CODE_INC IS NOT NULL
		AND CODE_INC <> '0000'
		AND SJC.link_dep  = @DEP_LINK 
	GROUP BY SJC.CODE_INC
	ORDER BY SJC.CODE_INC

	---
	CREATE TABLE #ndfl_ded_month_all_table_MONTH (MON INT, LINK_DED INT, SUMMA NUMERIC(11,2))

	--Вычеты по сотрудникам
	INSERT INTO #ndfl_ded_month_all_table_MONTH (MON, LINK_DED, SUMMA)
	SELECT MONTH(DATE_DED), REF_DED, SUM(SUMMA)
	FROM 
		dbo.EMPL E
		INNER JOIN SAL_DED_MONTH S ON E.LINK = S.LINK_EMPL
	WHERE
		E.PERS_LINK = @varKSnLinkPers
		AND YEAR(DATE_DED) = @varKSnYear
		--AND TYPE = 1
		AND DEP_LINK = @DEP_LINK
		----
		AND EXISTS ( SELECT * FROM #deds d WHERE d.ref_ded = s.REF_DED)
		----
	GROUP BY DATE_DED, REF_DED

	--Вычеты по договорникам
	INSERT INTO #ndfl_ded_month_all_table_MONTH (MON, LINK_DED, SUMMA)
	SELECT MONTH(DATE_DED), REF_DED, SUM(S.SUMMA)
	FROM 
		dbo.REESTR_DGH E
		INNER JOIN dbo.SAL_DED_MONTH S ON E.LINK = S.LINK_DGH
	WHERE
		E.PERS_LINK = @varKSnLinkPers
		AND YEAR(DATE_DED) = @varKSnYear
		--AND TYPE = 1
		AND DEP_LINK = @DEP_LINK
		----
		AND EXISTS ( SELECT * FROM #deds d WHERE d.ref_ded = s.REF_DED)
		----
	GROUP BY DATE_DED, REF_DED	


	CREATE TABLE #MONTHES ([MONTH] INT, SUMMA NUMERIC(18,2), CODE_DED VARCHAR(10) )
	DECLARE @varKSI INT
	SET @varKSI = 1
	WHILE @varKSI < 13 BEGIN
		INSERT INTO #MONTHES
		SELECT @varKSI, V.SUMMA, DTD.CODE
		FROM 
			#ndfl_ded_month_all_table_MONTH v
			INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION DTD ON DTD.LINK = V.LINK_DED
			INNER JOIN dbo.SALARY_GROUP_DEDUCTION T ON DTD.NUMBER = T.CODE
		WHERE
			T.CODE NOT IN (1,4)
			AND
			V.MON = @varKSI
	
		SET @varKSI = @varKSI + 1
	END

	CREATE TABLE #MONTHES2 (CODE_DED VARCHAR(10), 
		SM01 NUMERIC(11,2), SM02 NUMERIC(11,2), SM03 NUMERIC(11,2), SM04 NUMERIC(11,2), 
		SM05 NUMERIC(11,2), SM06 NUMERIC(11,2), SM07 NUMERIC(11,2), SM08 NUMERIC(11,2), 
		SM09 NUMERIC(11,2), SM10 NUMERIC(11,2), SM11 NUMERIC(11,2), SM12 NUMERIC(11,2))
		
	INSERT INTO #MONTHES2 (CODE_DED)
	SELECT DISTINCT CODE_DED FROM #MONTHES
	UPDATE #MONTHES2 SET SM01 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH = 1) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM02 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH = 2) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM03 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH = 3) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM04 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH = 4) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM05 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH = 5) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM06 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH = 6) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM07 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH = 7) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM08 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH = 8) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM09 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH = 9) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM10 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH = 10) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM11 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH = 11) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM12 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH = 12) FROM #MONTHES2 M1

	INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12)
	SELECT 2, * FROM #MONTHES2
	ORDER BY CODE_DED

	DELETE FROM  #MONTHES2
	DELETE FROM  #MONTHES


	INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12)
	SELECT 
		3, '',
		ISNULL(SUM(CASE WHEN MODE = 1 THEN SM01 ELSE -SM01 END), 0),
		ISNULL(SUM(CASE WHEN MODE = 1 THEN SM02 ELSE -SM02 END), 0),
		ISNULL(SUM(CASE WHEN MODE = 1 THEN SM03 ELSE -SM03 END), 0),
		ISNULL(SUM(CASE WHEN MODE = 1 THEN SM04 ELSE -SM04 END), 0),
		ISNULL(SUM(CASE WHEN MODE = 1 THEN SM05 ELSE -SM05 END), 0),
		ISNULL(SUM(CASE WHEN MODE = 1 THEN SM06 ELSE -SM06 END), 0),
		ISNULL(SUM(CASE WHEN MODE = 1 THEN SM07 ELSE -SM07 END), 0),
		ISNULL(SUM(CASE WHEN MODE = 1 THEN SM08 ELSE -SM08 END), 0),
		ISNULL(SUM(CASE WHEN MODE = 1 THEN SM09 ELSE -SM09 END), 0),
		ISNULL(SUM(CASE WHEN MODE = 1 THEN SM10 ELSE -SM10 END), 0),
		ISNULL(SUM(CASE WHEN MODE = 1 THEN SM11 ELSE -SM11 END), 0),
		ISNULL(SUM(CASE WHEN MODE = 1 THEN SM12 ELSE -SM12 END), 0)
	FROM #PAYS0 WHERE MODE IN (1, 2)

	IF (SELECT COUNT(*) FROM #PAYS0 WHERE MODE = 3) = 0
		INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12)
		VALUES (3, '', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
	

	IF @varKSStatus = 1
		INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12,SM13)
		SELECT 4, '',
			SM01,
			CASE WHEN @Today >= 2 THEN SM01 + SM02 ELSE 0 END,
			CASE WHEN @Today >= 3 THEN SM01 + SM02 + SM03 ELSE 0 END,
			CASE WHEN @Today >= 4 THEN SM01 + SM02 + SM03 + SM04 ELSE 0 END,
			CASE WHEN @Today >= 5 THEN SM01 + SM02 + SM03 + SM04 + SM05 ELSE 0 END,
			CASE WHEN @Today >= 6 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 ELSE 0 END,
			CASE WHEN @Today >= 7 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 ELSE 0 END,
			CASE WHEN @Today >= 8 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 ELSE 0 END,
			CASE WHEN @Today >= 9 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 ELSE 0 END,
			CASE WHEN @Today >= 10 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 + SM10 ELSE 0 END,
			CASE WHEN @Today >= 11 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 + SM10 + SM11 ELSE 0 END,
			CASE WHEN @Today >= 12 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 + SM10 + SM11 + SM12 ELSE 0 END,
			SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 + SM10 + SM11 + SM12
		FROM #PAYS0 WHERE MODE = 3 
	ELSE
		INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12)
		VALUES (4, '', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)




	DECLARE @varKSEMPL INT
	IF @varKSStatus = '1' BEGIN

		SET @varKSI = 1
		WHILE @varKSI < 13 BEGIN
			INSERT INTO #MONTHES
			SELECT @varKSI, V.SUMMA, DTD.CODE
			FROM 
				dbo.ndfl_ded_month_all_table_MONTH(@varKSnLinkPers, @varKSI, @varKSnYear) v
				INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION DTD ON DTD.LINK = V.LINK_DED
				INNER JOIN dbo.SALARY_GROUP_DEDUCTION T ON DTD.NUMBER = T.CODE
				----
				AND EXISTS ( SELECT * FROM #deds d WHERE d.ref_ded = v.LINK_DED)
				----
			WHERE
				T.CODE IN (1,4)

		SET @varKSI = @varKSI + 1
	END

	INSERT INTO #MONTHES2 (CODE_DED)
	SELECT DISTINCT CODE_DED FROM #MONTHES
	UPDATE #MONTHES2 SET SM01 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH = 1) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM02 = (SELECT ISNULL(SUM(CASE WHEN M0.MONTH = 2 THEN SUMMA ELSE - SUMMA END),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH IN(1, 2) ) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM03 = (SELECT ISNULL(SUM(CASE WHEN M0.MONTH = 3 THEN SUMMA ELSE - SUMMA END),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH IN(2, 3) ) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM04 = (SELECT ISNULL(SUM(CASE WHEN M0.MONTH = 4 THEN SUMMA ELSE - SUMMA END),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH IN(3, 4) ) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM05 = (SELECT ISNULL(SUM(CASE WHEN M0.MONTH = 5 THEN SUMMA ELSE - SUMMA END),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH IN(4, 5) ) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM06 = (SELECT ISNULL(SUM(CASE WHEN M0.MONTH = 6 THEN SUMMA ELSE - SUMMA END),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH IN(5, 6) ) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM07 = (SELECT ISNULL(SUM(CASE WHEN M0.MONTH = 7 THEN SUMMA ELSE - SUMMA END),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH IN(6, 7) ) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM08 = (SELECT ISNULL(SUM(CASE WHEN M0.MONTH = 8 THEN SUMMA ELSE - SUMMA END),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH IN(7, 8) ) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM09 = (SELECT ISNULL(SUM(CASE WHEN M0.MONTH = 9 THEN SUMMA ELSE - SUMMA END),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH IN(8, 9) ) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM10 = (SELECT ISNULL(SUM(CASE WHEN M0.MONTH = 10 THEN SUMMA ELSE - SUMMA END),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH IN(9, 10) ) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM11 = (SELECT ISNULL(SUM(CASE WHEN M0.MONTH = 11 THEN SUMMA ELSE - SUMMA END),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH IN(10, 11) ) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM12 = (SELECT ISNULL(SUM(CASE WHEN M0.MONTH = 12 THEN SUMMA ELSE - SUMMA END),0) FROM #MONTHES M0 WHERE M0.CODE_DED = M1.CODE_DED AND M0.MONTH IN(11, 12) ) FROM #MONTHES2 M1

---->>>>>>------
	
	DECLARE @SQLS1 VARCHAR(4000), @FIELDS VARCHAR(1000), @FIELDSUM VARCHAR(1000), @FIELDSTR VARCHAR(1000), @CODE varchar(4) , @HAS varchar(1), @FIELDCHILD varchar (1000), @FOR_CHILD varchar(1)
	
	set @FIELDSTR = ''
	set @FOR_CHILD = ''
	set @FIELDCHILD = ''

	SET @I=1

	WHILE @I <= @CNT BEGIN
		SET @CODE = RTRIM(LTRIM(STR((select CODE_DED from #DEDS where RECNO = @I and [TYPE] = 1) )))
		SET @FOR_CHILD = RTRIM(LTRIM(STR((select FOR_CHILD from #DEDS where RECNO = @I and [TYPE] = 1 )  ))) -- 1 - на налогоплательщика, 2 - на ребенка
		if @CODE is not null
		begin
			SET @FIELDSUM= 'SUM' + RTRIM(LTRIM(STR(@CODE)))
			SET @SQLS= ' UPDATE #RES0 SET '+@FIELDSUM+ ' = (SELECT distinct SUMMA FROM #DEDS WHERE CODE_DED = '+ @CODE+ ') ' 
			EXEC (@SQLS)
			
			SET @FIELD= 'HAS' + RTRIM(LTRIM(STR(@CODE)))
			SET @SQLS= ' UPDATE #RES0 SET '+@FIELD+ ' = (SELECT COUNT(*) FROM #MONTHES2 WHERE CODE_DED = '+ @CODE+ ') ' 

			EXEC (@SQLS)
			
			--  собираем строку с суммами по вычетам на налогоплательщика STRMD 
			IF @FOR_CHILD = 1
			begin
				if LEN(@FIELDSTR) = 0
				begin
		
					DECLARE @SQLString nvarchar(500)
					DECLARE @ParmDefinition nvarchar(500)
					DECLARE @max_title nvarchar(25)
			
					SET @SQLString = N'SELECT @max_titleOUT = '+@FIELD+'
									FROM #RES0
									'
					SET @ParmDefinition = N'@FIELDSTR1 varchar(50),
						@max_titleOUT nvarchar(25) OUTPUT'
			
					EXECUTE sp_executesql @SQLString,@ParmDefinition,@FIELDSTR1 = @FIELDSTR,@max_titleOUT = @max_title OUTPUT
					
					SET @FIELDSTR =	 ltrim(rtrim(str((SELECT distinct SUMMA FROM #DEDS WHERE CODE_DED =  @CODE )))) + ' руб. ' + CASE when @max_title = '1' then 'X' else ' ' end 
				end
				-- продолжение строки на налогоплательщика
				else begin
					DECLARE @SQLString1 nvarchar(500)
					DECLARE @ParmDefinition1 nvarchar(500)
					DECLARE @max_title1 nvarchar(25)
			
					SET @SQLString1 = N'SELECT @max_titleOUT1 = '+@FIELD+'
									FROM #RES0
									'
					SET @ParmDefinition1 = N'@FIELDSTR1 varchar(50),
						@max_titleOUT1 nvarchar(25) OUTPUT'
			
					EXECUTE sp_executesql @SQLString1,@ParmDefinition1,@FIELDSTR1 = @FIELDSTR,@max_titleOUT1 = @max_title1 OUTPUT
					
						SET @FIELDSTR = @FIELDSTR+ ', '+  ltrim(rtrim(str((SELECT distinct SUMMA FROM #DEDS WHERE CODE_DED =  @CODE )))) +  ' руб. ' + CASE when @max_title1 = '1' then 'X' else ' ' end
					end
			end
			--- Заполнение строки STR_RCH
			IF @FOR_CHILD = 2
			begin
				if LEN(@FIELDCHILD) = 0
				begin
		
					SET @SQLString = N'SELECT @max_titleOUT = '+@FIELD+'
									FROM #RES0
									'
					SET @ParmDefinition = N'@FIELDSTR1 varchar(50),
						@max_titleOUT nvarchar(25) OUTPUT'
			
					EXECUTE sp_executesql @SQLString,@ParmDefinition,@FIELDSTR1 = @FIELDCHILD,@max_titleOUT = @max_title OUTPUT
					
					SET @FIELDCHILD =	 ltrim(rtrim(str((SELECT distinct SUMMA FROM #DEDS WHERE CODE_DED =  @CODE )))) + ' руб.' + CASE when @max_title = ' 1' then ' X' else '' end 
				end
				-- продолжение строки на налогоплательщика
				else begin
				
					SET @SQLString1 = N'SELECT @max_titleOUT1 = '+@FIELD+'
									FROM #RES0
									'
					SET @ParmDefinition1 = N'@FIELDSTR1 varchar(50),
						@max_titleOUT1 nvarchar(25) OUTPUT'
			
					EXECUTE sp_executesql @SQLString1,@ParmDefinition1,@FIELDSTR1 = @FIELDCHILD,@max_titleOUT1 = @max_title1 OUTPUT
					
						SET @FIELDCHILD = @FIELDCHILD+ ', '+  ltrim(rtrim(str((SELECT distinct SUMMA FROM #DEDS WHERE CODE_DED =  @CODE )))) +  ' руб.' + CASE when @max_title1 = ' 1' then ' X' else '' end
					end
			end	


			-----
			if @FIELDS is null and @FIELD is not null 
			begin
				set @FIELDS = @FIELD 
			end 
		
			if @FIELDS is not null and @FIELD is not null 
			begin
				set @FIELDS= @FIELDS + ' + ' + @FIELD 
			end 
			
		end		
		SET @I=@I+1 
	END

	SET @SQLS1= ' UPDATE #RES0 SET HAS_VICHET = CASE WHEN '+@FIELDS+' > 0 THEN 1 ELSE 2 END '
	EXEC (@SQLS1)
	
	SET @SQLS1= ' UPDATE #RES0 SET STR_MD = '''+ltrim(rtrim(@FIELDSTR))+''''

	EXEC (@SQLS1)
	
	SET @SQLS1= ' UPDATE #RES0 SET STR_RCH = '''+ltrim(rtrim(@FIELDCHILD))+''''

	EXEC (@SQLS1) 	

---->>>>>>------	
/*	
	UPDATE #RES0 SET HAS103 = (SELECT COUNT(*) FROM #MONTHES2 WHERE CODE_DED = '103') 
	UPDATE #RES0 SET HAS104 = (SELECT COUNT(*) FROM #MONTHES2 WHERE CODE_DED = '104') 
	UPDATE #RES0 SET HAS105 = (SELECT COUNT(*) FROM #MONTHES2 WHERE CODE_DED = '105') 
	UPDATE #RES0 SET HAS108 = (SELECT COUNT(*) FROM #MONTHES2 WHERE CODE_DED = '108') 
	UPDATE #RES0 SET HAS109 = (SELECT COUNT(*) FROM #MONTHES2 WHERE CODE_DED = '109') 
	UPDATE #RES0 SET HAS110 = (SELECT COUNT(*) FROM #MONTHES2 WHERE CODE_DED = '110') 
	UPDATE #RES0 SET HAS111 = (SELECT COUNT(*) FROM #MONTHES2 WHERE CODE_DED = '111') 
	UPDATE #RES0 SET HAS112 = (SELECT COUNT(*) FROM #MONTHES2 WHERE CODE_DED = '112') 
	UPDATE #RES0 SET HAS113 = (SELECT COUNT(*) FROM #MONTHES2 WHERE CODE_DED = '113') 
	UPDATE #RES0 SET HAS_VICHET = CASE WHEN HAS103 +HAS104 +HAS105 +HAS108 +HAS109 +HAS110 +HAS111 +HAS112 +HAS113 > 0 THEN 1 ELSE 2 END
*/

-----------------------
	SET @I=1
	set @FIELDS = null
	WHILE @I <= @CNT BEGIN
		SET @CODE = RTRIM(LTRIM(STR((select CODE_DED from #DEDS where RECNO = @I and [TYPE] in (1,4)) )))
		if @CODE is not null
		
		begin
			SET @FIELD= 'SELECT '+ RTRIM(LTRIM(STR(@CODE))) + ' as CODE' 

			if @FIELDS is null and @FIELD is not null 
			begin
				set @FIELDS = @FIELD 
			end 
			if @FIELDS is not null and @FIELD is not null 
			begin
				set @FIELDS= @FIELDS + ' UNION ' + @FIELD 
			end 
			
		end		
		SET @I=@I+1 
	END
	SET @SQLS= ' INSERT INTO #MONTHES2
		SELECT V.CODE, 
			0, 0, 0, 0, 0, 0, 
			0, 0, 0, 0, 0, 0
		FROM ( '+@FIELDS+' ) V
		WHERE V.CODE NOT IN (SELECT m.CODE_DED FROM #MONTHES2 m WHERE EXISTS (  SELECT * FROM #DEDS  d WHERE d.CODE_DED = m.CODE_DED and d.[TYPE] in (1,4)))'
	EXEC (@SQLS) 
------------------------
/*		INSERT INTO #MONTHES2
		SELECT V.CODE, 
			0, 0, 0, 0, 0, 0, 
			0, 0, 0, 0, 0, 0
		FROM (	      SELECT '103' AS CODE 
			UNION SELECT '104' AS CODE 
			UNION SELECT '105' AS CODE 
			UNION SELECT '108' AS CODE 
			UNION SELECT '109' AS CODE 
			UNION SELECT '110' AS CODE 
			UNION SELECT '111' AS CODE 
			UNION SELECT '112' AS CODE 
			UNION SELECT '113' AS CODE
			UNION SELECT '312' AS CODE
			UNION SELECT '313' AS CODE) V
		WHERE V.CODE NOT IN (SELECT CODE_DED FROM #MONTHES2)
*/		

		INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12)
		SELECT case when CODE_DED not in (select d.CODE_DED from #DEDS d where d.[TYPE] = 4 ) then 5 else 7 end, * FROM #MONTHES2 
		ORDER BY CODE_DED

		DELETE FROM  #MONTHES2
		DELETE FROM  #MONTHES

		INSERT INTO #MONTHES2
		SELECT 
			convert(varchar(3),MODE), 
			SUM(SM01), SUM(SM02), SUM(SM03), SUM(SM04), SUM(SM05), SUM(SM06), 
			SUM(SM07), SUM(SM08), SUM(SM09), SUM(SM10), SUM(SM11), SUM(SM12)
		FROM #PAYS0 WHERE MODE in (5,7) group by MODE

		INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12,SM13)
		SELECT convert(int,CODE_DED)+1, '',
			SM01,
			CASE WHEN @Today >= 2 THEN SM01 + SM02 ELSE 0 END,
			CASE WHEN @Today >= 3 THEN SM01 + SM02 + SM03 ELSE 0 END,
			CASE WHEN @Today >= 4 THEN SM01 + SM02 + SM03 + SM04 ELSE 0 END,
			CASE WHEN @Today >= 5 THEN SM01 + SM02 + SM03 + SM04 + SM05 ELSE 0 END,
			CASE WHEN @Today >= 6 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 ELSE 0 END,
			CASE WHEN @Today >= 7 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 ELSE 0 END,
			CASE WHEN @Today >= 8 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 ELSE 0 END,
			CASE WHEN @Today >= 9 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 ELSE 0 END,
			CASE WHEN @Today >= 10 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 + SM10 ELSE 0 END,
			CASE WHEN @Today >= 11 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 + SM10 + SM11 ELSE 0 END,
			CASE WHEN @Today >= 12 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 + SM10 + SM11 + SM12 ELSE 0 END,
			SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 + SM10 + SM11 + SM12
		FROM #MONTHES2

		DELETE FROM  #MONTHES2
	END
	ELSE BEGIN
	/*	INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12)
		SELECT 5, V.CODE, 
			0, 0, 0, 0, 0, 0, 
			0, 0, 0, 0, 0, 0
		FROM (	      SELECT '103' AS CODE 
			UNION SELECT '104' AS CODE 
			UNION SELECT '105' AS CODE 
			UNION SELECT '108' AS CODE 
			UNION SELECT '109' AS CODE 
			UNION SELECT '110' AS CODE 
			UNION SELECT '111' AS CODE 
			UNION SELECT '112' AS CODE 
			UNION SELECT '113' AS CODE) V
		UNION
		SELECT 6, '', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
		
		INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12)
		SELECT 7, V.CODE, 
			0, 0, 0, 0, 0, 0, 
			0, 0, 0, 0, 0, 0
		FROM (	      SELECT '312' AS CODE 
			UNION SELECT '313' AS CODE) V
		UNION
		SELECT 8, '', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
	*/
	
	------>>>>>>>>-----------------
		SET @I=1
		set @FIELDS = null
		WHILE @I <= @CNT BEGIN
			SET @CODE = RTRIM(LTRIM(STR((select CODE_DED from #DEDS where RECNO = @I and [TYPE] = 1) )))
			if @CODE is not null
			
			begin
				SET @FIELD= 'SELECT '+ RTRIM(LTRIM(STR(@CODE))) + ' as CODE' 

				if @FIELDS is null and @FIELD is not null 
				begin
					set @FIELDS = @FIELD 
				end 
				if @FIELDS is not null and @FIELD is not null 
				begin
					set @FIELDS= @FIELDS + ' UNION ' + @FIELD 
				end 
				
			end		
			SET @I=@I+1 
		END
		SET @SQLS= ' INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12)
		SELECT 5, V.CODE, 
			0, 0, 0, 0, 0, 0, 
			0, 0, 0, 0, 0, 0
		FROM ( '+@FIELDS+' ) V
		UNION
		SELECT 6, '''', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0'
		EXEC (@SQLS) 
	------>>>>>>>>-----------------
		SET @I=1
		set @FIELDS = null
		WHILE @I <= @CNT BEGIN
			SET @CODE = RTRIM(LTRIM(STR((select CODE_DED from #DEDS where RECNO = @I and [TYPE] = 4) )))
			if @CODE is not null
			
			begin
				SET @FIELD= 'SELECT '+ RTRIM(LTRIM(STR(@CODE))) + ' as CODE' 

				if @FIELDS is null and @FIELD is not null 
				begin
					set @FIELDS = @FIELD 
				end 
				if @FIELDS is not null and @FIELD is not null 
				begin
					set @FIELDS= @FIELDS + ' UNION ' + @FIELD 
				end 
				
			end		
			SET @I=@I+1 
		END
		SET @SQLS= ' INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12)
		SELECT 7, V.CODE, 
			0, 0, 0, 0, 0, 0, 
			0, 0, 0, 0, 0, 0
		FROM ( '+@FIELDS+' ) V
		UNION
		SELECT 8, '''', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0'
		EXEC (@SQLS) 		
	------->>>>>>>>>-----------------


	END

	IF @varKSStatus = '1' BEGIN
		INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12,SM13)
		SELECT 9, '',
			SUM(CASE WHEN MODE = 4 THEN SM01 ELSE -SM01 END),
			SUM(CASE WHEN MODE = 4 THEN SM02 ELSE -SM02 END),
			SUM(CASE WHEN MODE = 4 THEN SM03 ELSE -SM03 END),
			SUM(CASE WHEN MODE = 4 THEN SM04 ELSE -SM04 END),
			SUM(CASE WHEN MODE = 4 THEN SM05 ELSE -SM05 END),
			SUM(CASE WHEN MODE = 4 THEN SM06 ELSE -SM06 END),
			SUM(CASE WHEN MODE = 4 THEN SM07 ELSE -SM07 END),
			SUM(CASE WHEN MODE = 4 THEN SM08 ELSE -SM08 END),
			SUM(CASE WHEN MODE = 4 THEN SM09 ELSE -SM09 END),
			SUM(CASE WHEN MODE = 4 THEN SM10 ELSE -SM10 END),
			SUM(CASE WHEN MODE = 4 THEN SM11 ELSE -SM11 END),
			SUM(CASE WHEN MODE = 4 THEN SM12 ELSE -SM12 END),
			CASE @Today
				WHEN 1 THEN SUM(CASE WHEN MODE = 4 THEN SM01 ELSE -SM01 END)
				WHEN 2 THEN SUM(CASE WHEN MODE = 4 THEN SM02 ELSE -SM02 END)
				WHEN 3 THEN SUM(CASE WHEN MODE = 4 THEN SM03 ELSE -SM03 END)
				WHEN 4 THEN SUM(CASE WHEN MODE = 4 THEN SM04 ELSE -SM04 END)
				WHEN 5 THEN SUM(CASE WHEN MODE = 4 THEN SM05 ELSE -SM05 END)
				WHEN 6 THEN SUM(CASE WHEN MODE = 4 THEN SM06 ELSE -SM06 END)
				WHEN 7 THEN SUM(CASE WHEN MODE = 4 THEN SM07 ELSE -SM07 END)
				WHEN 8 THEN SUM(CASE WHEN MODE = 4 THEN SM08 ELSE -SM08 END)
				WHEN 9 THEN SUM(CASE WHEN MODE = 4 THEN SM09 ELSE -SM09 END)
				WHEN 10 THEN SUM(CASE WHEN MODE = 4 THEN SM10 ELSE -SM10 END)
				WHEN 11 THEN SUM(CASE WHEN MODE = 4 THEN SM11 ELSE -SM11 END)
				WHEN 12 THEN SUM(CASE WHEN MODE = 4 THEN SM12 ELSE -SM12 END)
			END

		FROM #PAYS0
		WHERE MODE IN (4, 6, 8)	
	END
	ELSE BEGIN
		INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12)
		SELECT 9, '', SM01, SM02, SM03, SM04, SM05, SM06, SM07, SM08, SM09, SM10, SM11, SM12
		FROM #PAYS0 WHERE MODE = 3	
	END



	DECLARE @varKSCOEFF NUMERIC(20,2)
	SELECT @varKSCOEFF = CASE WHEN @varKSStatus = 1 THEN 0.13 ELSE 0.30 END
	INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12,SM13)
	SELECT 10, '',
		CAST ( ROUND(SM01 * @varKSCOEFF,0) AS INTEGER),
		CAST ( ROUND(SM02 * @varKSCOEFF,0) AS INTEGER),
		CAST ( ROUND(SM03 * @varKSCOEFF,0) AS INTEGER),
		CAST ( ROUND(SM04 * @varKSCOEFF,0) AS INTEGER),
		CAST ( ROUND(SM05 * @varKSCOEFF,0) AS INTEGER),
		CAST ( ROUND(SM06 * @varKSCOEFF,0) AS INTEGER),
		CAST ( ROUND(SM07 * @varKSCOEFF,0) AS INTEGER),
		CAST ( ROUND(SM08 * @varKSCOEFF,0) AS INTEGER),
		CAST ( ROUND(SM09 * @varKSCOEFF,0) AS INTEGER),
		CAST ( ROUND(SM10 * @varKSCOEFF,0) AS INTEGER),
		CAST ( ROUND(SM11 * @varKSCOEFF,0) AS INTEGER),
		CAST ( ROUND(SM12 * @varKSCOEFF,0) AS INTEGER),
		CAST ( ROUND(SM13 * @varKSCOEFF,0) AS INTEGER)
	FROM #PAYS0 WHERE MODE = 9

	INSERT INTO #MONTHES
	SELECT
		MONTH(DATE1), CAST( (SUM(CAST(round(SUMMA, 0) as int) )) AS NUMERIC(8,0) ), ''
	FROM 
		dbo.S_J_C_SHORT SJC 
		INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
		INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
	WHERE 
 		YEAR(DATE1) = @varKSnYear 
		AND 
		SJC.LINK_DEP = @DEP_LINK 
		AND 
		E.PERS_LINK = @varKSnLinkPers
	GROUP BY 
		MONTH(DATE1)
	UNION ALL
	SELECT MONTH(DATE1), CAST( (SUM(CAST(round(SUMMA, 0) as int) )) AS NUMERIC(8,0) ), ''
	FROM 
		dbo.S_J_C_SHORT SJC 
		INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
	WHERE 
 		YEAR(DATE1) = @varKSnYear 
		AND 
		SJC.LINK_DEP = @DEP_LINK 
		AND
		SJC.PERS_LINK = @varKSnLinkPers
	GROUP BY 
		MONTH(DATE1)		
	
	INSERT INTO #MONTHES2 (CODE_DED) VALUES ('')

	UPDATE #MONTHES2 SET SM01 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE  M0.MONTH = 1) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM02 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE  M0.MONTH = 2) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM03 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE  M0.MONTH = 3) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM04 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE  M0.MONTH = 4) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM05 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE  M0.MONTH = 5) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM06 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE  M0.MONTH = 6) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM07 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE  M0.MONTH = 7) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM08 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE  M0.MONTH = 8) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM09 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE  M0.MONTH = 9) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM10 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE  M0.MONTH = 10) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM11 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE  M0.MONTH = 11) FROM #MONTHES2 M1
	UPDATE #MONTHES2 SET SM12 = (SELECT ISNULL(SUM(SUMMA),0) FROM #MONTHES M0 WHERE  M0.MONTH = 12) FROM #MONTHES2 M1

	IF @varKSStatus = 1 BEGIN
		INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12,SM13)
		SELECT 11, '',
			SM01,
			CASE WHEN @Today >= 2 THEN SM01 + SM02 ELSE 0 END,
			CASE WHEN @Today >= 3 THEN SM01 + SM02 + SM03 ELSE 0 END,
			CASE WHEN @Today >= 4 THEN SM01 + SM02 + SM03 + SM04 ELSE 0 END,
			CASE WHEN @Today >= 5 THEN SM01 + SM02 + SM03 + SM04 + SM05 ELSE 0 END,
			CASE WHEN @Today >= 6 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 ELSE 0 END,
			CASE WHEN @Today >= 7 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 ELSE 0 END,
			CASE WHEN @Today >= 8 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 ELSE 0 END,
			CASE WHEN @Today >= 9 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 ELSE 0 END,
			CASE WHEN @Today >= 10 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 + SM10 ELSE 0 END,
			CASE WHEN @Today >= 11 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 + SM10 + SM11 ELSE 0 END,
			CASE WHEN @Today >= 12 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 + SM10 + SM11 + SM12 ELSE 0 END,
			SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 + SM10 + SM11 + SM12

		FROM #MONTHES2				
		
		UPDATE #RES0 SET SNN = (SELECT TOP 1 SM13 FROM #PAYS0 WHERE MODE = 10)
		UPDATE #RES0 SET SNU = (SELECT TOP 1 SM13 FROM #PAYS0 WHERE MODE = 11)
	END
	ELSE BEGIN
		INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12)
		SELECT 11, '', SM01, SM02, SM03, SM04, SM05, SM06, SM07, SM08, SM09, SM10, SM11, SM12
		FROM #MONTHES2				

		UPDATE #RES0 SET SNN = (SELECT TOP 1 COALESCE(SM01,0) + COALESCE(SM02,0) + COALESCE(SM03,0) + COALESCE(SM04,0) + COALESCE(SM05,0) + COALESCE(SM06,0) + COALESCE(SM07,0) + COALESCE(SM08,0) + COALESCE(SM09,0) + COALESCE(SM10,0) + COALESCE(SM11,0) + COALESCE(SM12,0) FROM #PAYS0 WHERE MODE = 10)
		UPDATE #RES0 SET SNU = (SELECT TOP 1 COALESCE(SM01,0) + COALESCE(SM02,0) + COALESCE(SM03,0) + COALESCE(SM04,0) + COALESCE(SM05,0) + COALESCE(SM06,0) + COALESCE(SM07,0) + COALESCE(SM08,0) + COALESCE(SM09,0) + COALESCE(SM10,0) + COALESCE(SM11,0) + COALESCE(SM12,0) FROM #PAYS0 WHERE MODE = 11)
	END


	UPDATE #RES0 SET DOLG_NPEND = SNN - SNU, DOLG_NAEND = 0
	UPDATE #RES0 SET DOLG_NAEND = -DOLG_NPEND, DOLG_NPEND = 0 WHERE DOLG_NPEND <0



	
	INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12)
	SELECT 12, '',
		SUM(CASE WHEN MODE = 10 THEN SM01 ELSE -SM01 END),
		SUM(CASE WHEN MODE = 10 THEN SM02 ELSE -SM02 END),
		SUM(CASE WHEN MODE = 10 THEN SM03 ELSE -SM03 END),
		SUM(CASE WHEN MODE = 10 THEN SM04 ELSE -SM04 END),
		SUM(CASE WHEN MODE = 10 THEN SM05 ELSE -SM05 END),
		SUM(CASE WHEN MODE = 10 THEN SM06 ELSE -SM06 END),
		SUM(CASE WHEN MODE = 10 THEN SM07 ELSE -SM07 END),
		SUM(CASE WHEN MODE = 10 THEN SM08 ELSE -SM08 END),
		SUM(CASE WHEN MODE = 10 THEN SM09 ELSE -SM09 END),
		SUM(CASE WHEN MODE = 10 THEN SM10 ELSE -SM10 END),
		SUM(CASE WHEN MODE = 10 THEN SM11 ELSE -SM11 END),
		SUM(CASE WHEN MODE = 10 THEN SM12 ELSE -SM12 END)
		FROM #PAYS0
		WHERE MODE IN (10, 11)	


	INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12)
	SELECT 13, '',
		CASE WHEN SM01 > 0 THEN SM01 ELSE 0 END,
		CASE WHEN SM02 > 0 THEN SM02 ELSE 0 END,
		CASE WHEN SM03 > 0 THEN SM03 ELSE 0 END,
		CASE WHEN SM04 > 0 THEN SM04 ELSE 0 END,

		CASE WHEN SM05 > 0 THEN SM05 ELSE 0 END,
		CASE WHEN SM06 > 0 THEN SM06 ELSE 0 END,
		CASE WHEN SM07 > 0 THEN SM07 ELSE 0 END,
		CASE WHEN SM08 > 0 THEN SM08 ELSE 0 END,
		CASE WHEN SM09 > 0 THEN SM09 ELSE 0 END,
		CASE WHEN SM10 > 0 THEN SM10 ELSE 0 END,
		CASE WHEN SM11 > 0 THEN SM11 ELSE 0 END,
		CASE WHEN SM12 > 0 THEN SM12 ELSE 0 END
		FROM #PAYS0
		WHERE MODE = 12


	INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12)
	SELECT 14, '',
		CASE WHEN SM01 < 0 THEN ABS(SM01) ELSE 0 END,
		CASE WHEN SM02 < 0 THEN ABS(SM02) ELSE 0 END,
		CASE WHEN SM03 < 0 THEN ABS(SM03) ELSE 0 END,
		CASE WHEN SM04 < 0 THEN ABS(SM04) ELSE 0 END,
		CASE WHEN SM05 < 0 THEN ABS(SM05) ELSE 0 END,
		CASE WHEN SM06 < 0 THEN ABS(SM06) ELSE 0 END,
		CASE WHEN SM07 < 0 THEN ABS(SM07) ELSE 0 END,
		CASE WHEN SM08 < 0 THEN ABS(SM08) ELSE 0 END,
		CASE WHEN SM09 < 0 THEN ABS(SM09) ELSE 0 END,
		CASE WHEN SM10 < 0 THEN ABS(SM10) ELSE 0 END,
		CASE WHEN SM11 < 0 THEN ABS(SM11) ELSE 0 END,
		CASE WHEN SM12 < 0 THEN ABS(SM12) ELSE 0 END
		FROM #PAYS0
		WHERE MODE = 12

	EXEC dbo.BufferClear

	SELECT * FROM #DEP, #RES0
	SELECT * FROM #PAYS0
END



GO


GRANT EXECUTE ON dbo.[SD_REP_1NDFL2009] TO PUBLIC

GO


GO

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

GO

CREATE  PROCEDURE [dbo].SALARY_SAVE_DICTIONARY_STAVKI_PF
	@varKSparLINK		int	OUTPUT,
	@varKSparLinkPays	int,
	@varKSparDate		datetime,
	@varKSparCOMMENT	varchar(50),
	@varKSparPredel		numeric(15,2),
	@varKSparPercent1	    numeric(6,2),
	@varKSparPercent2	    numeric(6,2),
	@varKSparPercent3	    numeric(6,2),
	@TARIF TINYINT = 1,
	@SPECO INT = NULL
AS
DECLARE @varKSERROR	tinyint,
		@varKStrancount	int

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


	IF @varKSparLinkPays IS NULL OR @varKSparLinkPays = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END
	
	IF @varKSparPredel is null
		SET @varKSparPredel = 0

	IF @varKSparPercent1 is null
		SET @varKSparPercent1 = 0

	IF @varKSparPercent2 is null
		SET @varKSparPercent2 = 0

	IF @varKSparPercent3 is null
		SET @varKSparPercent3 = 0
		
	IF @TARIF IS NULL
		SET @TARIF = 1
	
	EXECUTE @varKSERROR = X_UPDATE_STAVKI_PF @varKSparLINK OUTPUT,@varKSparLinkPays, @varKSparDate,@varKSparCOMMENT,
									@varKSparPredel,@varKSparPercent1,@varKSparPercent2,@varKSparPercent3, @TARIF,@SPECO 
	IF @varKSERROR <> 0
		RETURN @varKSERROR

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0





GO


GRANT EXECUTE ON dbo.[SALARY_SAVE_DICTIONARY_STAVKI_PF] TO PUBLIC

GO



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

GO

CREATE PROCEDURE dbo.SS_SPR_DOP_VZNOS
	@varKScYear1 varchar(4) /*Расчетный год*/,			
	@nLinkEmpl int = 0   /*Сотрудник*/,
	@cNumSPR VARCHAR(8) = ''  /* Номер справки */
	
AS BEGIN

SET NOCOUNT ON


	DECLARE @varKSnYear1 INT
	SET @varKSnYear1 = CAST(@varKScYear1 AS INT)

	DECLARE @BEGIN_YEAR DATETIME
	SET @BEGIN_YEAR = dbo.ConvertDMY2Date(1,1,@varKSnYear1)

	
	DECLARE @END_YEAR DATETIME
	SET @END_YEAR = dbo.ConvertDMY2Date(31,12,@varKSnYear1)

	DECLARE @CURRENT_DATE DATETIME 
	SET @CURRENT_DATE = (SELECT GETDATE())	
	
	DECLARE @DATE_R DATETIME 
	SET @DATE_R  = (case when  YEAR(@CURRENT_DATE) >@varKSnYear1 THEN  @end_year ELSE @CURRENT_DATE end)
	

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK OUTPUT
	


	

	CREATE TABLE #RES0 (
		ID INT IDENTITY,
		NOM_SPR VARCHAR(8),
		LINK_FACE INT,
		SEX INT,
		INNFIZ VARCHAR(20),
		NUMB_SERT VARCHAR(20),
		STATUS VARCHAR(1),
		FIO VARCHAR(254),
		FM VARCHAR(254),
		IM VARCHAR(254),
		OT VARCHAR(254),
		KDVD VARCHAR(4),
		SERNOM VARCHAR(254), 
		BIRTH DATETIME,
		GRAZD VARCHAR(3),
		KSTR VARCHAR(3),
		LINK_ADR INT,
		IND_ADR VARCHAR(10),
		REGION VARCHAR(4),
		RAION VARCHAR(254),
		GOROD VARCHAR(254),
		NASEL VARCHAR(254),
		STREET VARCHAR(254),
		HOUSE VARCHAR(20),
		KORP VARCHAR(10),
		FLAT VARCHAR(10),

		KSTR_ino VARCHAR(3),
		Adr_ino VARCHAR(200),

		O_OKATO VARCHAR(14),
		O_OKTMO VARCHAR(11),
		O_KPP VARCHAR(9),		

		SUM_DOP numeric(18,2),
		err int,
		S_5_6 NUMERIC(18,2), S_5_7 NUMERIC(18,2),		
		dolg_np numeric(8), dolg_na numeric(8),
		kbkcode1 varchar(20),
		kbksum1 numeric(18,2),
		VIFNSPL numeric(18,2),
		ZSummPL numeric(18,2),
		UdSumPL numeric(18,2),
		VzkIFNS numeric(18,2)

	)	


	CREATE TABLE #FACES (LINK int,PERS_LINK int)

	IF @nLinkEmpl > 0
	BEGIN
		INSERT INTO #FACES
		SELECT distinct LINK,PERS_LINK FROM dbo.empl WHERE LINK = @nLinkEmpl and DEP_LINK = @DEP_LINK
	END
	

	EXEC dbo.BufferClear
	EXEC dbo.BufferPushTable '#faces', 'SPRDOPVZNOS', 'pers_link'
	/*Временная таблица*/
	Declare @isPrevPreiod tinyint

	create table #S_J_C_SHORT (LINK_FACE int,PERS_LINK int, link_empl int, link_pays int, link_vkr int, link_ekr int, typ_per tinyint, typ_oper tinyint, summa numeric(18,2), link_inc int, period_begin datetime, date1 datetime, link_dep int)

	Insert into #S_J_C_SHORT (LINK_FACE, PERS_LINK, link_empl, link_pays, link_vkr, link_ekr, typ_per, typ_oper, summa, link_inc, period_begin, date1, link_dep)
	--Удержания
	Select LINK_FACE, PERS_LINK, link_empl, link_pays, link_vkr, link_ekr, typ_per, typ_oper, summa, link_inc, period_begin, date1, link_dep
	from dbo.S_J_C_SHORT SJC 
		LEFT JOIN  DICTIONARY_TAX_SALARY dts ON dts.LINK = sjc.LINK_PAYS
	where 
		SJC.LINK_DEP = @DEP_LINK
/*		and
		(
			SJC.LINK_FACE in (select PERS_LINK from #FACES )
			or
			SJC.PERS_LINK in (select PERS_LINK from #FACES )
		)
*/		and YEAR(SJC.PERIOD_BEGIN) = @varKSnYear1
		and Month(SJC.PERIOD_BEGIN) >= month(@begin_year)
		and Month(SJC.PERIOD_BEGIN) <=  month(@DATE_R)
		and TYP_OPER = 2
		AND dts.osgu_code = '160' OR dts.CODE_DED = '602'


-- exec SS_SPR_DOP_VZNOS '2013', 11 
-----------------------------------------------------------
--Для обособленных подразделений
DECLARE @DATE DATETIME
SET @DATE = @begin_year
SET @DATE = DBO.DateEndOfMonth(@DATE)

CREATE TABLE #E_SUBDIV (EMPL_LINK INT, SUBDIV_LINK INT)
INSERT INTO #E_SUBDIV (EMPL_LINK, SUBDIV_LINK)
SELECT EMPL_LINK, SUBDIV_LINK
FROM DBO.SA_EMPLS_INFO(@DATE, DEFAULT)
WHERE [STATUS] = 1 OR [STATUS] = 3

CREATE TABLE #S_OBOSOB (SUBDIV_LINK INT, O_OKATO VARCHAR(14), O_OKTMO VARCHAR(11), O_KPP VARCHAR(9))
INSERT INTO #S_OBOSOB (SUBDIV_LINK, O_OKATO,  O_OKTMO, O_KPP)
SELECT SUBDIV_LINK, O_OKATO,  O_OKTMO, O_KPP 
FROM [dbo].SUBDIVISION(@DATE) 
WHERE OBOSOB = 1


CREATE TABLE #P_OBOSOB (PERS_LINK INT, O_OKATO VARCHAR(14), O_OKTMO VARCHAR(11), O_KPP VARCHAR(9))
INSERT INTO #P_OBOSOB(PERS_LINK, O_OKATO, O_OKTMO, O_KPP)
SELECT E.PERS_LINK, SO.O_OKATO , SO.O_OKTMO, SO.O_KPP 
FROM 
	#S_OBOSOB SO INNER JOIN #E_SUBDIV ES ON SO.SUBDIV_LINK = ES.SUBDIV_LINK
	INNER JOIN DBO.EMPL E ON E.LINK = ES.EMPL_LINK

-----------------------------------------------------------
	INSERT INTO #RES0 (
		LINK_FACE,
		SEX,
		INNFIZ, --NALOG,
		NUMB_SERT,
		STATUS,
		FIO,
		FM, IM, OT,
		KDVD,
		SERNOM, 
		BIRTH,
		GRAZD,
		KSTR,
		LINK_ADR,
		IND_ADR,
		REGION,
		RAION,
		GOROD,
		NASEL,
		STREET,
		HOUSE,
		KORP,
		FLAT, 
		KSTR_ino,
		Adr_ino,
		ERR,
		O_OKATO,
		O_OKTMO,
		O_KPP
	)

	SELECT 	distinct 
		P.LINK, P.SEX, P.INN, /*P.IFNS,*/ P.INSUR_NUM, 
		CASE 
			WHEN P.RESIDENT  IS NULL THEN ''
			WHEN P.RESIDENT = 1 THEN '1'
			WHEN P.RESIDENT = 0 THEN '2'
		END,
		RTRIM(P.FM) + ',' + RTRIM(P.IM) + ',' + RTRIM(P.OT),
		RTRIM(P.FM), RTRIM(P.IM), RTRIM(P.OT),
		[KDVD] = (SELECT TOP 1 CODE FROM FACE_DOCUMENT WHERE LINK = P.DOC_LINK),
		P.DOC_NUM,
		P.BIRTHDATE,
		GRAZD= (SELECT TOP 1 CODE FROM CITIZENSHIP WHERE LINK = P.CITIZ_LINK),
		KSTR= (case when (SELECT TOP 1 CODE FROM CITIZENSHIP WHERE LINK = P.CITIZ_LINK) = '1' then '643' else '' END),
		ADR.LINK_ADDR,
		ADR.IND_ADR,
		ADR.REGION,
		ADR.RAION,
		ADR.GOROD,
		ADR.NASEL,
		ADR.STREET,
		ADR.HOUSE,
		ADR.KORP,
		ADR.FLAT,
		KSTR_ino = '',
		Adr_ino = '',
		0,
		PO.O_OKATO,
		PO.O_OKTMO,
		PO.O_KPP
	FROM 
		#FACES F 
		INNER JOIN PERSON P ON P.LINK = F.PERS_LINK
		INNER JOIN (SELECT LINK_FACE from #S_J_C_Short SJC where LINK_FACE is not null
			UNION SELECT LINK_FACE= PERS_LINK from #S_J_C_Short SJC where PERS_LINK is not null) J on P.LINK = J.LINK_FACE
		LEFT OUTER JOIN dbo.DOP_VZNOS_GET_ADDRESS() ADR ON P.LINK = ADR.LINK_FACE
		LEFT JOIN #P_OBOSOB PO ON PO.PERS_LINK = F.PERS_LINK
	WHERE 
		j.LINK_FACE in (select PERS_LINK from #FACES )
	ORDER BY 
		RTRIM(P.FM) + ',' + RTRIM(P.IM) + ',' + RTRIM(P.OT)

--Перечисленная сумма по всем за период
DECLARE @SUMMA_PLAT_ALL NUMERIC(18,2)
EXEC dbo.SS_DOP_VZNOS_PLAT @BEGIN_YEAR, @DATE_R, @DEP_LINK, @SUMMA_PLAT_ALL OUTPUT

declare @SUMMA_UD_ALL NUMERIC(18,2) 
SELECT @SUMMA_UD_ALL =  (SELECT sum(summa) FROM #S_J_C_SHORT )   

declare @SUMMA_UD_FACE NUMERIC(18,2)
SELECT @SUMMA_UD_FACE = (SELECT sum(summa) 
                         FROM #S_J_C_SHORT  
						 WHERE 
							(
							LINK_FACE in (select PERS_LINK from #FACES )
							or
							PERS_LINK in (select PERS_LINK from #FACES )
							)
						)



--Перечисленная за сотрудника	
UPDATE #RES0 SET sum_dop = CONVERT(NUMERIC(18,0), ISNULL( @SUMMA_PLAT_ALL * (@SUMMA_UD_FACE	/ @SUMMA_UD_ALL), 0))


--UPDATE #RES0 SET NALOG13S = CASE WHEN NALOG13S > NALOGU13 THEN NALOGU13 ELSE NALOG13S END

	-------------------------------------
	update #res0
	set 	VIFNSPL =0, ZSummPL =0, UdSumPL =0, VzkIFNS =0


	DECLARE @varKSCNT INT

	SELECT @varKSCNT  = COUNT(*) FROM #RES0

	SELECT TOP 1 
		LTRIM(RTRIM(STR(@varKSCNT))) AS DOCCOUNT, 
		ISNULL(IMNS, '') AS NALOG,
		ISNULL(dd.INN, '') AS INN,
		ISNULL(KPP, '') AS KPP,
		ISNULL(OKATO, '')  AS OKATO,
		ISNULL(OKTMO, '')AS OKTMO,
		convert(varchar (254),(ISNULL(FULL_NAME, ''))) AS FULL_NAME,
		ISNULL(DOTF.PHONE, '') AS PHONE,
		ISNULL(RTRIM(FM), '') + ' ' + ISNULL(RTRIM(IM), '') + ' ' + ISNULL(RTRIM(OT), '') AS GLBUH,
		ISNULL(RTRIM(FM), '') AS FM,
		ISNULL(RTRIM(IM), '') AS IM, 
		ISNULL(RTRIM(OT), '') AS OT,
		ISNULL(RTRIM(DOTF.NAME), '') AS Dolzh
	INTO #DEP
	FROM DICTIONARY_DEPARTMENT DD 
	LEFT OUTER JOIN DICTIONARY_OTV_FACE DOTF ON 
		(DOTF.DEP_LINK = DD.LINK
		AND DOTF.NAME = 'Главный бухгалтер')
	LEFT OUTER JOIN KU_EMPL_PLACING EP ON DOTF.FACE_LINK = EP.LINK
	WHERE DD.link = @DEP_LINK



	DECLARE @varKScInn VARCHAR(254), @varKScKPP VARCHAR(254), @varKSFULL_NAME varchar(254), 
		@varKSNALOG VARCHAR(254), @varKSOKATO VARCHAR(254), @varKSOKTMO VARCHAR(254), @varKSPHONE VARCHAR(254), 
		@varKSGLBUH VARCHAR(254), 
		@varKSRESULT BIT

	SELECT 
		@varKScInn = INN, @varKScKPP = KPP,
		@varKSFULL_NAME = FULL_NAME, 
		@varKSNALOG = NALOG, @varKSOKATO = Replace(OKATO,' ',''), @varKSOKTMO = Replace(OKTMO,' ',''),
		@varKSPHONE = PHONE, 
		@varKSGLBUH  = GLBUH
	FROM #DEP
	
	UPDATE #RES0
		set NOM_SPR = CASE WHEN ISNULL(@cNumSPR,'') = '' THEN '' ELSE @cNumSPR   END 

	-------------------
	SELECT 
		R.ID, R.NOM_SPR, R.LINK_FACE, R.SEX, R.INNFIZ, R.NUMB_SERT, R.STATUS, 
		R.FIO, R.FM, R.IM, R.OT, R.KDVD, R.SERNOM, R.BIRTH, R.GRAZD, R.KSTR, 
		R.LINK_ADR, R.IND_ADR, R.REGION, R.RAION, R.GOROD, R.NASEL, R.STREET, 
		R.HOUSE, R.KORP, R.FLAT, R.KSTR_ino, R.Adr_ino, 
		R.SUM_DOP,
		nalog	= @varKSNALOG,
		KPP1 = ISNULL(R.O_KPP,@varKScKPP),
		OKATO1 = replace(ISNULL(R.O_OKATO,@varKSOKATO),' ',''),
		OKTMO1 = replace(ISNULL(R.O_OKATO,@varKSOKTMO),' ','')
	FROM #RES0 R 


	---
	SELECT *, CAST(  (CAST (DOCCOUNT AS INT) - @varKSCNT) AS VARCHAR(254) ) AS DOCCOUNT2 FROM #DEP 
	---	
	EXEC dbo.BufferClear
	---

	DROP TABLE #E_SUBDIV
	DROP TABLE #S_OBOSOB
	DROP TABLE #P_OBOSOB	
	DROP TABLE #RES0	
			
	
END




GO
-- SS_SPR_DOP_VZNOS '2013' , 11 , '' 

GRANT EXECUTE ON dbo.[SS_SPR_DOP_VZNOS] TO PUBLIC

GO



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

GO

CREATE PROCEDURE [dbo].[SA_CREATE_PROV_VEDOM] @nMONTH INT, @nYear INT, @LINK_DEP INT
/*
Процедура формирует проводки по удержаниям на выплату зарплаты через банк
по ведомостям для штатных и внештатных сотрудников
*/
AS BEGIN

SET NOCOUNT OFF

DECLARE @LINK_DOC_SAL INT,
	@NUM_DOC_SAL VARCHAR(25),
	@OSNOVANIE VARCHAR(100),
	@SUM_DOC_SAL NUMERIC(18,2),
	@ACC_CODE VARCHAR(20)

DECLARE @varKStrancount int, @varKSERROR as INT

DECLARE @CODE_OBJECT VARCHAR(254), @LINK_EKR_DEFAULT int

DECLARE @Cur CURSOR, @SRC VARCHAR(20), @LINK_EKR INT, @SUM_PROV numeric(18,2), @order int, @Account1 INT, @Account2 INT,	
	@HOZ_OPER int, @P1 float, @P2 float, @SGU INT, @DATE_VEDOM DATETIME,
	@LINK_KBK int, @LINK_KAU int, @LINK_DOP_KL int, @USER_ACC varchar(4), @CODE_SFIN VARCHAR(20), @Fin_Source CHAR(1) 

Set @order = 0

--Счет начислений на оплату труда (999)
SELECT TOP 1 @SRC = RTRIM(LTRIM(VALUE)) FROM dbo.S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SALARY_OPTIONS_OPT1'))) AND SID IS NULL
---
Declare @SAL_ACC_KD VARCHAR(10)
--Счет для расчетов по удержаниям из з/пл (999.99)
SELECT TOP 1 @SAL_ACC_KD = LTRIM(RTRIM(VALUE)) FROM dbo.S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SALARY_OPTIONS_OPT2'))) AND SID IS NULL

DECLARE @LINK_ORG int, @LINK_ACC int, @LINK_VEDOM INT
DECLARE @SALARY_PROV_OPT2 tinyint
--В комментарий проводки ставить комментарий из документа
SET @SALARY_PROV_OPT2 = dbo.SA_GET_OPTION_BY_CODE('SALARY_PROV_OPT2')
--SELECT * FROM S_OBJECTS WHERE CODE = 'VEDOM_OPTIONS_OPT11'

--период редактирования
DECLARE @BB DATETIME, @BE DATETIME
SELECT @BB = BEGINDATE, @BE = ENDDATE FROM dbo.ADMIN_INFO

SET @Cur = CURSOR FORWARD_ONLY
FOR 
-- Данные для проводок
SELECT
	S.LINK,
	CASE WHEN dbo.SA_GET_OPTION_BY_CODE('VEDOM_OPTIONS_OPT11') = 1 THEN dbo.DateEndOfMonth(D.REF_BASE) ELSE S.[DATE] END,
	O.CODE,
 	JC.LINK_EKR, 
	LINK_KBK = F.KBK,
	LINK_KAU = F.KAU,
	LINK_DOP_KL = F.DOP_KL,
	USER_ACC = F.USER_ACC,
	CODE_SFIN = F.CODE,
	COALESCE(CAST (F.SOURCE as CHAR(1)),''),
	SUMMA= SUM(JC.SUMMA),
	T.LINK_ORG,
	T.LINK_ACC,
	CASE WHEN @SALARY_PROV_OPT2 = 0 
		THEN 'Удержание на выплату' + (CASE WHEN RTRIM(LTRIM(O.CODE)) = 'DOCUMENTS_DED_PAYROLL' THEN '' ELSE ' внештатникам' END) + ' з/пл через банк' 
	ELSE
		'Ведомость' + (CASE WHEN RTRIM(LTRIM(O.CODE)) = 'DOCUMENTS_DED_PAYROLL' THEN '' ELSE ' внештатникам' END) + ' №' + RTRIM(LTRIM(COALESCE(NUMBER,''))) + ' от ' + COALESCE(convert(VARCHAR(10),[DATE], 104),'') + ' ' + RTRIM(LTRIM(COMMENTARY))
	END	
FROM	
	dbo.SDOC S INNER JOIN dbo.S_OBJECTS O ON S.OBJECT = O.LINK
	INNER JOIN 
	(
		SELECT CARD_LINK, LINK, REF_BASE FROM dbo.DOCUMENTS_DED_PR V1
		UNION ALL
		SELECT CARD_LINK, LINK, REF_BASE FROM dbo.DOCUMENTS_DED_PR_DGH V2
	) D ON S.LINK = D.LINK
	INNER JOIN CALCULATE_JURNAL JC ON D.LINK = JC.LINK_DOC
	INNER JOIN dbo.SAL_SFIN F ON F.LINK = JC.LINK_VKR
	LEFT JOIN TAX2_APP T on JC.LINK_PAYS = T.link_up
WHERE   
	NOT JC.LINK_PAYS IS NULL AND JC.LINK_PAYS<>0  
	--AND MONTH(JC.PERIOD_BEGIN) = @nMONTH AND YEAR(JC.PERIOD_BEGIN) = @nYEAR
	AND MONTH(S.[DATE]) = @nMONTH AND YEAR(S.[DATE]) = @nYEAR
	AND JC.LINK_DEP = @LINK_DEP
	AND CARD_LINK IS NOT NULL
	AND JC.LINK_PAYS <> dbo.sa_get_option_by_code('VEDOM_OPTIONS_OPT10')
GROUP BY 
	S.LINK, O.CODE, S.[DATE], D.REF_BASE, JC.LINK_EKR, F.KBK, F.KAU, F.DOP_KL, F.USER_ACC, F.CODE, F.SOURCE, T.LINK_ORG, T.LINK_ACC, S.LINK, 

	CASE WHEN @SALARY_PROV_OPT2 = 0 
		THEN 'Удержание на выплату' + (CASE WHEN RTRIM(LTRIM(O.CODE)) = 'DOCUMENTS_DED_PAYROLL' THEN '' ELSE ' внештатникам' END) + ' з/пл через банк' 
	ELSE
		'Ведомость' + (CASE WHEN RTRIM(LTRIM(O.CODE)) = 'DOCUMENTS_DED_PAYROLL' THEN '' ELSE ' внештатникам' END) + ' №' + RTRIM(LTRIM(COALESCE(NUMBER,''))) + ' от ' + COALESCE(convert(VARCHAR(10),[DATE], 104),'') + ' ' + RTRIM(LTRIM(COMMENTARY))
	END
	
ORDER BY
	F.SOURCE

--------------------
OPEN @Cur
FETCH NEXT FROM @Cur INTO @LINK_VEDOM, @DATE_VEDOM, @CODE_OBJECT, @LINK_EKR, @LINK_KBK, @LINK_KAU, @LINK_DOP_KL, @USER_ACC, @CODE_SFIN, @Fin_Source,@SUM_PROV, @LINK_ORG, @LINK_ACC, @OSNOVANIE
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN
		IF COALESCE(@SUM_PROV,0) <> 0 BEGIN

			IF @DATE_VEDOM NOT BETWEEN @BB AND @BE
				SET @DATE_VEDOM = dbo.DateEndOfMonth( dbo.ConvertDMY2Date(1,@nMONTH,@nYEAR))

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

			IF @varKSERROR <> 0
				RETURN @varKSERROR
			--------------------

			SET @LINK_EKR_DEFAULT = (SELECT TOP 1 LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = CASE WHEN RTRIM(LTRIM(@CODE_OBJECT)) = 'DOCUMENTS_DED_PAYROLL' THEN '211' ELSE '226' END)
			SET @LINK_EKR = COALESCE(@LINK_EKR,@LINK_EKR_DEFAULT)

			--SET @OSNOVANIE = 'Удержание на выплату' + CASE WHEN RTRIM(LTRIM(@CODE_OBJECT)) = 'DOCUMENTS_DED_PAYROLL' THEN '' ELSE ' внештатникам' END + ' з/пл через банк'
				
			-- Сохраняем документ
			SELECT @LINK_DOC_SAL = 0, @NUM_DOC_SAL = NULL
			-- определим максимальный номер
			exec dbo.X_DOCUMENT_GET_MAX_NUMBER 'DOCUMENTS_SALARY', @NUM_DOC_SAL output, @LINK_DEP
			SET @NUM_DOC_SAL = CASE WHEN @NUM_DOC_SAL is null THEN '0001' ELSE convert(VARCHAR(25),convert(int, @NUM_DOC_SAL)+1) END

			exec X_SAVE_DOCUMENTS_SALARY @LINK_DOC_SAL OUT, @NUM_DOC_SAL, @DATE_VEDOM, @DATE_VEDOM, @SUM_PROV, @OSNOVANIE, @LINK_DEP, NULL

			--Связь между проводкой и ведомостью
			INSERT INTO dbo.sdoc_vedom_rko (LINK_VEDOM, LINK_RKO, COMMENT) VALUES(@LINK_VEDOM, @LINK_DOC_SAL, @OSNOVANIE)

			SET @P1 = NULL
			exec X_UPDATE_G_PROV1 @P1 output, @LINK_DOC_SAL, NULL, @OSNOVANIE, 1
	
			Set @order = @order + 1

			IF RTRIM(LTRIM(COALESCE(@SRC,''))) = '' BEGIN
				ROLLBACK
				SET IMPLICIT_TRANSACTIONS OFF
				INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
				select 'Не сформированы проводки: ' + @OSNOVANIE,
					'Не указан cчет начислений на оплату труда в общих настройках по зарплате.',
					'Укажите cчет начислений на оплату труда в общих настройках по зарплате.',
					'SALARY'
				GOTO DO_NEXT
			END	
	
			IF RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> ''
				Set @Account1 = (SELECT TOP 1 link FROM dbo.S_ACCOUNTS WHERE cSource = @Fin_Source and cSinth = RTRIM(LTRIM(@SRC)) and ANALIT_EKR = @LINK_EKR AND cUser = RTRIM(LTRIM(COALESCE(@USER_ACC,''))) )
			ELSE 
				Set @Account1 = (SELECT TOP 1 link FROM dbo.S_ACCOUNTS WHERE cSource = @Fin_Source and cSinth = RTRIM(LTRIM(@SRC)) and ANALIT_EKR = @LINK_EKR)				

			IF COALESCE(@Account1,0) = 0 BEGIN 
				ROLLBACK
				SET IMPLICIT_TRANSACTIONS OFF
				INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
				select 'Не сформированы проводки ' + @OSNOVANIE,
					'В плане счетов не найден счет ' + @Fin_Source + '.' + RTRIM(LTRIM(@SRC)) + '.0X' + CASE WHEN RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> '' THEN '/' + RTRIM(LTRIM(COALESCE(@USER_ACC,''))) else '' END + ' с настройкой на ЭКР ' + RTRIM(LTRIM((select top 1 code from KOSGU where LINK = @LINK_EKR))),
					'Добавьте в план счетов такой счет или укажите ЭКР в нстройках счета',
					'SALARY'
				GOTO DO_NEXT
			END

			---
			SET @ACC_CODE = (select top 1 A2.CODE from dbo.S_ACCOUNTS A1 inner join dbo.S_ACCOUNTS A2 on A1.link_self = A2.link
				WHERE A2.LINK = @Account1 and A2.cSource <> '')

			IF  RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) <> '' AND RTRIM(LTRIM(COALESCE(@USER_ACC,''))) = '' BEGIN
				ROLLBACK
				SET IMPLICIT_TRANSACTIONS OFF
				INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
				select 'Не сформированы проводки: ' + @OSNOVANIE,
					'У источника финансирования ' + RTRIM(LTRIM(@CODE_SFIN)) + ' не указан пользовательский субсчет, однако у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' есть субсчета',
					'Укажите пользовательский субсчет, либо уберите в плане счетов субсчет у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' с помощью слияния',
					'SALARY'
				GOTO DO_NEXT
			END
			
			--Определяем счет в настройках по зарплате
			Set @Account2 = (SELECT TOP 1 link FROM dbo.S_ACCOUNTS 	WHERE cSource = RTRIM(LTRIM(@Fin_Source)) 
				and cSinth = RTRIM(dbo.SA_GET_WORD_NUM(@SAL_ACC_KD,1,'.')) and cAnalit = RTRIM(dbo.SA_GET_WORD_NUM(@SAL_ACC_KD,2,'.')))	

			IF COALESCE(@Account2,0) = 0 BEGIN
				ROLLBACK
				SET IMPLICIT_TRANSACTIONS OFF
				INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
				select 'Не сформированы проводки: ' + @OSNOVANIE,
					'Не указан (либо указан несуществующий для данного вида деятельности) счет для расчетов по удержаниям из з/пл в общих настройках по зарплате.',
					'Укажите счет для расчетов по удержаниям из з/пл в общих настройках по зарплате',
					'SALARY'
				GOTO DO_NEXT
			END	

			IF RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> '' BEGIN
				
				Set @Account2 = (select top 1 A1.link from dbo.S_ACCOUNTS A1 inner join dbo.S_ACCOUNTS A2 on A1.link_self = A2.link
						WHERE A2.LINK = @Account2 AND A1.cUser = RTRIM(LTRIM(COALESCE(@USER_ACC,''))))

				IF COALESCE(@Account2,0) = 0 BEGIN 
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформированы проводки: ' + @OSNOVANIE,
						'В плане счетов не найден счет ' + RTRIM(LTRIM(@Fin_Source)) + '.'+ RTRIM(LTRIM(@SAL_ACC_KD)) + '/' + RTRIM(LTRIM(COALESCE(@USER_ACC,''))),
						'Добавьте в план счетов счет ' + RTRIM(LTRIM(@Fin_Source)) + '.'+ RTRIM(LTRIM(@SAL_ACC_KD)) + '/' + RTRIM(LTRIM(COALESCE(@USER_ACC,''))),
						'SALARY'
					GOTO DO_NEXT
				END

			END


			---
			SET @ACC_CODE = (select top 1 A2.CODE from dbo.S_ACCOUNTS A1 inner join dbo.S_ACCOUNTS A2 on A1.link_self = A2.link
				WHERE A2.LINK = @Account2 and A2.cSource <> '')

			IF  RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) <> '' AND RTRIM(LTRIM(COALESCE(@USER_ACC,''))) = '' BEGIN
				ROLLBACK
				SET IMPLICIT_TRANSACTIONS OFF
				INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
				select 'Не сформированы проводки: ' + @OSNOVANIE,
					'У источника финансирования ' + RTRIM(LTRIM(@CODE_SFIN)) + ' не указан пользовательский субсчет, однако у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' есть субсчета',
					'Укажите пользовательский субсчет, либо уберите в плане счетов субсчет у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' с помощью слияния',
					'SALARY'
				GOTO DO_NEXT
			END

			IF COALESCE(@Account1,0) > 0 AND COALESCE(@Account2,0) > 0 BEGIN
	
				SET @HOZ_OPER = (SELECT TOP 1 LINK FROM dbo.BX_BPROV_VIBOR_ECON_OPER(@Account1,@Account2))

				IF COALESCE(@HOZ_OPER,0) = 0 BEGIN
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформированы проводки: ' + @OSNOVANIE,
						'Не найдено подходящей хоз. операции для проводки ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account1) + '-' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account2),
						'Вероятно в общих настройках по зарплате указан некорректный счет для начисления на оплату труда или счет для расчетов по удержаниям из з/пл.',
						'SALARY'
					GOTO DO_NEXT
				END	
	
				set @P2 = null
				exec X_UPDATE_G_PROV2 @P2 output, @P1, NULL, @SUM_PROV, 0, 0, @OSNOVANIE, @HOZ_OPER, @order
				
				SET @SGU = (SELECT TOP 1 LINK_SGU FROM S_ACCOUNTS_SGU SGU INNER JOIN KOSGU ON SGU.LINK_SGU = KOSGU.LINK WHERE DB_KR = 0 AND ACCOUNT = @Account1)
				IF EXISTS (SELECT p_KASSA FROM dbo.s_accounts WHERE LINK = @Account1 AND p_KASSA = 1)
					SET @SGU = @LINK_EKR

				IF COALESCE(@SGU,0) = 0 BEGIN
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформированы проводки : ' + @OSNOVANIE,
						'У счета ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account1) + ' не задано СГУ',
						'Укажите СГУ в настройках счета в плане счетов',
						'SALARY'
					GOTO DO_NEXT
				END	

				exec X_UPDATE_G_PROV_AP @P2, 0, @Account1, @LINK_KBK, @LINK_EKR, @LINK_DEP, NULL, NULL, NULL, NULL, @LINK_KAU, NULL, NULL, NULL, NULL, @LINK_DOP_KL, NULL, @SGU
				------		
				SET @SGU = (SELECT TOP 1 LINK_SGU FROM S_ACCOUNTS_SGU SGU INNER JOIN KOSGU ON SGU.LINK_SGU = KOSGU.LINK WHERE DB_KR = 1 AND ACCOUNT = @Account2)
				IF EXISTS (SELECT p_KASSA FROM dbo.s_accounts WHERE LINK = @Account2 AND p_KASSA = 1)
					SET @SGU = @LINK_EKR

				IF COALESCE(@SGU,0) = 0 BEGIN
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформированы проводки : ' + @OSNOVANIE,
						'У счета ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account2) + ' не задано СГУ',
						'Укажите СГУ в настройках счета в плане счетов',
						'SALARY'
					GOTO DO_NEXT
				END	

				exec X_UPDATE_G_PROV_AP @P2, 1, @Account2, @LINK_KBK, @LINK_EKR, @LINK_ORG, NULL, NULL, NULL, NULL, @LINK_KAU, @LINK_ACC, NULL, NULL, NULL, @LINK_DOP_KL, NULL, @SGU
			END

			IF @@TRANCOUNT > @varKStrancount BEGIN
				COMMIT TRAN
				SET IMPLICIT_TRANSACTIONS OFF
			END
	
			---Если надо, то сформировать БО
			DECLARE @TestBO tinyint
			exec @TestBO = dbo.XD_TEST_FORM_BO @LINK_DOC_SAL 
			IF @TestBO = 0
			BEGIN
				create table #tProtocol1(txt varchar(1000), NEW_ROW tinyint, nSTATUS tinyint, nTAB tinyint, ord int identity(1,1))

				insert into #tProtocol1 (txt, NEW_ROW, nSTATUS, nTAB) 
				Exec dbo.XD_FORM_BO @LINK_DOC_SAL

				IF EXISTS (SELECT * FROM #tProtocol1 WHERE nSTATUS >=1 )
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Обнаружены замечания при формирование БО:', CASE WHEN nSTATUS = 1 THEN 'Предупреждение!' ELSE 'Ошибка!' END + SPACE(1) + LEFT(txt,240), 'Устраните замечания!', 'SALARY'
					FROM #tProtocol1	WHERE nSTATUS >= 1
				
				DROP TABLE #tProtocol1
					
			END	
		END
	END
	DO_NEXT:
	FETCH NEXT FROM @Cur INTO @LINK_VEDOM, @DATE_VEDOM, @CODE_OBJECT, @LINK_EKR, @LINK_KBK, @LINK_KAU, @LINK_DOP_KL, @USER_ACC, @CODE_SFIN, @Fin_Source,@SUM_PROV, @LINK_ORG, @LINK_ACC, @OSNOVANIE
END

CLOSE @Cur
DEALLOCATE @Cur

exec X_SALDO_CommitChanges

SET NOCOUNT OFF
Return 0
END


GO


GRANT EXECUTE ON dbo.[SA_CREATE_PROV_VEDOM] TO PUBLIC

GO

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

GO

CREATE	PROCEDURE dbo.BV_SAVE_G_PROV1_AVANSE_REP
	@varKSnLINK_DOC INT,
	@varKSnDEL	TINYINT = 0	

AS

DECLARE 
--	@varKSnTYP_LINK INT,			
	@varKScNAME_OPER VARCHAR(250),
	@varKScNAME_DOC VARCHAR(100),
	@varKSnSUMMA NUMERIC(28,2),
	@varKSnQTY NUMERIC(19,4),
	@varKSnDT_LINK INT,
	@varKSnKT_LINK INT,
	@varKSnLINK_GP1 INT,
	@varKSnORDERS INT,
--	@varKSdCALC_DATE DATETIME,
	@varKSxRet	INT,
	@varKSnEKR_DT INT,
	@varKSnEKR_KT INT,
	@varKSnEMP INT,
	@varKSnOSNOV INT,
	@varKSnINV INT,
	@varKSnNOMEN INT,
	@varKScErrTxt VARCHAR(60),
	@intAO_EMPL INT,
	@intAO_KBK INT,
	@intAO_DEP INT,
	@intAO_SUB INT,
	@LINK_ROW	INT



DECLARE GRID_CUR CURSOR LOCAL STATIC READ_ONLY FOR
	SELECT
		LINK,
		NAMEDOC,
		SUMACCEPTED,
		DT,
		KT,
		EKR_LINK_DT,
		EKR_LINK_KT,
		EMP_LINK,
		OSNOV_LINK,
		CASE
			WHEN MZ_TYPE = 1 THEN MZ_LINK
			ELSE NULL
		END AS INV,
		CASE
			WHEN MZ_TYPE = 2 THEN MZ_LINK
			ELSE NULL
		END AS NOMEN,
		QTY
	FROM dbo.BK_DOC_TABLE_AO_FN (@varKSnLINK_DOC)
	WHERE SUMACCEPTED <> 0
		AND DTACCOUNT IS NOT NULL AND KTACCOUNT IS NOT NULL

SELECT 	@intAO_EMPL = EMP_LINK,
	@intAO_KBK = KBK_LINK,
	@intAO_DEP = DEP_LINK,
	@intAO_SUB = OTDEL_LINK
FROM dbo.BV_DOC_AVANSE_REP
WHERE LINK = @varKSnLINK_DOC

IF @varKSnLINK_DOC IS NULL OR @varKSnLINK_DOC <= 0
	RETURN -1	

IF @varKSnDEL = 1
  BEGIN
	PRINT 'Удаление существующих проводок'
	DELETE FROM G_PROV1 WHERE LINK_UP = @varKSnLINK_DOC
  END

SET @varKSnORDERS = 0

OPEN GRID_CUR
FETCH FROM GRID_CUR
	INTO @LINK_ROW,
		@varKScNAME_DOC,
		@varKSnSUMMA,
		@varKSnDT_LINK,
		@varKSnKT_LINK,
		@varKSnEKR_DT,
		@varKSnEKR_KT,
		@varKSnEMP,
		@varKSnOSNOV,
		@varKSnINV,
		@varKSnNOMEN,
		@varKSnQTY
		
WHILE @@FETCH_STATUS = 0
BEGIN
	SET @varKSnORDERS = @varKSnORDERS + 1

	SET @varKScNAME_OPER = 'Содержание операции: ' + RTRIM(ISNULL(@varKScNAME_DOC,'информация отсутствует'))

	SET @varKSnLINK_GP1 = NULL
	EXEC dbo.X_UPDATE_G_PROV1 @varKSnLINK_GP1 OUTPUT, @varKSnLINK_DOC, NULL,
			@varKScNAME_OPER, @varKSnORDERS

	IF @varKSnLINK_GP1 IS NULL
		RETURN -3	
	SET @varKSnQTY = ISNULL(@varKSnQTY,0)
	EXEC @varKSxRet = dbo.BV_SAVE_G_PROV2_AP_AO_REP @varKSnLINK_GP1, @varKSnDT_LINK, @varKSnKT_LINK, @varKSnEKR_DT, @varKSnEKR_KT, @varKSnEMP, @varKSnOSNOV, @varKSnINV, @varKSnNOMEN, @varKSnSUMMA, @varKSnQTY,
		@intAO_KBK, @intAO_DEP, @intAO_SUB, @intAO_EMPL

	IF @varKSxRet <> 0
	  BEGIN
/*	    SET @varKScErrTxt = CASE @varKSxRet
				WHEN -1 THEN '"Не задан линк операции"'
				WHEN -2 THEN '"Не найден остаток по данному ОС"'
			   END */
	    PRINT 'Ошибка при записи проводки'
	    IF @varKSxRet = -2
		RETURN -5	
	    ELSE
		RETURN -4	
	  END

	UPDATE OTR
	SET LINK_OPER = @varKSnLINK_GP1
	FROM dbo.OUT_TABLE_ROW OTR
	WHERE OTR.LINK = @LINK_ROW

	FETCH NEXT FROM GRID_CUR
		INTO @LINK_ROW,
			@varKScNAME_DOC,
			@varKSnSUMMA,
			@varKSnDT_LINK,
			@varKSnKT_LINK,
			@varKSnEKR_DT,
			@varKSnEKR_KT,
			@varKSnEMP,
			@varKSnOSNOV,
			@varKSnINV,
			@varKSnNOMEN,
			@varKSnQTY

END

CLOSE GRID_CUR
DEALLOCATE GRID_CUR

EXEC dbo.X_SALDO_COMMITCHANGES	

RETURN 0

GO

GRANT EXECUTE ON dbo.[BV_SAVE_G_PROV1_AVANSE_REP] TO PUBLIC

GO


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


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

GO

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

CREATE PROCEDURE dbo.BV_AVANSE_TABLE_SAVE
	@varKSintLINK	INT	OUTPUT,
	@varKSLink_Up	INT,
	@varKSNumber	INT,
	@varKSDateDoc	DateTime,
	@varKSNumDoc	VARCHAR(50),
	@varKSNameDoc	VARCHAR(100),
	@varKSSumReport	NUMERIC(13,2),
	@varKSSumAccepted	NUMERIC(13,2),
	@varKSDtAccount	VARCHAR(13),
	@varKSKtAccount	VARCHAR(13),
	@varKSEkrDT	INT,
	@varKSEkrKT	INT,
	@varKSEMP	INT,
	@varKSSumNDFL	INT,
	@varKSSumVznos	INT,
	@varOSNOV	INT,
	@varINV		INT,
	@varNOMEN	INT,
	@varQTY		NUMERIC(19,4)
AS
BEGIN
	DECLARE
		@varKSSQLError	int,
		@varKSRowCount	int,
		@varKStrancount	int,
		@varKSAccountDT	int,
		@varKSAccountKT	int,
		@iTAB_ID	INT

	SET @varKStrancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON
	BEGIN TRAN
	COMMIT TRAN
	
	IF @varKSDtAccount IS NOT NULL AND @varKSDtAccount <> ''
	BEGIN
		SELECT @varKSAccountDT = LINK From dbo.S_ACCOUNTS WITH (UPDLOCK) Where CODE = @varKSDtAccount AND ZABALANS = 0
		SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK TRAN
			RETURN 3
		END
	END
	ELSE
		SET @varKSAccountDT = NULL
	
	IF @varKSKtAccount IS NOT NULL AND @varKSKtAccount <> ''
	BEGIN
		SELECT @varKSAccountKT = LINK From dbo.S_ACCOUNTS WITH (UPDLOCK) Where CODE = @varKSKtAccount AND ZABALANS = 0
		SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK TRAN
			RETURN 3
		END
	END
	ELSE
		SET @varKSAccountKT = NULL

	SET @varKSEkrDT = (SELECT LINK FROM dbo.KOSGU WHERE LINK = @varKSEkrDT)
	SET @varKSEkrKT = (SELECT LINK FROM dbo.KOSGU WHERE LINK = @varKSEkrKT)
	SET @varOSNOV = (SELECT LINK FROM dbo.OSNOV WHERE LINK = @varOSNOV)
	SET @varINV = (SELECT LINK FROM dbo.INVENTORY WHERE LINK = @varINV)
	SET @varNOMEN = (SELECT LINK FROM dbo.NOMENCLATURE WHERE LINK = @varNOMEN)
	SET @varKSEMP = (SELECT LINK FROM dbo.EMPL WHERE LINK = @varKSEMP)

	-- Вставка/обновление OUT_TABLE_ROW --
	SELECT TOP 1
		@iTAB_ID = LINK
	FROM dbo.S_OBJECTS 
	WHERE CODE = 'BV_DOC_AVANSE_TABLE'

	EXECUTE @varKSSQLError = dbo.X_UPDATE_OUT_TABLE_ROW
				@varKSintLINK OUTPUT,
				@varKSLink_Up,
				@iTAB_ID,
				@varKSNumber
				
	IF @varKSSQLError <> 0 OR NOT EXISTS (SELECT * FROM dbo.OUT_TABLE_ROW WHERE LINK = @varKSintLINK)
	BEGIN
		ROLLBACK
		RAISERROR ('Строка была удалена!', 11, 1)
		RETURN @varKSSQLError
	END	

	Set @varKSRowCount = 0
	IF @varKSintLINK <> 0 and @varKSintLINK is not null
	BEGIN
		UPDATE dbo.G_AVANSE_TABLE
		SET NUMBER = @varKSNumber,
			DATEDOC = @varKSDATEDOC,
			NUMDOC = @varKSNUMDOC,
			NAMEDOC = @varKSNAMEDOC,
			SUMREPORT = @varKSSUMREPORT,
			SUMACCEPTED = @varKSSUMACCEPTED,
			DTACCOUNT = @varKSAccountDT,
			KTACCOUNT = @varKSAccountKT,
			SUM_NDFL = @varKSSumNDFL,
			SUM_VZNOS = @varKSSumVznos,
			EKR_DT = @varKSEkrDT,
			EKR_KT = @varKSEkrKT,
			EMP = @varKSEMP,
			OSNOV = @varOSNOV,
			INV = @varINV,
			NOMEN = @varNOMEN,
			QTY = @varQTY
		WHERE LINK_UP = @varKSintLINK

		SELECT @varKSRowCount = @@ROWCOUNT, @varKSSQLError = @@ERROR

		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END

	IF @varKSRowCount = 0
	BEGIN
		INSERT INTO dbo.G_AVANSE_TABLE
			(
			LINK_UP,
			NUMBER,
			DATEDOC,
			NUMDOC,
			NAMEDOC,
			SUMREPORT,
			SUMACCEPTED,
			DTACCOUNT,
			KTACCOUNT,
			SUM_NDFL,
			SUM_VZNOS,
			EKR_DT,
			EKR_KT,
			EMP,
			OSNOV,
			INV,
			NOMEN,
			QTY
			)
		VALUES
			(
			@varKSintLINK,
			@varKSNumber,
			@varKSDATEDOC,
			@varKSNUMDOC,
			@varKSNAMEDOC,
			@varKSSUMREPORT,
			@varKSSUMACCEPTED,
			@varKSAccountDT,
			@varKSAccountKT,
			@varKSSumNDFL,
			@varKSSumVznos,
			@varKSEkrDT,
			@varKSEkrKT,
			@varKSEMP,
			@varOSNOV,
			@varINV,
			@varNOMEN,
			@varQTY
			)

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

	IF @@TRANCOUNT > @varKStrancount
		COMMIT TRAN
	RETURN 0
END

GO

GRANT EXECUTE ON dbo.[BV_AVANSE_TABLE_SAVE] TO PUBLIC

GO

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

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

GO

/*
	Расчет формул для формирования отчета
	20060817 - доступ к колонке
*/
CREATE PROCEDURE dbo.RI_REPORT_FORMULA_ALL_CALCULATE 
	@dBegin datetime = '20050101', @dEnd datetime = '20051231', @perType int = 1, @perNom int = 1, @LSF int = NULL,@cTables varchar(1000)= '',@cParam varchar(50)='' -- входные параметры
AS

DECLARE 
	@varKSstrVALUE	varchar(7000),
	@varKStrancount	int,
	@varKSERROR		int,
	@varKSRowCount	int,
	@varKSEventStr	varchar (200),
	@varKSEventStr2	varchar (200),
	@varKSLink_Task	int,
	@varKSLink_last_event int,
    @cstr varchar(5000),    
    @cForm varchar(50),
	@iNotCalc		tinyint

if @LSF is NULL
	return -1
if not exists(select * from report_saved_forms where Link_Saved_Form = @LSF)
	return -2

SET DATEFORMAT ymd
--перенос формы из архивной базы
exec RN_MOVE_FORM_FROM_ARH @LSF

select @cForm=code from report_forms where link_form=(select link_form from report_saved_forms where link_saved_form=@LSF)

declare @linkRow int, @linkCol int, @Formula varchar(2000)
declare @tmp int, @i int, @subStr varchar(700), @Str varchar(1000)
IF @cTables=''
BEGIN
        -- обнуление всего
        update dbo.report_summa
        set summa = 0
        where Link_Saved_Form = @LSF --and dbo.RO_AccessColByLink(Link_Col) > 0 -- доступ к колонке должен быть
END
ELSE
BEGIN
        -- обнуление таблиц
        set @cstr='update dbo.report_summa
        set summa = 0
        where Link_Saved_Form = '+str(@LSF)+'  and EXISTS(select * from REPORT_COLOUMNS RC where RC.Link_col=REPORT_SUMMA.Link_Col AND RC.Link_Table in ('+@cTables+'))'
--        where Link_Saved_Form = '+str(@LSF)+' and dbo.RO_AccessColByLink(Link_Col) > 0 and EXISTS(select * from REPORT_COLOUMNS RC where RC.Link_col=REPORT_SUMMA.Link_Col AND RC.Link_Table in ('+@cTables+'))'

        exec(@cstr)
END

--считаем настройку - тип расчета
declare @cStrVal varchar(100),@type_calc int,@nameServer varchar(50),@nameBase varchar(50),@nameUser varchar(50),@userPass varchar(50)
exec X_GET_OPTION 'REPORT_ORTIONS_TYPE_CALC',0,@cStrVal output 	
set @type_calc=CAST(ISNULL(@cStrVal,'1') as int)

IF @type_calc = '2'
	exec dbo.RO_CALC_BKS @iNotCalc output, @LSF
ELSE
	set @iNotCalc = 1
  
if dbo.xk_get_nastr_int('XK_NASTR_REPORT_CALC') > 0 AND @iNotCalc = 1 
	exec RO_CALC_NASTR @iNotCalc output, @LSF

-- признак правильности КС становится неопределенным
update report_saved_forms
set IsRightKS = 0,
	modify_date = getdate()
where Link_Saved_Form = @LSF


-- увеличивается счетчик сохранения 
declare @liTable int,@cword varchar(20)
set @str=@cTables
create table #itables (link_table int)
WHILE LEN(RTRIM(@Str))>0
  BEGIN
    SET @i=@i+1
    exec RO_FORMULA_FUNCTIONS 1,@str output ,@cword output,','
    SET @liTable=CAST(@cword as int)
    INSERT #iTables (link_table) values (@liTable)            
    exec RN_INC_COUNTSAVE @LSF,@liTable,0
  END
exec RN_INC_COUNTSAVE @LSF,0,1

create table #F (Link_Row int,Link_Col int,Formula varchar(4000),rco int,cco int,tco int)

-- для рассчёта (72н)0503125
if (select Code from dbo.report_forms where Link_Form = (select link_form from dbo.report_saved_forms where link_saved_form = @LSF)) = '(72н)0503125'
begin
    exec dbo.RT_CALC_0503125 @LSF
    exec dbo.RO_CALCULATE_DOSCHET @LSF,@cTables
    return
end
-- для рассчёта (137н)0503125
if (select Code from dbo.report_forms where Link_Form = (select link_form from dbo.report_saved_forms where link_saved_form = @LSF)) = '(137н)0503125'
begin
    exec dbo.RT_CALC_0503125SE @LSF
    exec dbo.RO_CALCULATE_DOSCHET @LSF,@cTables
    return
end

if @iNotCalc = 1
BEGIN 
   IF @cForm like '0503074%' or @cForm='05030mo' OR @cForm like '0503075%' --для 14 формы нужен спец расчет 
       BEGIN
           delete report_dinamics where Link_SF = @LSF
           INSERT #F
           select RF.Link_Row, RF.Link_Col, dbo.RO_REPORT_FORMULA_REPLACE(Formula, @dBegin, @dEnd, RF.Link_Col, RF.Link_Row, @LSF,@cForm,'') as Formula, RR.Calc_Orders as rco, RC.Calc_Orders as cco, rt.orders as tco
           from	Report_Formula RF
        	   left join report_coloumns RC on RF.link_col = RC.link_col
        	   left join report_rows RR on RR.link_row = RF.link_row
        	   left join report_tables RT on RT.Link_Table = RC.link_Table and RT.link_Table = RR.Link_Table
           where	IsEdited = 1 and RT.Val_Type = 0 and RT.Link_Form = (select top 1 Link_Form from Report_Saved_Forms RSF where Link_Saved_Form = @LSF)
   --        	 and dbo.RO_AccessColByLink(RF.Link_Col) > 0 -- доступ к колонке должен быть
           order by tco, rco, cco
       END
   ELSE
   begin
   IF @cTables=''
   BEGIN
   declare @link_col int, @link_row int

          INSERT #F
           select  RF.Link_Row, RF.Link_Col, dbo.RO_REPORT_FORMULA_REPLACE(Formula, @dBegin, @dEnd, RF.Link_Col, RF.Link_Row, @LSF,'','') as Formula,
    RR.Calc_Orders as rco, RC.Calc_Orders as cco, rt.orders as tco
           from	Report_Formula RF
        	   left join report_coloumns RC on RF.link_col = RC.link_col
        	   left join report_rows RR on RR.link_row = RF.link_row
        	   left join report_tables RT on RT.Link_Table = RC.link_Table and RT.link_Table = RR.Link_Table
           where	IsEdited = 1 and RT.Val_Type = 0 and RT.Link_Form = (select top 1 Link_Form from Report_Saved_Forms RSF where Link_Saved_Form = @LSF)
		   and Formula is NOT NULL
   --        	 and dbo.RO_AccessColByLink(RF.Link_Col) > 0 -- доступ к колонке должен быть
           order by tco, rco, cco
   /*

           select  Formula, RF.Link_Col, RF.Link_Row 
		   into #FFF
           from	Report_Formula RF
        	   left join report_coloumns RC on RF.link_col = RC.link_col
        	   left join report_rows RR on RR.link_row = RF.link_row
        	   left join report_tables RT on RT.Link_Table = RC.link_Table and RT.link_Table = RR.Link_Table
           where	IsEdited = 1 and RT.Val_Type = 0 and RT.Link_Form = (select top 1 Link_Form from Report_Saved_Forms RSF where Link_Saved_Form = @LSF)
		   and Formula is NOT NULL
   --        	 and dbo.RO_AccessColByLink(RF.Link_Col) > 0 -- доступ к колонке должен быть


		   while exists(select top 1 * from #FFF)
		   begin
			   select @Formula = Formula, @Link_Col = Link_Col, @Link_Row = Link_Row from #FFF
   						
			   select @Formula
			   select dbo.RO_REPORT_FORMULA_REPLACE(@Formula, @dBegin, @dEnd, @Link_Col, @Link_Row, @LSF,'','')

			   delete #FFF where @Formula = Formula and @Link_Col = Link_Col and @Link_Row = Link_Row
		   end
   */
   END
   BEGIN
           INSERT #F
           select RF.Link_Row, RF.Link_Col, dbo.RO_REPORT_FORMULA_REPLACE(Formula, @dBegin, @dEnd, RF.Link_Col, RF.Link_Row, @LSF,'','') as Formula, RR.Calc_Orders as rco, RC.Calc_Orders as cco, rt.orders as tco
           from	Report_Formula RF
        	   left join report_coloumns RC on RF.link_col = RC.link_col
        	   left join report_rows RR on RR.link_row = RF.link_row
        	   left join report_tables RT on RT.Link_Table = RC.link_Table and RT.link_Table = RR.Link_Table
           where	IsEdited = 1 and RT.Val_Type = 0 and RT.Link_Form = (select top 1 Link_Form from Report_Saved_Forms RSF where Link_Saved_Form = @LSF)
   --        	 and dbo.RO_AccessColByLink(RF.Link_Col) > 0 -- доступ к колонке должен быть
                    and exists(select * from #iTables IT where RT.link_Table=IT.Link_table) order by tco, rco, cco
   END
   end --else 14форма

   set ansi_warnings OFF
   SET ARITHABORT OFF
   SET ARITHIGNORE OFF

   while exists(select * from #F)
   begin
	   select top 1 @Formula = Formula, @linkCol = Link_Col, @linkRow = Link_Row from #F order by tco, rco, cco
	   if not @Formula is null and LEN(@Formula) > 0
	   begin
	       --print  @Formula
			   execute (@Formula)
	   end
	   delete #F where Link_Col = @linkCol and Link_Row = @linkRow
   end

set ansi_warnings ON
SET ARITHABORT ON
SET ARITHIGNORE ON



drop table #F
IF @cForm not like '0503074%' and @cForm<>'05030mo' AND @cForm not like '0503075%'
begin
IF @cTables=''
BEGIN
        -- удаление старого содержимого динамических таблиц
        delete report_dinamics where Link_SF = @LSF --and dbo.RO_AccessColByLink(Link_Col) > 0 -- имеем доступ к колонке
END
ELSE
BEGIN
        delete report_dinamics where Link_SF = @LSF --and dbo.RO_AccessColByLink(Link_Col) > 0  and EXISTS(select * from REPORT_COLOUMNS RC where RC.Link_col=REPORT_DINAMICS.Link_Col AND exists(select * from #iTables IT where RC.link_Table=IT.Link_table))         -- имеем доступ к колонке
END

	-- линк учреждения должен быть @depLink
	declare @depLink int
	select @depLink = Link_Organization from report_saved_forms where link_saved_form = @LSF
	-- расчет динамических таблиц
	declare @tablename varchar(30)
	exec dbo.X_GET_TABLE_NAME @tablename output
	--set @tablename = '#RT'
	declare @ScriptStr varchar(7000), @ScriptStrF varchar(7000), @LinkTable int, @ColType tinyint, @order int

	IF @cTables=0
	BEGIN
			declare Dinamic_Table cursor  local static
        		for select Link_Table, Script_Str from Report_tables RT left join report_saved_forms RSF on RT.link_form = RSF.link_form where link_saved_form = @LSF and RT.Val_type <> 0 and LEN(RTRIM(RT.Script_Str)) > 0 
	END
	ELSE
	BEGIN 
			declare Dinamic_Table cursor  local static
        		for select Link_Table, Script_Str from Report_tables RT left join report_saved_forms RSF on RT.link_form = RSF.link_form where link_saved_form = @LSF and RT.Val_type <> 0 and LEN(RTRIM(RT.Script_Str)) > 0 AND exists(select * from #iTables IT where RT.link_Table=IT.Link_table)
	END
	open Dinamic_Table
	fetch next from Dinamic_Table
	into @LinkTable, @ScriptStrF
	declare @nt int
	set @nt = 1

	declare @cCalc_Method VARCHAR(50)
   IF @iNotCalc = 1
   begin
	   IF @type_calc=1
		   SET @cCalc_Method='CALC_SMETA='
	   ELSE
		   begin
			   SET @cCalc_Method='CALC_BKS='
			   exec X_GET_OPTION 'REPORT_ORTIONS_SERVER_BKS',0,@cStrVal output 	
			   set @nameServer=ISNULL(@cStrVal,'')

			   exec X_GET_OPTION 'REPORT_ORTIONS_BASE_BKS',0,@cStrVal output 	
			   set @nameBase=ISNULL(@cStrVal,'')

			   exec X_GET_OPTION 'REPORT_ORTIONS_USER_BKS',0,@cStrVal output 	
			   set @nameUser=ISNULL(@cStrVal,'')

			   exec X_GET_OPTION 'REPORT_ORTIONS_PASS_BKS',0,@cStrVal output 	
			   set @userPass=ISNULL(@cStrVal,'')
   	        
		   END
       
	   --что ищем. расчет по смете. CALC_SMETA, CALC_BKS

	   while @@fetch_status = 0
	   begin

		   set @ScriptStrF = UPPER(@ScriptStrF)+CHAR(13)+CHAR(10)
		   if CHARINDEX(@cCalc_Method, @ScriptStrF) > 0 
			   set @ScriptStrF = SUBSTRING(@ScriptStrF, 
										   CHARINDEX(@cCalc_Method, @ScriptStrF)+LEN(@cCalc_Method),
										   CHARINDEX(CHAR(13)+CHAR(10), @ScriptStrF,CHARINDEX(@cCalc_Method, @ScriptStrF)+LEN(@cCalc_Method)) - CHARINDEX(@cCalc_Method, @ScriptStrF)-LEN(@cCalc_Method))
		   else
		    set   @ScriptStrF=''
		   IF  @ScriptStrF=''
		   begin
			   fetch next from Dinamic_Table
			   into @LinkTable, @ScriptStrF
			   CONTINUE -- нет процедуры, только скелет
		   end


		   IF @type_calc=2
			   begin
				   exec XO_CONNECT_ANOTHER_SERVER @nameServer,@nameUser,@userPass
        		   set @ScriptStr = 'declare @LSF int,@dateBeginPeriod datetime, @dateEndPeriod datetime, @PerType tinyint, @PerNomber tinyint, @depLink int set @lsf='+str(@LSF)+' set @depLink = ' + STR(@depLink) + ' set @dateBeginPeriod = ''' + CONVERT(varchar(8), @dBegin, 112) + ''' set @dateEndPeriod = ''' + CONVERT(varchar(8), @dEnd, 112) + ''' set @perType = ' + LTRIM(STR(@perType)) + ' set @perNomber = ' + LTRIM(STR(@perNom)) + ' '  + @ScriptStrF
				   print   @ScriptStr
			     execute(@ScriptStr)
				   CONTINUE
			   end    

		   if CHARINDEX('SQL', @ScriptStrF) > 0 -- если написано на фоксе
		   begin
			   if CHARINDEX('SQL.CALL(', @ScriptStrF) > 0
				   set @ScriptStrF = REPLACE(@ScriptStrF, 'SQL.CALL(', 'exec ')
			   else begin
				   set @tmp = CHARINDEX('(', @ScriptStrF)
				   set @ScriptStrF = RIGHT(@ScriptStrF, LEN(@ScriptStrF) - @tmp)
			   end
			   exec dbo.RO_FORMULA_FUNCTIONS 1, @ScriptStrF output, @SubStr output, ','
			   set @ScriptStr = REPLACE(@SubStr, '"', '')
			   set @ScriptStr = REPLACE(@ScriptStr, '''', '')
			   set @i = 0
			   while LEN(@ScriptStrF) > 0 and @i < 2
			   begin
				   exec dbo.RO_FORMULA_FUNCTIONS 1, @ScriptStrF output, @SubStr output, ','
				   set @i = @i + 1
			   end
			   if LEN(@ScriptStrF) > 0
				   if CHARINDEX(')', @ScriptStrF, LEN(RTRIM(@ScriptStrF))) = LEN(RTRIM(@ScriptStrF))
					   set @ScriptStrF = LEFT(@ScriptStrF, LEN(RTRIM(@ScriptStrF)) - 1)
			   set @i = 0
			   while LEN(@ScriptStrF) > 0 -- параметры
			   begin
				   exec dbo.RO_FORMULA_FUNCTIONS 1, @ScriptStrF output, @SubStr output, ','
				   set @SubStr = REPLACE(@SubStr, 'DATEBEGINPERIOD', '@dateBeginPeriod')
				   set @SubStr = REPLACE(@SubStr, 'DATEENDPERIOD', '@dateEndPeriod')
				   set @SubStr = REPLACE(@SubStr, 'PERTYPE', '@perType')
				   set @SubStr = REPLACE(@SubStr, 'PERNOMBER', '@perNomber')
				   set @SubStr = REPLACE(@SubStr, '"', '''')
				   set @ScriptStr = @ScriptStr + case when @i > 0 then ',' else '' end + ' ' + @SubStr
				   set @i = @i + 1
			   end

		   end

		   else
			   set @ScriptStr = @ScriptStrF

		   select @Str = 'create table ' + RTRIM(@tablename) + LTRIM(STR(@nt)) + ' (CODE ' + case when Col_type = 1 then 'varchar(250)' else 'float' end
		   from report_coloumns RC left join report_tables RT on RT.Link_Code_Col = RC.Link_Col
		   where RT.link_table = @linkTable

		   set @i = 1
		   declare Coloumns cursor local static
			   for select Link_Col, Col_Type, orders from report_coloumns where link_table = @linkTable order by orders
		   open Coloumns
		   fetch next from Coloumns
		   into @linkCol, @colType, @order
		   while @@fetch_status = 0
		   begin
			   set @Str = @Str + ', COL' + LTRIM(STR(@i)) + case when @colType = 1 then ' varchar(8000)' else ' float' end
			   set @i = @i + 1
			   fetch next from Coloumns
			   into @linkCol, @colType, @order
		   end
		   close Coloumns
		   set @Str = @Str + ')'
		   PRINT @ScriptStr
		   set @ScriptStr = 'declare @lsf int ,@dateBeginPeriod datetime, @dateEndPeriod datetime, @PerType tinyint, @PerNomber tinyint, @depLink int set @lsf='+str(@LSF)+' set @depLink = ' + STR(@depLink) + ' set @dateBeginPeriod = ''' + CONVERT(varchar(8), @dBegin, 112) + ''' set @dateEndPeriod = ''' + CONVERT(varchar(8), @dEnd, 112) + ''' set @perType = ' + LTRIM(STR(@perType)) + ' set @perNomber = ' + LTRIM(STR(@perNom)) + ' ' + @Str + ' insert into ' + RTRIM(@tablename) + LTRIM(STR(@nt)) + ' ' + @ScriptStr
		   PRINT @ScriptStr
		   execute(@ScriptStr)
		   set @i = 1
		   open Coloumns
		   fetch next from Coloumns
		   into @linkCol, @colType, @order
		   while @@fetch_status = 0
		   begin
			   delete report_dinamics where Link_SF = @LSF and Link_Col = @linkCol -- удаление старой формы
			   if @linkCol <> (select link_code_col from report_tables where link_table = @linkTable)
				   --and dbo.RO_AccessColByLink(@linkCol) > 0 -- доступ к колонке
			   begin
				   set @Str = 'insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
					   select ' + STR(@LSF) + ', ' + STR(@linkCol) + ', Code, ' + case when @colType = 1 then ' 0,' else ' sum(isnull(Col' + LTRIM(STR(@order)) + ',0)),'  end + case when @colType = 1 then ' isnull(max(col' + LTRIM(STR(@order)) + '), '''')' else '''''' end + 
					   ' from ' + RTRIM(@tablename) + LTRIM(STR(@nt)) + ' group by CODE'
				   execute(@Str)
			   end
			   set @i = @i + 1
			   fetch next from Coloumns
			   into @linkCol, @colType, @order
		   end
		   --set @Str = 'select * from ##RT' + LTRIM(STR(@nt))
		   --execute(@Str)
		   set @Str = 'drop table ' + RTRIM(@tablename) + LTRIM(STR(@nt))
		   execute(@Str)
		   set @nt = @nt + 1
		   deallocate Coloumns
		   fetch next from Dinamic_Table
		   into @LinkTable, @ScriptStrF
	   END
    END   
	end --14форма
end

-- расчет из КС (формулы досчеты)
exec dbo.RO_CALCULATE_DOSCHET @LSF,@cTables

SET @varKSEventStr2 = 'Расчет сохраненной формы'

select @varKSLink_Task = link_task from user_info
select @varKSEventStr = 'Форма: ' + rtrim(code) + ' Период: ' + 
	(case RSF.IsSvod when 1 then 'свод за ' else '' end + 
	 case period_Type when 1 then convert(char(4),year(BEGIN_DATE)) + ' год'
		when 2 then convert(char(1),period_number) + ' квартал'
		when 4 then convert(char(2),period_number) + ' месяц'
	 end) + ' Версия:' +  convert(char(3),version)
from report_saved_forms RSF left join report_forms RF on RSF.link_form = RF.Link_Form where link_saved_form = @LSF
	
exec RO_GENERATEEVENT @varKSEventStr2, @varKSEventStr, @varKSLink_Task, 'REPORT_SAVED_FORMS', @LSF
-- сохраним ссылку на журнал в форме
set @varKSLink_last_event = @@identity 
update dbo.REPORT_saved_forms
SET link_jurnal = @varKSLink_last_event
where link_saved_form = @LSF



GO


GRANT EXECUTE ON dbo.[RI_REPORT_FORMULA_ALL_CALCULATE] TO PUBLIC

GO




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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE  PROCEDURE dbo.X_DOCUMENT_PROV
	@varKSnLink	int,
	@varKSlOperation bit = 0,
	@varKSnLINKDoc int = null,
	@varKSintJurnal int = 0
AS
SET NOCOUNT OFF
BEGIN

	DECLARE @varKSObject int,
		    @varKSTASK varchar(30)

	SELECT @varKSTASK = CODE From dbo.S_OBJECTS WHERE LINK = dbo.GetCurrentTask()
	SELECT @varKSObject = CASE WHEN SO.CODE = 'SHABLON_DOCUMENTS_PROV' THEN 1 ELSE 0 END
	   FROM dbo.G_PROV G INNER JOIN dbo.S_OBJECTS SO ON G.LINK = @varKSnLink AND SO.LINK = G.OBJECT

	DECLARE @varKSoper table (LINK int NOT NULL PRIMARY KEY, ORDERS int NOT NULL, FSORT	VARCHAR (254))

	IF @varKSnLINKDoc is null
	BEGIN
	    IF @varKSlOperation=0
	    BEGIN
			IF @varKSObject = 1 AND @varKSTASK <> 'OUTPUTS'
				INSERT INTO @varKSoper(LINK, ORDERS, FSORT)
				SELECT
					G1.LINK,
					G1.ORDERS,
					G1.NAME_OPER
				FROM dbo.G_PROV1 G1
				WHERE G1.LINK_UP = @varKSnLink 
					AND (@varKSintJurnal = 0
						 OR @varKSintJurnal > 0
							  AND EXISTS(
									SELECT *
									FROM dbo.G_PROV2 G2
										INNER JOIN dbo.XOZ_OPER EO ON G2.ECON_OPER = EO.LINK
										INNER JOIN dbo.XOZ_OPER_JURN XG ON XG.XOZ_LINK = EO.LINK AND XG.JURN_LINK = @varKSintJurnal
									WHERE G2.LINK_UP = G1.LINK)
						 OR @varKSintJurnal = -1
					  AND NOT EXISTS(
					SELECT *
					FROM dbo.G_PROV2 G2
						INNER JOIN dbo.XOZ_OPER EO ON G2.ECON_OPER = EO.LINK
						INNER JOIN dbo.XOZ_OPER_JURN XG ON XG.XOZ_LINK = EO.LINK
					WHERE G2.LINK_UP = G1.LINK))
			ELSE
				INSERT INTO @varKSoper(LINK, ORDERS)
				SELECT
					LINK,
					ORDERS
				FROM dbo.G_PROV1 G1
				WHERE G1.LINK_UP = @varKSnLink
		
			SELECT 	G2.LINK,
				G2.LINK_UP,
				G2.SUMMA,
				G2.QUANTITY,
				convert(bit, G2.STORNO) as STORNO,
				G2.LINK_SELF,
				[DEBIT]=S1.ACCOUNT,
				[CREDIT]=S2.ACCOUNT,
				G2.NAME,
				G2.ORDERS,
				[SECOND] = (CASE WHEN G2.LINK_SELF is null THEN convert(bit,0) ELSE convert(bit,1) END),
				[DEB_CODE] = DS.CODE,
				[CRE_CODE] = KS.CODE,
				[DEB_KSU]  = convert(bit, DS.KSU),
				[CRE_KSU]  = convert(bit, KS.KSU),
				[ap_DEB_DATE] = convert(bit, DS.ap_INDATE),
				[ap_CRE_DATE] = convert(bit, KS.ap_INDATE),
				[DEB_INDATE] = S1.INDATE,
				[CRE_INDATE] = S2.INDATE,
				[LINK_ECON]	= G2.ECON_OPER,
				[CODE_ECON]	= (SELECT CODE from BK_TYPE_ECONOM_OPER WHERE LINK = G2.ECON_OPER),
				[NAME_ECON]	= (SELECT NAME from BK_TYPE_ECONOM_OPER WHERE LINK = G2.ECON_OPER),
				[JO_CODE]	= CONVERT(VARCHAR(100),LTRIM(RTRIM((SELECT JOUR_CODE from BK_TYPE_ECONOM_OPER WHERE LINK = G2.ECON_OPER))) + ' - ' +		
							 LTRIM(RTRIM((SELECT JOUR_NAME from BK_TYPE_ECONOM_OPER WHERE LINK = G2.ECON_OPER))))
			FROM  @varKSoper as G1 INNER JOIN G_PROV2 as G2 ON G2.LINK_UP = G1.LINK
				LEFT JOIN dbo.G_PROV_AP S1 ON S1.LINK_UP = G2.LINK AND S1.DB_KR = 0
				LEFT JOIN dbo.G_PROV_AP S2 ON S2.LINK_UP = G2.LINK AND S2.DB_KR = 1
				LEFT JOIN dbo.S_ACCOUNTS DS ON DS.LINK = S1.ACCOUNT
				LEFT JOIN dbo.S_ACCOUNTS KS ON KS.LINK = S2.ACCOUNT
			ORDER BY G1.ORDERS, G2.ORDERS


		
			SELECT GE.LINK_UP,GE.OBJECT,GE.DB_KR,GE.DIC_LINK,GE.DIC_CODE,GE.DIC_NAME,GE.NAME_AP,GE.OBJ_CODE,GE.TO_G2,GE.ORDERS,GE.LENGTH
			FROM dbo.G_PROV_AP_EDIT_TABLE(@varKSnLink, 0) GE
				INNER JOIN dbo.G_PROV2 G2 ON G2.LINK = GE.LINK_UP
				INNER JOIN @varKSoper O ON O.LINK = G2.LINK_UP
	
		
			SELECT 0 as UPD, 0 as DEL, G1.LINK, G1.OPER, G1.NAME_OPER, G1.ORDERS, G1.LINK as FOR_G2
			FROM dbo.G_PROV1 as G1
			INNER JOIN @varKSoper O ON O.LINK = G1.LINK
			ORDER BY O.FSORT
		
	    END
	    ELSE
	    BEGIN
		SELECT 	G2.LINK,
			G2.LINK_UP,
			G2.SUMMA,
			G2.QUANTITY,
			convert(bit, G2.STORNO) as STORNO,
			G2.LINK_SELF,
			[DEBIT]=S1.ACCOUNT,
			[CREDIT]=S2.ACCOUNT,
			G2.NAME,
			G2.ORDERS,
			[SECOND] = (CASE WHEN G2.LINK_SELF is null THEN convert(bit,0) ELSE convert(bit,1) END),
			[DEB_CODE] = (Select CODE From S_ACCOUNTS Where LINK = S1.ACCOUNT),
			[CRE_CODE] = (Select CODE From S_ACCOUNTS Where LINK = S2.ACCOUNT),
			[DEB_KSU]  = (Select convert(bit, KSU) From S_ACCOUNTS Where LINK = S1.ACCOUNT),
			[CRE_KSU]  = (Select convert(bit, KSU) From S_ACCOUNTS Where LINK = S2.ACCOUNT),
			[ap_DEB_DATE] = (Select convert(bit, ap_INDATE) From S_ACCOUNTS Where LINK = S1.ACCOUNT),
			[ap_CRE_DATE] = (Select convert(bit, ap_INDATE) From S_ACCOUNTS Where LINK = S2.ACCOUNT),
			[DEB_INDATE] = (Select INDATE from G_PROV_AP AP where AP.LINK_UP = G2.LINK and AP.DB_KR=0),
			[CRE_INDATE] = (Select INDATE from G_PROV_AP AP where AP.LINK_UP = G2.LINK and AP.DB_KR=1),
			[LINK_DVZ] = (Select ZPROV from G_PROV_DVZ where LINK_UP = G2.LINK),
			[LINK_ECON]	= G2.ECON_OPER,
			[CODE_ECON]	= (SELECT CODE from BK_TYPE_ECONOM_OPER WHERE LINK = G2.ECON_OPER),
			[NAME_ECON]	= (SELECT NAME from BK_TYPE_ECONOM_OPER WHERE LINK = G2.ECON_OPER),
			[JO_CODE]	= CONVERT(VARCHAR(100),LTRIM(RTRIM((SELECT JOUR_CODE from BK_TYPE_ECONOM_OPER WHERE LINK = G2.ECON_OPER))) + ' - ' +		
						 LTRIM(RTRIM((SELECT JOUR_NAME from BK_TYPE_ECONOM_OPER WHERE LINK = G2.ECON_OPER))))
		FROM dbo.G_PROV2 as G2
			LEFT JOIN dbo.G_PROV_AP S1 ON S1.LINK_UP = G2.LINK AND S1.DB_KR = 0
			LEFT JOIN dbo.G_PROV_AP S2 ON S2.LINK_UP = G2.LINK AND S2.DB_KR = 1
		WHERE G2.LINK_UP=@varKSnLink
		ORDER BY G2.ORDERS

		
		SELECT LINK_UP,DB_KR,OBJECT,DIC_LINK,DIC_CODE,DIC_NAME,NAME_AP,OBJ_CODE,TO_G2,ORDERS,LENGTH
		FROM dbo.G_PROV_AP_EDIT_TABLE(@varKSnLink, 1)

		
		SELECT 0 as UPD, 0 as DEL, G1.LINK, G1.OPER, G1.NAME_OPER, G1.ORDERS, G1.LINK as FOR_G2
		FROM dbo.G_PROV1 as G1
		WHERE  G1.LINK = @varKSnLink
		ORDER BY G1.NAME_OPER
	    END
	END
	ELSE
	BEGIN
		IF @varKSnLINKDoc = (Select Link From dbo.s_objects where code = 'DOCUMENTS_SALARY')
			INSERT INTO @varKSoper(LINK, ORDERS)
			SELECT LINK, ORDERS
			FROM dbo.G_PROV1 G1
			WHERE G1.LINK_UP = @varKSnLink 
			AND (@varKSintJurnal = 0
			 OR @varKSintJurnal > 0
			  AND EXISTS(
				SELECT *
				FROM dbo.G_PROV2 G2
					INNER JOIN dbo.XOZ_OPER EO ON G2.ECON_OPER = EO.LINK
					INNER JOIN dbo.XOZ_OPER_JURN XG ON XG.XOZ_LINK = EO.LINK AND XG.JURN_LINK = @varKSintJurnal
				WHERE G2.LINK_UP = G1.LINK)
			 OR @varKSintJurnal = -1
			  AND NOT EXISTS(
				SELECT *
				FROM dbo.G_PROV2 G2
					INNER JOIN dbo.XOZ_OPER EO ON G2.ECON_OPER = EO.LINK
					INNER JOIN dbo.XOZ_OPER_JURN XG ON XG.XOZ_LINK = EO.LINK
				WHERE G2.LINK_UP = G1.LINK))
		ELSE
		BEGIN
			INSERT INTO @varKSoper(LINK, ORDERS, FSORT)
			SELECT
				DT.LINK_OPER,
				DT.ORDERS,
				CASE
					WHEN @varKSObject = 1 THEN G1.NAME_OPER
					ELSE RIGHT (REPLACE (SPACE (30), SPACE (1), '0') + CONVERT (VARCHAR (30), G1.ORDERS), 30)
				END
			FROM dbo.DocTypOper() DT
			INNER JOIN dbo.G_PROV1 G1 ON (G1.LINK = DT.LINK_OPER)
			WHERE DT.DOC_TYPE = @varKSnLINKDoc
			AND (@varKSintJurnal = 0
			 OR @varKSintJurnal > 0
			  AND EXISTS(
				SELECT *
				FROM dbo.G_PROV2 G2
					INNER JOIN dbo.XOZ_OPER EO ON G2.ECON_OPER = EO.LINK
					INNER JOIN dbo.XOZ_OPER_JURN XG ON XG.XOZ_LINK = EO.LINK AND XG.JURN_LINK = @varKSintJurnal
				WHERE G2.LINK_UP = DT.LINK_OPER)
			 OR @varKSintJurnal = -1
			  AND NOT EXISTS(
				SELECT *
				FROM dbo.G_PROV2 G2
					INNER JOIN dbo.XOZ_OPER EO ON G2.ECON_OPER = EO.LINK
					INNER JOIN dbo.XOZ_OPER_JURN XG ON XG.XOZ_LINK = EO.LINK
				WHERE G2.LINK_UP = DT.LINK_OPER))
	
			IF @@ROWCOUNT = 0 
				INSERT INTO @varKSoper(LINK, ORDERS, FSORT)
				SELECT
					G1.LINK,
					G1.ORDERS,
					CASE
						WHEN @varKSObject = 1 THEN G1.NAME_OPER
						ELSE RIGHT (REPLACE (SPACE (30), SPACE (1), '0') + CONVERT (VARCHAR (30), G1.ORDERS), 30)
					END
				FROM dbo.G_PROV1 G1
				WHERE G1.LINK_UP = @varKSnLink 
				AND (@varKSintJurnal = 0
				 OR @varKSintJurnal > 0
				  AND EXISTS(
					SELECT *
					FROM dbo.G_PROV2 G2
						INNER JOIN dbo.XOZ_OPER EO ON G2.ECON_OPER = EO.LINK
						INNER JOIN dbo.XOZ_OPER_JURN XG ON XG.XOZ_LINK = EO.LINK AND XG.JURN_LINK = @varKSintJurnal
					WHERE G2.LINK_UP = G1.LINK)
				 OR @varKSintJurnal = -1
				  AND NOT EXISTS(
					SELECT *
					FROM dbo.G_PROV2 G2
						INNER JOIN dbo.XOZ_OPER EO ON G2.ECON_OPER = EO.LINK
						INNER JOIN dbo.XOZ_OPER_JURN XG ON XG.XOZ_LINK = EO.LINK
					WHERE G2.LINK_UP = G1.LINK))
		END
		SELECT 	G2.LINK,
			G2.LINK_UP,
			G2.SUMMA,
			G2.QUANTITY,
			convert(bit, G2.STORNO) as STORNO,
			G2.LINK_SELF,
			[DEBIT]=S1.ACCOUNT,
			[CREDIT]=S2.ACCOUNT,
			G2.NAME,
			G2.ORDERS,
			[SECOND] = (CASE WHEN G2.LINK_SELF is null THEN convert(bit,0) ELSE convert(bit,1) END),
			[DEB_CODE] = (SELECT DS.CODE FROM dbo.S_ACCOUNTS DS Where LINK = S1.ACCOUNT),
			[CRE_CODE] = (SELECT KS.CODE FROM dbo.S_ACCOUNTS KS Where LINK = S2.ACCOUNT),
			[DEB_CODE] = (Select CODE From S_ACCOUNTS Where LINK = S1.ACCOUNT),
			[CRE_CODE] = (Select CODE From S_ACCOUNTS Where LINK = S2.ACCOUNT),
			[ap_DEB_DATE] = (Select convert(bit, ap_INDATE) From S_ACCOUNTS Where LINK = S1.ACCOUNT),
			[ap_CRE_DATE] = (Select convert(bit, ap_INDATE) From S_ACCOUNTS Where LINK = S2.ACCOUNT),
			[DEB_INDATE] = (Select INDATE from G_PROV_AP AP where AP.LINK_UP = G2.LINK and AP.DB_KR=0),
			[CRE_INDATE] = (Select INDATE from G_PROV_AP AP where AP.LINK_UP = G2.LINK and AP.DB_KR=1),
			[DEB_KSU]  = (Select convert(bit, KSU) From S_ACCOUNTS Where LINK = S1.ACCOUNT),
			[CRE_KSU]  = (Select convert(bit, KSU) From S_ACCOUNTS Where LINK = S2.ACCOUNT),
			[LINK_DVZ] = (Select ZPROV from G_PROV_DVZ where LINK_UP = G2.LINK),
			[LINK_ECON]	= G2.ECON_OPER,
			[CODE_ECON]	= (SELECT CODE from BK_TYPE_ECONOM_OPER WHERE LINK = G2.ECON_OPER),
			[NAME_ECON]	= (SELECT NAME from BK_TYPE_ECONOM_OPER WHERE LINK = G2.ECON_OPER),
			[JO_CODE]	= CONVERT(VARCHAR(100),LTRIM(RTRIM((SELECT JOUR_CODE from BK_TYPE_ECONOM_OPER WHERE LINK = G2.ECON_OPER))) + ' - ' +		
						 LTRIM(RTRIM((SELECT JOUR_NAME from BK_TYPE_ECONOM_OPER WHERE LINK = G2.ECON_OPER))))

		FROM  @varKSoper as G1
			INNER JOIN dbo.G_PROV2 as G2 ON G2.LINK_UP = G1.LINK
			LEFT JOIN dbo.G_PROV_AP as S1 ON S1.LINK_UP = G2.LINK AND S1.DB_KR = 0
			LEFT JOIN dbo.G_PROV_AP as S2 ON S2.LINK_UP = G2.LINK AND S2.DB_KR = 1
		ORDER BY G1.ORDERS, G2.ORDERS

		
		SELECT GE.LINK_UP,GE.OBJECT,GE.DB_KR,GE.DIC_LINK,GE.DIC_CODE,GE.DIC_NAME,GE.NAME_AP,GE.OBJ_CODE,GE.TO_G2,GE.ORDERS,GE.LENGTH
		FROM dbo.G_PROV_AP_EDIT_TABLE(@varKSnLink, 0) GE
			INNER JOIN dbo.G_PROV2 G2 ON G2.LINK = GE.LINK_UP
			INNER JOIN @varKSoper O ON O.LINK = G2.LINK_UP

		
		SELECT 0 as UPD, 0 as DEL, G1.LINK, G1.OPER, G1.NAME_OPER, G1.ORDERS, G1.LINK as FOR_G2
		FROM dbo.G_PROV1 as G1 INNER JOIN @varKSoper O ON O.LINK = G1.LINK
		ORDER BY FSORT
		
	END
	
END

GO


GRANT EXECUTE ON dbo.[X_DOCUMENT_PROV] TO PUBLIC

GO


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


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

GO


/*
c Кейсистемс (Keysystems), 2005
*/
CREATE   PROCEDURE dbo.RSD_REPORT_FORMULA_AVPAT3_P22_VALUE14
	@cres char(20) output, @varcStr varchar(250), @vardBegin datetime = '20050101', @vardEnd datetime = '20051231', @variCol int, @variRow int, @variLSF int
AS
	declare @res float,@cStr varchar(250), @q tinyint, @lnDiv int, @linkCol int, @linkRow int, @linkTable int

	set @res = 0
	set @q = DATEPART (QUARTER, @vardEnd)
	set @cStr = case @q
				when 1 then '020~030~040~050'
				when 2 then '020~030~040~050~060~070~080'
				when 3 then '020~030~040~050~060~070~080~090~100~110'
				when 4 then '020~030~040~050~060~070~080~090~100~110~120~130~140'
			end
	set @lnDiv = case @q
				when 1 then 4
				when 2 then 7
				when 3 then 10
				when 4 then 13
			end

	IF @varcStr = 'КОНЕЦ_ОСТАТ'
	BEGIN
		SET @cStr = RIGHT(@cStr, 3)
		SET @lnDiv = 1
	END

	select
		@linkTable = RT.Link_Table
	from dbo.report_rows A 
	left join dbo.report_tables C on c.Link_Table = a.Link_Table
	LEFT JOIN dbo.REPORT_FORMS RF ON (RF.LINK_FORM = C.LINK_FORM)
	left join dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RF.LINK_FORM)
	where 
		A.Link_Row = @variRow
		AND (
				(
				RF.CODE = 'AV_IMU' AND RF.[START_DATE] = '20140101' 
				OR RF.CODE = 'ND_IMU' AND RF.[START_DATE] = '20130101'
				)
				AND RT.orders = 2
			OR RT.orders = 1
			)

	select @linkRow = Link_Row from (select top 1 Link_Row from report_rows where Link_Table = @linkTable) A
	if @varcStr = 'ВСЕГО' OR @varcStr = 'КОНЕЦ_ОСТАТ'
		select @linkCol = link_Col from report_coloumns A where orders = 3 and link_table = @linkTable
	else
		select @linkCol = link_Col from report_coloumns A where orders = 4 and link_table = @linkTable

	exec dbo.RI_Report_Formula_itog @res output, @cStr, @vardBegin, @vardEnd, @linkCol, @linkRow, @variLSF
	set @cres = str(@res/@lnDiv)
	
-- SELECT @cStr, @res, @lnDiv, @cres
	
GO


GRANT EXECUTE ON dbo.[RSD_REPORT_FORMULA_AVPAT3_P22_VALUE14] 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.[RO_EXPORT_REPORT_XML]') AND 
                 OBJECTPROPERTY(ID, N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_EXPORT_REPORT_XML]
END
GO

/*  
  
 c Кейсистемс (Keysystems), 2010  
 Экспорт отчетов в формате xml  
  
 create table #Files ([TXT]             VARCHAR(8000),   
                        [ORDERS]          INT IDENTITY(1,1),   
                        [NAMEFILE]        VARCHAR(100),   
                        [NAMEFILE_ARH]    VARCHAR(100),   
                        [OrderFile]       INT DEFAULT(0),  
                        [LINK_SAVED_FORM] INT)  
 create table #Reports (LSF int)  
  
*/  
CREATE PROCEDURE [dbo].[RO_EXPORT_REPORT_XML]  
 @varKSiLSF int  
AS  
 SET NOCOUNT ON  
 -- поиск шаблона экспорта  
 declare @CodeForm varchar(30), @StartDate datetime, @LinkE int, @NameDate varchar(30), @CodeBudg varchar(30), @CodeOrg varchar(30), @LF int, @BeginDate datetime, @LinkOrg int, @LinkBudg int, @ExecStr nvarchar(4000), @PeriodType TINYINT, @orderCol VARCHAR
(100), @value VARCHAR(8000)  
 select  @PeriodType = RSF.Period_Type, @BeginDate = RSF.begin_date, @LinkOrg = RSF.Link_Organization, @LinkBudg = RSF.Link_Type_Svod, @LF = RSF.Link_Form, @CodeForm = RF.Code, @StartDate = RF.Start_date from report_forms RF join report_saved_forms RSF on
 RF.Link_Form = RSF.Link_Form and RSF.Link_Saved_Form = @varKSiLSF  
 select @LinkE = Link from REPORT_EXPORT_XML_Forms where Code_Form =  @CodeForm and Start_Date = @StartDate  
  
 if @LinkE is NULL  
  select @LinkE = Link from REPORT_EXPORT_XML_Forms where Code_Form =  @CodeForm  
  
 if @LinkE is NULL  
  return 1  
      
     IF @CodeForm=RTRIM(LTRIM('0503738G')) AND @LinkE IS NOT NULL  
    BEGIN  
       EXEC dbo.[RA_EXPORT_FORM_FNS_738] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm=RTRIM(LTRIM('0503725G')) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_725] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm=RTRIM(LTRIM('0503710G')) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_710] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm=RTRIM(LTRIM('0503779G')) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_779] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm IN (RTRIM(LTRIM('0503769G_D')),RTRIM(LTRIM('0503769G_K'))) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_769] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm=RTRIM(LTRIM('0503730G_BU')) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_730] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm=RTRIM(LTRIM('0503830G')) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_830] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm=RTRIM(LTRIM('0503721G')) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_721] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm=RTRIM(LTRIM('0503737G')) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_737] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm=RTRIM(LTRIM('0503760G')) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_760] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm=RTRIM(LTRIM('0503130G')) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_130] @varKSiLSF,NULL,1
       RETURN   
    END
--declare #t_LSF table (LSF int)  
 create table #t_LSF (LSF int, atr varchar(1000))  
 create table #t_Exec (txt varchar(8000))  
  
 insert #t_LSF (LSF, atr)  
 select distinct LSF, RSF.atr_code  
 from #Reports R join report_saved_forms RSF on R.LSF = RSF.Link_Saved_Form  
 where RSF.Link_Form = @LF and RSF.begin_date = @BeginDate and RSF.Link_Organization = @LinkOrg and isnull(RSF.Link_Type_Svod,0) = isnull(@LinkBudg,0)  
 union  
 select distinct link, RSF.atr_code from dbo.buffer B join report_saved_forms RSF on B.Link = RSF.Link_Saved_Form and sid = suser_sid() and ID = 'REPORT_ATR_EXPORT'  
 where RSF.Link_Form = @LF and RSF.begin_date = @BeginDate and RSF.Link_Organization = @LinkOrg and isnull(RSF.Link_Type_Svod,0) = isnull(@LinkBudg,0)  
  
   DELETE R   
 from #Reports R join report_saved_forms RSF on R.LSF = RSF.Link_Saved_Form  
 where RSF.Link_Form = @LF and RSF.begin_date = @BeginDate and RSF.Link_Organization = @LinkOrg and isnull(RSF.Link_Type_Svod,0) = isnull(@LinkBudg,0)  
   
   DELETE B  
   from dbo.buffer B join report_saved_forms RSF on B.Link = RSF.Link_Saved_Form and sid = suser_sid() and ID = 'REPORT_ATR_EXPORT'  
 where RSF.Link_Form = @LF and RSF.begin_date = @BeginDate and RSF.Link_Organization = @LinkOrg and isnull(RSF.Link_Type_Svod,0) = isnull(@LinkBudg,0)  
  
  -- готовим данные  
------------------------------------------------------------------------------------------------------  
 declare @i int  
 declare @t_Header table (Code varchar(100), Value varchar(8000), LSF int default 0)  
  
 if @PeriodType = 1  
 begin  
  insert @t_Header (Code, Value)  
  select '@DATE@', convert(varchar(10), dbo.DateBeginOfYear(@beginDate), 120)   
  
  set @NameDate = LTRIM(RTRIM(STR(YEAR(@beginDate)))) + ' год'   
 end  
 else begin  
  insert @t_Header (Code, Value)  
  select '@DATE@', convert(varchar(10), dbo.DateBeginOfMonth(@beginDate), 120)   
  
  set @NameDate = RTRIM(dbo.DateMonthName(MONTH(@begindate))) + ' ' + LTRIM(RTRIM(STR(YEAR(@beginDate)))) + ' года'   
 end  
  
 insert @t_Header (Code, Value)  
 select '@NAME_DATE@', @NameDate  
  
 set @codeBudg = isnull((select RTRIM(isnull(B.OutCode,'')) from  dbo.kl_budg_type B where  B.link = @LinkBudg ),'')  
  
 insert @t_Header (Code, Value)  
 select '@CODE_BUDG@',  @CodeBudg  
  
 insert @t_Header (Code, Value)  
 select '@NAME_BUDG@',  isnull((select dbo.[RA_XML_MASK] (RTRIM(isnull(B.Name, ''))) from dbo.kl_budg_type B where B.link = @LinkBudg), '')   
  
 select @CodeOrg = RTRIM(isnull(D.budg,'')) from dbo.departments D where D.link = @LinkOrg  
  
 insert @t_Header (Code, Value)  
 select '@CODE_ORG@',  @CodeOrg  
  
 insert @t_Header (Code, Value)  
 select '@NAME_ORG@',  dbo.[RA_XML_MASK](RTRIM(isnull(D.Name,'')))  from dbo.departments D where D.link = @LinkOrg  
  
 insert @t_Header (Code, Value, LSF)  
 select '@' + LTRIM(RTRIM(code))+ '@',  RTRIM(dbo.RN_GET_ATR_VALUE(Link_Saved_Form , Code)), Link_Saved_Form   
 from dbo.N_REPORT_ATRIBUTS_VIEW V  
   left join report_saved_forms RSF on charindex(RTRIM(V.Code), RSF.atr_code) > 0  
   join #t_LSF L on L.LSF = RSF.Link_Saved_Form  
  
  
   
 --declare #t_Data table (OrderTable tinyint, CodeRow varchar(50), OrderCol char(4), Value varchar(8000), LSF int)  
 create table #t_Data (LSF int, OrderTable tinyint, CodeRow varchar(50), OrderCol char(4), Value varchar(8000))  
 Create index #IX_DATA on  #t_Data (LSF, OrderTable, CodeRow)  
 -- пока только динамика  
 insert #t_Data (OrderTable, CodeRow, OrderCol, Value, LSF)  
 select RT.orders, RD.Code_Row, '@' + LTRIM(STR(RC.orders)) + '@', case when RC.Col_Type = 0 then LTRIM(STR(RD.float_val, 20, 4)) else dbo.[RA_XML_MASK] (RTRIM(RD.Str_Val)) end, RSF.Link_Saved_form  
 from dbo.report_saved_forms RSF   
  join #t_LSF L on RSF.Link_Saved_Form = L.LSF  
  join dbo.report_tables RT on RSF.Link_Form = RT.Link_Form  
  join dbo.report_coloumns RC on RT.Link_Table = RC.Link_Table  
  join dbo.report_dinamics_all RD on RD.Link_SF = RSF.Link_Saved_Form and RC.Link_Col = RD.Link_Col  
 where RT.Val_Type = 1 --and exists(select top 1 * from dbo.report_dinamics_all RD1 where RD1.Link_SF = RD.Link_SF and RD1.Code_Row = RD.Code_Row and RD1.float_val <> 0)   
   and not exists(select * from dbo.report_export_xml_data D where D.link_up = @LinkE and (RT.orders = D.OT) and (RC.orders = D.OC or D.OC = 0))  
  
 insert #t_Data (OrderTable, CodeRow, OrderCol, Value, LSF)  
 select RT.orders, RR.Code, '@' + LTRIM(STR(RC.orders)) + '@', case when RC.Col_Type = 0 then LTRIM(STR(isnull(RS.summa,0), 20, 4)) else case when RC.IsEdited = 1 then dbo.[RA_XML_MASK] (RTRIM(isnull(RST.Str_Val,''))) else dbo.[RA_XML_MASK] (RTRIM(isnull(
RF.Formula,''))) end end, RSF.Link_Saved_form  
 from dbo.report_saved_forms RSF   
  join #t_LSF L on RSF.Link_Saved_Form = L.LSF  
  join dbo.report_tables RT on RSF.Link_Form = RT.Link_Form  
  join dbo.report_coloumns RC on RT.Link_Table = RC.Link_Table  
  join i_report_rows RR on RR.Link_Table = RT.Link_Table  
  left join dbo.report_summa_all RS on RS.Link_Saved_Form = RSF.Link_Saved_Form and RC.Link_Col = RS.Link_Col and RR.Link_Row = RS.Link_Row  
  left join dbo.report_string_all RST on RST.Link_Saved_Form = RSF.Link_Saved_Form and RC.Link_Col = RST.Link_Col and RR.Link_Row = RST.Link_Row  
  left join dbo.report_formula RF on RC.Link_Col = RF.Link_Col and RR.Link_Row = RF.Link_Row  
 where RT.Val_Type = 0 and exists(select top 1 * from dbo.report_summa S1 where S1.Link_Saved_Form = RSF.Link_Saved_Form and S1.Link_Row = RR.Link_Row and S1.summa <> 0)   
  and not exists(select * from dbo.report_export_xml_data D where D.link_up = @LinkE and RT.orders = D.OT and (RC.orders = D.OC or D.OC = 0))  
  
 insert #t_Exec (txt)  
 select 'insert #t_Data (OrderTable, CodeRow, OrderCol, Value, LSF)  
 select ' + isnull(T.COND, 'RT.orders') + ', RD.Code_Row, ''@'' + LTRIM(STR(RC.orders)) + ''@'', case when RC.Col_Type = 0 then LTRIM(STR(RD.float_val, 20, 4)) else dbo.[RA_XML_MASK] (' + isnull(C.COND, 'RD.Str_Val') +  ') end, RSF.Link_Saved_form  
 from dbo.report_saved_forms RSF   
  join #t_LSF L on RSF.Link_Saved_Form = L.LSF  
  join dbo.report_tables RT on RSF.Link_Form = RT.Link_Form and RT.orders = ' + case when LTRIM(STR(COALESCE(C.OT, T.OT, 0))) = '0' then 'RT.orders' else LTRIM(STR(COALESCE(C.OT, T.OT, 0))) end  + '  
  join dbo.report_coloumns RC on RT.Link_Table = RC.Link_Table and (RC.orders = ' + LTRIM(STR(isnull(C.OC, 0))) + ' or 0 = ' + LTRIM(STR(isnull(C.OC,0))) + ')  
  join dbo.report_dinamics_all RD on RD.Link_SF = RSF.Link_Saved_Form and RC.Link_Col = RD.Link_Col '  
 from (select * from dbo.report_export_xml_data D where D.link_up = @LinkE and OC <> 0) C  
  full join (select * from dbo.report_export_xml_data D where D.link_up = @LinkE and OC = 0) T on C.OT = T.OT  
 where isnull(C.OT, T.OT) in (select orders from dbo.report_tables where Link_Form = @LF and Val_Type = 1)  
  
   
 insert #t_Exec (txt)  
 select ' insert #t_Data (OrderTable, CodeRow, OrderCol, Value, LSF)  
 select ' + isnull(T.COND, 'RT.orders') + ', RR.Code, ''@'' + LTRIM(STR(RC.orders)) + ''@'', case when RC.Col_Type = 0 then LTRIM(STR(isnull(RS.summa,0), 20, 4)) else case when RC.IsEdited = 1 then dbo.[RA_XML_MASK] (RTRIM(isnull(RST.Str_Val,''''))) else 
dbo.[RA_XML_MASK] (' + isnull(C.COND,'RTRIM(isnull(RF.Formula,''''))') + ') end end, RSF.Link_Saved_form  
 from dbo.report_saved_forms RSF   
  join #t_LSF L on RSF.Link_Saved_Form = L.LSF  
  join dbo.report_tables RT on RSF.Link_Form = RT.Link_Form and RT.orders = ' + case when LTRIM(STR(COALESCE(C.OT, T.OT, 0))) = '0' then 'RT.orders' else LTRIM(STR(COALESCE(C.OT, T.OT, 0))) end  + '  
  join dbo.report_coloumns RC on RT.Link_Table = RC.Link_Table and (RC.orders = ' + LTRIM(STR(isnull(C.OC, 0))) + ' or 0 = ' + LTRIM(STR(isnull(C.OC,0))) + ')  
  join i_report_rows RR on RR.Link_Table = RT.Link_Table  
  left join dbo.report_summa_all RS on RS.Link_Saved_Form = RSF.Link_Saved_Form and RC.Link_Col = RS.Link_Col and RR.Link_Row = RS.Link_Row  
  left join dbo.report_string_all RST on RST.Link_Saved_Form = RSF.Link_Saved_Form and RC.Link_Col = RST.Link_Col and RR.Link_Row = RST.Link_Row  
  left join dbo.report_formula RF on RC.Link_Col = RF.Link_Col and RR.Link_Row = RF.Link_Row  
 where exists(select top 1 * from dbo.report_summa S1 where S1.Link_Saved_Form = RSF.Link_Saved_Form and S1.Link_Row = RR.Link_Row and S1.summa <> 0)'  
 from (select * from dbo.report_export_xml_data D where D.link_up = @LinkE and OC <> 0) C  
  full join (select * from dbo.report_export_xml_data D where D.link_up = @LinkE and OC = 0) T on C.OT = T.OT  
 where isnull(C.OT, T.OT)  in (select orders from dbo.report_tables where Link_Form = @LF and Val_Type = 0)  
  
 insert #t_Exec (txt)  
 select top 1 ' insert #t_Data (OrderTable, CodeRow, OrderCol, Value, LSF)  
 select ' + isnull(T.COND, 'RT.orders') + ', RR.Code, ''@'' + LTRIM(STR(RC.orders)) + ''@'', case when RC.Col_Type = 0 then LTRIM(STR(isnull(RS.summa,0), 20, 4)) else case when RC.IsEdited = 1 then dbo.[RA_XML_MASK] (RTRIM(isnull(RST.Str_Val,''''))) else 
dbo.[RA_XML_MASK] (RTRIM(isnull(RF.Formula,''''))) end end, RSF.Link_Saved_form  
 from dbo.report_saved_forms RSF   
  join #t_LSF L on RSF.Link_Saved_Form = L.LSF  
  join dbo.report_tables RT on RSF.Link_Form = RT.Link_Form and RT.orders = ' + LTRIM(STR(COALESCE(T.OT, 0))) + '  
  join dbo.report_coloumns RC on RT.Link_Table = RC.Link_Table   
  join i_report_rows RR on RR.Link_Table = RT.Link_Table  
  left join dbo.report_summa_all RS on RS.Link_Saved_Form = RSF.Link_Saved_Form and RC.Link_Col = RS.Link_Col and RR.Link_Row = RS.Link_Row  
  left join dbo.report_string_all RST on RST.Link_Saved_Form = RSF.Link_Saved_Form and RC.Link_Col = RST.Link_Col and RR.Link_Row = RST.Link_Row  
  left join dbo.report_formula RF on RC.Link_Col = RF.Link_Col and RR.Link_Row = RF.Link_Row  
 where exists(select top 1 * from dbo.report_summa S1 where S1.Link_Saved_Form = RSF.Link_Saved_Form and S1.Link_Row = RR.Link_Row and S1.summa <> 0)  
  and not exists(select top 1 * from #t_Data D where D.OrderTable = '+ isnull(T.COND, 'RT.orders') + ' and D.CodeRow = RR.Code and D.OrderCol = ''@'' + LTRIM(STR(RC.orders)) + ''@'' and D.LSF = RSF.Link_Saved_form)'  
 from (select * from dbo.report_export_xml_data D where D.link_up = @LinkE and OC = 0) T   
 where  T.OT  in (select orders from dbo.report_tables where Link_Form = @LF and Val_Type = 0)  
  
  
 insert #t_Exec (txt)  
 select top 1 'insert #t_Data (OrderTable, CodeRow, OrderCol, Value, LSF)  
 select ' + isnull(T.COND, 'RT.orders') + ', RD.Code_Row, ''@'' + LTRIM(STR(RC.orders)) + ''@'', case when RC.Col_Type = 0 then LTRIM(STR(RD.float_val, 20, 4)) else dbo.[RA_XML_MASK] (RD.Str_Val) end, RSF.Link_Saved_form  
 from dbo.report_saved_forms RSF   
  join #t_LSF L on RSF.Link_Saved_Form = L.LSF  
  join dbo.report_tables RT on RSF.Link_Form = RT.Link_Form and RT.orders = ' + LTRIM(STR(COALESCE(T.OT, 0)))  + '  
  join dbo.report_coloumns RC on RT.Link_Table = RC.Link_Table   
  join dbo.report_dinamics_all RD on RD.Link_SF = RSF.Link_Saved_Form and RC.Link_Col = RD.Link_Col   
 where not exists(select top 1 * from #t_Data D where D.OrderTable = '+ isnull(T.COND, 'RT.orders') + ' and D.CodeRow = RD.Code_Row and D.OrderCol = ''@'' + LTRIM(STR(RC.orders)) + ''@'' and D.LSF = RSF.Link_Saved_form)'  
 from (select * from dbo.report_export_xml_data D where D.link_up = @LinkE and OC = 0) T   
 where  T.OT  in (select orders from dbo.report_tables where Link_Form = @LF and Val_Type = 1)  
  
  
 exec ssp_execresultset 'select txt from #t_Exec'--, @varKSDebug = 1  
  
--select txt from #t_Exec     
--select * from #t_Data order by OrderTable, CodeRow, OrderCol  
--return  
 -- формируем текст  
------------------------------------------------------------------------------------------------------------  
 --declare @t_Txt table (link int, txt varchar(8000), orders varchar(1000), orderTable tinyint default 0, CodeRow varchar(50), LSF int default (0))  
 create table #t_Txt (link int, txt varchar(8000), orders varchar(1000), orderTable tinyint default 0, CodeRow varchar(50), LSF int default (0))  
 create table #t_Txt1 (link int, txt varchar(8000), orders varchar(1000), orderTable tinyint default 0, CodeRow varchar(50), LSF int default (0))  
 Create index #IX_TXT on  #t_Txt (link)  
  
   
 insert #t_Txt (link, txt, orders, OrderTable, CodeRow, LSF)  
 select link, txt , RIGHT('0000' + LTRIM(RTRIM(STR(orders))) ,5) + '00000000000000000000000000000000000000000000000000000000000' AS orders , X.OrderTable, '' as CodeRow, 0  
 from dbo.report_export_xml X     
   where link_up = @LinkE and Link_Self = 0 and Type = 0 and X.OrderTable= 0  
 union  
 select -link, txt_end, RIGHT('0000' + LTRIM(RTRIM(STR(orders))) ,5)  + '00000000000000000000000000000000000000000000000000000000005', X.OrderTable,  '', 0  
 from dbo.report_export_xml X   
 where link_up = @LinkE and Link_Self = 0  and txt_end <> '' and X.OrderTable= 0  
 union   
 select link, txt , RIGHT('0000' + LTRIM(RTRIM(STR(orders))) ,5) + RIGHT('0000000000000000000000000000000000000000000000000000000000' + RIGHT('0000000' + LTRIM(RTRIM(STR(D.LSF))),7) + isnull(CodeRow,''), 57)  + '0' AS orders , X.OrderTable, isnull(CodeRow
, ''), D.LSF  
 from dbo.report_export_xml X   join (select distinct LSF, OrderTable, CodeRow from #t_Data) D on X.orderTable = D.OrderTable   
   where link_up = @LinkE and Link_Self = 0 and Type = 0  
 union  
 select -link, txt_end, RIGHT('0000' + LTRIM(RTRIM(STR(orders))) ,5)  + RIGHT('0000000000000000000000000000000000000000000000000000000000'  + RIGHT('0000000' + LTRIM(RTRIM(STR(D.LSF))),7) +  isnull(CodeRow,''), 57) + '5', X.OrderTable, isnull(CodeRow, '')
, D.LSF  
 from dbo.report_export_xml X   
  join (select distinct LSF, OrderTable, CodeRow from #t_Data) D on X.orderTable = D.OrderTable   
 where link_up = @LinkE and Link_Self = 0  and txt_end <> ''  
  
 while @@rowcount > 0   
 begin  
  -- сначала заполняем атрибуты  
  set @i = 1  
  
  update T   
  set txt = T.txt + ' ' + X.txt + '="' + X.Field + '"'    
  from dbo.report_export_xml X join #t_Txt T on X.Link_Self = T.Link  
  where X.link_up = @LinkE and Type = 1 and LEN(T.orders) + 5 >= (select max(LEN(orders)) from  #t_Txt T )  
    and X.orders = @i  
  
  while @@rowcount > 0  
  begin  
   set @i = @i + 1  
  
   update T   
   set txt = T.txt + ' ' + X.txt + '="' + X.Field + '"'    
   from dbo.report_export_xml X join #t_Txt T on X.Link_Self = T.Link  
   where X.link_up = @LinkE and Type = 1 and LEN(T.orders) + 5 >= (select max(LEN(orders)) from  #t_Txt T )  
     and X.orders = @i  
  end  
  
  truncate table #t_Txt1  
  
  -- теперь потомки, умноженные на строки    
  insert #t_Txt1 (link, txt, orders, OrderTable, CodeRow, LSF)  
  select X.link, X.txt  , T.orders + '.' + RIGHT('0000' + LTRIM(RTRIM(STR(X.orders))),5)  + '00000000000000000000000000000000000000000000000000000000000'  AS orders, 0, '', 0  
  from dbo.report_export_xml X join #t_Txt T on X.Link_Self = T.Link  
   where link_up = @LinkE and Type = 0 and X.orderTable = 0  
    and not exists(select top 1 * from  #t_Txt T where X.link = T.link)  
  union  
  select -X.link, X.txt_end, T.orders + '.' + RIGHT('0000' + LTRIM(RTRIM(STR(X.orders))),5) + '00000000000000000000000000000000000000000000000000000000005', 0, '', 0  from dbo.report_export_xml X join #t_Txt T on X.Link_Self = T.Link  
   where link_up = @LinkE and Type = 0 and txt_end <> '' and X.orderTable = 0   
    and not exists(select top 1 * from  #t_Txt T where X.link = T.link)  
  
  insert #t_Txt1 (link, txt, orders, OrderTable, CodeRow, LSF)  
  select X.link, X.txt  , T.orders + '.' + RIGHT('0000' + LTRIM(RTRIM(STR(X.orders))),5)  + RIGHT('0000000000000000000000000000000000000000000000000000000000'  + RIGHT('0000000' + LTRIM(RTRIM(STR(D.LSF))),7) +  isnull(D.CodeRow,''), 57) + '0'  AS orders, 
X.OrderTable, isnull(D.CodeRow,''), isnull(D.LSF,0)  
  from dbo.report_export_xml X join #t_Txt T on X.Link_Self = T.Link   
   join (select distinct LSF, OrderTable, CodeRow from #t_Data) D on X.OrderTable = D.OrderTable and ((D.CodeRow = T.CodeRow and D.LSF = T.LSF) or T.LSF = 0)  
   where link_up = @LinkE and Type = 0   
    and not exists(select top 1 * from  #t_Txt T where X.link = T.link)  
  
  insert #t_Txt1 (link, txt, orders, OrderTable, CodeRow, LSF)  
  select -X.link, X.txt_end, T.orders + '.' + RIGHT('0000' + LTRIM(RTRIM(STR(X.orders))),5) + RIGHT('0000000000000000000000000000000000000000000000000000000000'  + RIGHT('0000000' + LTRIM(RTRIM(STR(D.LSF))),7) +  isnull(D.CodeRow,''), 57) + '5',  X.OrderT
able, isnull(D.CodeRow, ''), isnull(D.LSF,0)  from dbo.report_export_xml X join #t_Txt T on X.Link_Self = T.Link  
    join (select distinct LSF, OrderTable, CodeRow from #t_Data) D  on X.OrderTable = D.OrderTable and ((D.CodeRow = T.CodeRow and D.LSF = T.LSF) or T.LSF = 0)  
   where link_up = @LinkE and Type = 0 and txt_end <> ''    
    and not exists(select top 1 * from  #t_Txt T where X.link = T.link)  
  
  insert #t_Txt (link, txt, orders, OrderTable, CodeRow, LSF)  
  select link, txt, orders, OrderTable, CodeRow, LSF  
  from #t_Txt1  
  
 end  
 -- заполняем таблицу:  
 declare @txt varchar(8000), @orders varchar(1000), @link int, @OT tinyint, @CodeRow varchar(50), @LSF int  
 declare @t_Empty table (Code char(4))  
  
 insert @t_Empty (Code) values ('@1@') insert @t_Empty (Code) values ('@2@') insert @t_Empty (Code) values ('@3@') insert @t_Empty (Code) values ('@4@') insert @t_Empty (Code) values ('@5@')   
 insert @t_Empty (Code) values ('@6@') insert @t_Empty (Code) values ('@7@') insert @t_Empty (Code) values ('@8@') insert @t_Empty (Code) values ('@9@') insert @t_Empty (Code) values ('@10@')   
 insert @t_Empty (Code) values ('@11@') insert @t_Empty (Code) values ('@12@') insert @t_Empty (Code) values ('@13@') insert @t_Empty (Code) values ('@14@') insert @t_Empty (Code) values ('@15@')   
 insert @t_Empty (Code) values ('@16@') insert @t_Empty (Code) values ('@17@') insert @t_Empty (Code) values ('@18@') insert @t_Empty (Code) values ('@19@') insert @t_Empty (Code) values ('@20@')   
 insert @t_Empty (Code) values ('@21@') insert @t_Empty (Code) values ('@22@') insert @t_Empty (Code) values ('@23@') insert @t_Empty (Code) values ('@24@') insert @t_Empty (Code) values ('@25@')   
 insert @t_Empty (Code) values ('@26@') insert @t_Empty (Code) values ('@27@') insert @t_Empty (Code) values ('@28@') insert @t_Empty (Code) values ('@29@') insert @t_Empty (Code) values ('@30@')   
  
 update #t_Txt  
 set txt = REPLACE(txt, 'RIGHT(@CODEROW@' + SUBSTRING(txt, CHARINDEX(',', txt, CHARINDEX('RIGHT(', txt)), CHARINDEX(')', txt, CHARINDEX('RIGHT(', txt)) - CHARINDEX(',', txt, CHARINDEX('RIGHT(', txt))) + ')',  
   RIGHT(RTRIM(CodeRow),convert(int, SUBSTRING(txt, CHARINDEX(',', txt, CHARINDEX('RIGHT(', txt))+1, CHARINDEX(')', txt, CHARINDEX('RIGHT(', txt)) - CHARINDEX(',', txt, CHARINDEX('RIGHT(', txt))-1))))  
   WHERE txt like '%RIGHT(@CODEROW@%'  
  
 update #t_Txt  
 set txt = REPLACE(txt, 'LEFT(@CODEROW@' + SUBSTRING(txt, CHARINDEX(',', txt, CHARINDEX('LEFT(', txt)), CHARINDEX(')', txt, CHARINDEX('LEFT(', txt)) - CHARINDEX(',', txt, CHARINDEX('LEFT(', txt))) + ')', LEFT(RTRIM(CodeRow),convert(int, SUBSTRING(txt, CHARINDEX(',', txt, CHARINDEX('LEFT(', txt))+1, CHARINDEX(')', txt, CHARINDEX('LEFT(', txt)) - CHARINDEX(',', txt, CHARINDEX('LEFT(', txt))-1))))  
   WHERE txt like '%LEFT(@CODEROW@%' --+ SUBSTRING(txt, CHARINDEX(',', txt, CHARINDEX('LEFT(', txt)), CHARINDEX(')', txt, CHARINDEX('LEFT(', txt)) - CHARINDEX(',', txt, CHARINDEX('LEFT(', txt))) + ')%'  
  
 update #t_Txt  
 set txt =    
    REPLACE(txt, 'SUBSTRING(@CODEROW@' + SUBSTRING(txt, CHARINDEX(',', txt, CHARINDEX('SUBSTRING(', txt)), CHARINDEX(')', txt, CHARINDEX('SUBSTRING(', txt)) - CHARINDEX(',', txt, CHARINDEX('SUBSTRING(', txt))) + ')',   
    SUBSTRING(CodeRow, convert(int, SUBSTRING(txt, CHARINDEX(',', txt, CHARINDEX('SUBSTRING(', txt))+1, CHARINDEX(',', txt, CHARINDEX(',', txt, CHARINDEX('SUBSTRING(', txt)) + 1) - CHARINDEX(',', txt, CHARINDEX('SUBSTRING(', txt)) - 1)),  
     convert(int,SUBSTRING(txt, CHARINDEX(',', txt, CHARINDEX(',', txt, CHARINDEX('SUBSTRING(', txt))+1)+1,  CHARINDEX(')', txt, CHARINDEX('SUBSTRING(', txt))  - CHARINDEX(',', txt, CHARINDEX(',', txt, CHARINDEX('SUBSTRING(', txt))+1) - 1)))  
    )  
   WHERE txt like '%SUBSTRING(@CODEROW@%' --+ SUBSTRING(txt, CHARINDEX(',', txt, CHARINDEX('SUBSTRING(', txt)), CHARINDEX(')', txt, CHARINDEX('SUBSTRING(', txt)) - CHARINDEX(',', txt, CHARINDEX('SUBSTRING(', txt))) + ')%'  
  
 update #t_Txt  
 set txt = REPLACE(txt, '@CODEROW@', RTRIM(CodeRow))  
  
 update #t_Txt  
 set txt = REPLACE(txt, '@КОД_ДОХОДА@', RIGHT(RTRIM(K.Code),17))  
 from dbo.report_kbk K  
 where code_form = 'ДОХОДЫ_2010' and K.Code like '%' + RTRIm(CodeRow) + '%' and CHARINDEX('@КОД_ДОХОДА@', txt) > 0  
  
 declare @code_skif table (code_str varchar(50), code varchar(50))  
  
 insert @code_skif (code_str, code) values ('520', '0105000000000000А')  
 insert @code_skif (code_str, code) values ('520', '0105000000000050А')  
 insert @code_skif (code_str, code) values ('520', '0105010000000050А')  
 insert @code_skif (code_str, code) values ('520', '0105020000000050А')  
 insert @code_skif (code_str, code) values ('520', '0105000000000060А')  
 insert @code_skif (code_str, code) values ('520', '0105010000000060А')  
 insert @code_skif (code_str, code) values ('520', '0105020000000060А')  
 insert @code_skif (code_str, code) values ('520', '0800000000000000А')  
 insert @code_skif (code_str, code) values ('520', '0800000000000050А')  
 insert @code_skif (code_str, code) values ('520', '0801000000000050А')  
 insert @code_skif (code_str, code) values ('520', '0802000000000050A')  
 insert @code_skif (code_str, code) values ('520', '0800000000000060A')  
 insert @code_skif (code_str, code) values ('520', '0801000000000060A')  
 insert @code_skif (code_str, code) values ('520', '0802000000000060А')  
 insert @code_skif (code_str, code) values ('800', 'И4000000000000000')  
 insert @code_skif (code_str, code) values ('810', 'И5000000000000000')  
 insert @code_skif (code_str, code) values ('811', 'И6000000000000000')  
 insert @code_skif (code_str, code) values ('812', 'И7000000000000000')  
 insert @code_skif (code_str, code) values ('820', 'И8000000000000000')  
 insert @code_skif (code_str, code) values ('821', 'И9000000000000000')  
 insert @code_skif (code_str, code) values ('822', 'И1000000000000000')  
  
 update #t_Txt  
 set txt = REPLACE(txt, '@КОД_ИСТОЧНИКОВ@', RIGHT(RTRIM(K.Code),17))  
 from @code_skif K  
 where K.Code_str = LEFT(CodeRow,3) and K.Code like  + '%' + RIGHT(RTRIM(CodeRow),LEN(CodeRow)-3) + '%' and CHARINDEX('@КОД_ИСТОЧНИКОВ@', txt) > 0  
  
 update #t_Txt  
 set txt = REPLACE(txt, '@КОД_ИСТОЧНИКОВ@', RIGHT(RTRIM(K.Code),17))  
 from dbo.report_kbk K  
 where code_form = 'ИСТОЧНИКИ_2010' and K.Code like '%' + LEFT(CodeRow,3) + '%' + RIGHT(RTRIM(CodeRow),LEN(CodeRow)-3) + '%' and CHARINDEX('@КОД_ИСТОЧНИКОВ@', txt) > 0 and LEFT(CodeRow, 3) > '700'  
  
 update #t_Txt  
 set txt = REPLACE(txt, '@КОД_ИСТОЧНИКОВ@', RIGHT(RTRIM(K.Code),14) + '000')  
 from dbo.report_kbk K  
 where code_form = 'ИСТОЧНИКИ_2010' and K.Code like '%' + LEFT(CodeRow,3) + '%' + RIGHT(RTRIM(CodeRow),LEN(CodeRow)-3) + '%' and CHARINDEX('@КОД_ИСТОЧНИКОВ@', txt) > 0  
  
 declare cur_Text  cursor local static for select link, orders, txt,  orderTable, CodeRow, LSF from #t_Txt where charindex('@', txt) > 0  
  
 open cur_Text  
 fetch next from cur_Text into  @link, @orders, @txt, @OT, @CodeRow, @LSF  
 while @@fetch_status = 0  
 BEGIN  
  select @txt = REPLACE(@txt, RTRIM(code), RTRIM(VALUE))  
  from @t_header  
  where LSF = @LSF or LSF = 0  
        
  if @LSF = 0  
  begin  
   delete #t_TXT where link = @link  
  
   insert #t_TXT  
   select @link, max(REPLACE(@txt, code, value)), @orders, @OT, @CodeRow, LSF  
   from @t_header  
   where LSF <> 0 and CHARINDEX(code, @txt) > 0     
         GROUP BY LSF  
   union  
   select -@link, (select top 1 txt from #t_TXT where link = -@link), LEFT(@orders, LEN(@orders)-1) + '5', @OT, @CodeRow, LSF  
   from @t_header  
   where LSF <> 0 and CHARINDEX(code, @txt) > 0     
  
   if @@ROWCOUNT = 0  
   begin  
    insert #t_TXT  
    select @link, @txt, @orders, @OT, @CodeRow, 0     
   end  
   else  
    delete #t_TXT where link = -@link and LSF = 0  
              
         SELECT @LSF = MIN(LSF) FROM #t_TXT WHERE [link] = @link  
         WHILE EXISTS(SELECT * FROM #t_TXT WHERE [link] = @link AND LSF > @LSF)  
         BEGIN  
            SELECT @TXT = TXT FROM #t_TXT WHERE [link] = @link AND LSF = @LSF  
  
        select @txt = replace(@txt, RTRIM(Code_str), RTRIM(add_info)) from dbo.report_kbk where code_form = 'SEND_XML' and (CHARINDEX('#' + RTRIM(@CodeForm) + '#', Code) > 0 or REPLACE(Code,'#','') = '')  
            SELECT @txt = REPLACE(@txt, code, value)  
            FROM @t_Header  
            WHERE LSF = @LSF              
              
            UPDATE #t_TXT SET TXT = @TXT WHERE [link] = @link AND LSF = @LSF      
            SELECT @LSF = MIN(LSF) FROM #t_TXT WHERE [link] = @link AND LSF > @LSF  
         END              
         SELECT @TXT = TXT FROM #t_TXT WHERE [link] = @link AND LSF = @LSF  
  
         SELECT @txt = REPLACE(@txt, code, value)  
         FROM @t_Header  
         WHERE LSF = @LSF              
  
       select @txt = replace(@txt, RTRIM(Code_str), RTRIM(add_info)) from dbo.report_kbk where code_form = 'SEND_XML' and (CHARINDEX('#' + RTRIM(@CodeForm) + '#', Code) > 0 or REPLACE(Code,'#','') = '')  
              
         UPDATE #t_TXT SET TXT = @TXT WHERE [link] = @link AND LSF = @LSF  
         SET @LSF = 0      
  END  
        
  
  if @TXT like '%RIGHT%'  
  BEGIN  
  
  
     select  @TXT = REPLACE(@txt, 'RIGHT(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt)), CHARINDEX(')', @txt, CHARINDEX('RIGHT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt))) + ')', RIGHT(RTRIM(Value),convert(int, SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt))+1, CHARINDEX(')', @txt, CHARINDEX('RIGHT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt))-1))))  
   from #t_Data  
   where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF   
    and @txt like '%RIGHT(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt)), CHARINDEX(')', @txt, CHARINDEX('RIGHT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt))) + ')%'  
  
     select  @TXT = REPLACE(@txt, 'RIGHT(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt)), CHARINDEX(')', @txt, CHARINDEX('RIGHT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt))) + ')', RIGHT(RTRIM(Value),convert(int, SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt))+1, CHARINDEX(')', @txt, CHARINDEX('RIGHT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt))-1))))  
   from #t_Data  
   where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF   
    and @txt like '%RIGHT(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt)), CHARINDEX(')', @txt, CHARINDEX('RIGHT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt))) + ')%'  
  
    end  
  
  if @TXT like '%LEFT%'  
  BEGIN  
  
   select  @TXT = REPLACE(@txt, 'LEFT(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt)), CHARINDEX(')', @txt, CHARINDEX('LEFT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt))) + ')', LEFT(RTRIM(Value),convert(int, SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt))+1, CHARINDEX(')', @txt, CHARINDEX('LEFT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt))-1))))  
   from #t_Data  
   where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF   
    and @txt like '%LEFT(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt)), CHARINDEX(')', @txt, CHARINDEX('LEFT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt))) + ')%'  
  
   select  @TXT = REPLACE(@txt, 'LEFT(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt)), CHARINDEX(')', @txt, CHARINDEX('LEFT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt))) + ')', LEFT(RTRIM(Value),convert(int, SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt))+1, CHARINDEX(')', @txt, CHARINDEX('LEFT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt))-1))))  
   from #t_Data  
   where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF   
    and @txt like '%LEFT(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt)), CHARINDEX(')', @txt, CHARINDEX('LEFT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt))) + ')%'  
              
  END  
  
--  if @TXT like '%SUBSTRING%'  
--  BEGIN  
--  
--   select  @TXT = REPLACE(@txt, 'SUBSTRING(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt)), CHARINDEX(')', @txt, CHARINDEX('SUBSTRING(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))) + ')',   
--         SUBSTRING(RTRIM(Value),convert(int, SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))+1, CHARINDEX(')', @txt, CHARINDEX('SUBSTRING(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))-1))  
--         , convert(int, SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt)))+1, CHARINDEX(')', @txt, CHARINDEX('SUBSTRING(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))-1  
--         ))))  
--   
--   from #t_Data  
--   where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF   
--    and @txt like '%SUBSTRING(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt)), CHARINDEX(')', @txt, CHARINDEX('SUBSTRING(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))) + ')%'  
--  
--  
--   select  @TXT = REPLACE(@txt, 'SUBSTRING(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt)), CHARINDEX(')', @txt, CHARINDEX('SUBSTRING(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))) + ')',   
--         SUBSTRING(RTRIM(Value),convert(int, SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))+1, CHARINDEX(')', @txt, CHARINDEX('SUBSTRING(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))-1))  
--         , convert(int, SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt)))+1, CHARINDEX(')', @txt, CHARINDEX('SUBSTRING(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))-1  
--         ))))  
--  
--   from #t_Data  
--   where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF   
--    and @txt like '%SUBSTRING(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt)), CHARINDEX(')', @txt, CHARINDEX('SUBSTRING(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))) + ')%'  
--              
--  END  
        
      SELECT @OrderCol = RTRIM(min(OrderCol))   
  from #t_Data  
  where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF  
  
      WHILE EXISTS(select * from #t_Data where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF AND orderCol > @orderCol)  
      BEGIN  
         SELECT @Value = RTRIM(VALUE)    
     from #t_Data  
     where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF AND orderCol = @orderCol  
  
         select @txt = REPLACE(@txt, @OrderCol, @Value)     
  
         SELECT @OrderCol = RTRIM(min(OrderCol))   
     from #t_Data  
     where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF AND orderCol > @orderCol  
      END            
  
         
      SELECT @Value = VALUE    
    from #t_Data  
    where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF AND orderCol = @orderCol  
  
      IF @OrderCol IS NOT NULL  
      select @txt = REPLACE(@txt, @OrderCol, @Value)     
  
  select @txt = replace(@txt, RTRIM(Code), '')  
  from @t_Empty  
  
  select @txt = replace(@txt, RTRIM(Code_str), RTRIM(add_info)) from dbo.report_kbk where code_form = 'SEND_XML' and (CHARINDEX('#' + RTRIM(@CodeForm) + '#', Code) > 0 or REPLACE(Code,'#','') = '')  
  
  update #t_Txt set txt = @txt where link = @link and LSF = @LSF and CodeRow = @CodeRow and OrderTable = @OT  
  fetch next from cur_Text into  @link, @orders, @txt, @OT, @CodeRow, @LSF  
 end  
  
 close cur_Text  
 deallocate cur_Text  
 --select  txt + case when link > 0 then '>' else '' end,  orders, LSF from #t_Txt order by orders, CodeRow  
  
 delete #t_Txt where ltrim(txt) = ''  
  
 -------- результат  
 declare @OrderFile int  
 set @OrderFile = isnull((select max(OrderFile) from #Files), 0)  
  
 insert #Files ([TXT], [NAMEFILE],  [NAMEFILE_ARH], [OrderFile], [LINK_SAVED_FORM])  
 select T.txt + isnull(X.txt_close,''),   
  REPLACE(RTRIM(@NameDate), ' ', '_') + '_' + @CodeBudg + '_' + @CodeOrg + '_Форма_' + RTRIM(@CodeForm) + '.xml',  
  REPLACE(RTRIM(@NameDate), ' ', '_') + '_' + @CodeBudg + '_' + @CodeOrg + '_Форма_' + RTRIM(@CodeForm) + '.arj' , @OrderFile, @varKSiLSF     
 from #t_Txt T left join dbo.report_export_xml X on T.link =  X.link and X.link_up = @LinkE  
 order by T.orders  
  
  

GO
GRANT ALL ON dbo.[RO_EXPORT_REPORT_XML] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

GO

CREATE  PROCEDURE dbo.BV_AVANSE_TABLE_DELETE
	@varKSintLINK	int
AS
	DELETE OTR
	FROM dbo.OUT_TABLE_ROW OTR
--	INNER JOIN dbo.S_OBJECTS SO ON (SO.LINK = OTR.[OBJECT]
--		AND SO.CODE = 'BV_DOC_AVANSE_TABLE')
	WHERE OTR.LINK = @varKSintLINK

	RETURN
GO

GRANT EXECUTE ON dbo.[BV_AVANSE_TABLE_DELETE] TO PUBLIC

GO

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


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

GO
CREATE PROCEDURE [dbo].[KIR_EXEC_SALARY_ESN_REPORT1]

	@DATE1 DATETIME,			/* Начало периода */
	@DATE2 DATETIME,			/* Конец периода */
	@CHECK1 INT	= 1,			/* Мужчины до 1952 г. р., женщины до 1956 */
	@CHECK2 INT	= 1,			/* Мужчины до 1952 г. р., женщины до 1956 */
	@CHECK3 INT	= 1,			/* 1967 г.р. и моложе */
	@ORDERBY INT,				/* Сортировать по */

	@DETAL_SUB TINYINT = 1,		/* Детализировать по подразделениям */
	@DETAL_FIO TINYINT = 1,		/* Детализировать по сотрудникам */
	@DETAL_SOURCE TINYINT = 1,	/* Детализировать по источникам */
	
	@DGH TINYINT = 0,			/* Включать договорников */
	@SHOW_Data TINYINT = 0 ,	/* Вывод данных : 1) по страховым взносам  , 2) по доп тарифам  */
	@cVAL1 CHAR(1)='', @nOTBORLINK1 INT = 0, /* Отбор сотрудников */
	@cVAL2 CHAR(1)='', @nOTBORLINK2 INT = 0, /* Отбор подразделений */
	@cVAL3 CHAR(1)='', @nOTBORLINK3 INT = 0 /* Отбор источников */

AS 
BEGIN

	DECLARE @LINK_DEP INT
	EXEC DBO.XD_WHATS_ZB @LINK_DEP OUTPUT
	
	DECLARE @YEAR_BEG DATETIME
	SET @YEAR_BEG = dbo.DateBeginOfyEAR(@DATE2)	

	CREATE TABLE #EMPLS(LINK_EMPL INT)
	IF LEN(@cVAL1) <> 0 
		INSERT INTO #EMPLS
		SELECT RECORD AS LINK_EMPL FROM DBO.OBJECT_VAR_EMPL WHERE LINK_UP = @nOTBORLINK1
	ELSE
		INSERT INTO #EMPLS
		SELECT LINK AS LINK_EMPL 
 		FROM DBO.EMPL WHERE DEP_LINK = @LINK_DEP

	CREATE TABLE #SUBDIV(LINK_SUB INT)
	IF LEN(@cVAL2) <> 0 
		INSERT INTO #SUBDIV
		SELECT RECORD FROM DBO.OBJECT_VAR_SUBDIV_HEAD WHERE LINK_UP = @nOTBORLINK2

	--
	DECLARE @Y INT, @MIN_M INT, @MAX_M INT
	SELECT @Y = YEAR(@DATE2), @MAX_M = MONTH(@DATE2), @MIN_M = CASE WHEN YEAR(@DATE1) = YEAR(@DATE2) THEN MONTH(@DATE1) ELSE 1 END

	DECLARE @WAY TABLE (WAY_CALC TINYINT) 
	INSERT INTO @WAY(WAY_CALC)
	SELECT T4.way_calc
	FROM 
		dbo.DICTIONARY_MROT_TABLE4 t4
	WHERE
		t4.link_minrot = (SELECT TOP 1 link FROM dbo.DICTIONARY_MROT ss WHERE ss.period <= @DATE1 ORDER BY ss.period DESC)

	--
	CREATE TABLE #T1 (LINK_VKR INT, MONTH_BASE NUMERIC(18,2), SUMMA_BASE NUMERIC(18,2), DED_M NUMERIC(18,2), INV_M NUMERIC(18,2), SUMMA NUMERIC(18,2), WAY_CALC TINYINT, REF_PHYS_PERS INT, DGH TINYINT, SPO INT)
	
	INSERT INTO #T1 (LINK_VKR, MONTH_BASE, SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, DGH, SPO)
	SELECT 
		LINK_VKR = (CASE WHEN @DETAL_SOURCE = 1 THEN LINK_VKR ELSE 0 END),
		MONTH_BASE, SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, 0 ,SPO = SPECO  
	FROM DBO.SA_ESN_VIEW(@Y, @MAX_M, @LINK_DEP, 0) E
	WHERE 
		(@cVAL3 = '' OR @cVAL3 <> '' AND EXISTS (SELECT RECORD FROM DBO.OBJECT_VAR_SAL_SFIN V WHERE LINK_UP = @nOTBORLINK3 AND V.RECORD = E.LINK_VKR))
	--	
	DECLARE @CUR1 CURSOR
	SET @CUR1 = CURSOR FORWARD_ONLY

	FOR SELECT Y, MIN(M) AS MIN_M, MAX(M) AS MAX_M FROM DBO.MONTHS_EX(@YEAR_BEG, @DATE2) WHERE Y < @Y GROUP BY Y ORDER BY Y DESC 
	
	OPEN @CUR1
	FETCH NEXT FROM @CUR1 INTO @Y, @MIN_M, @MAX_M
	WHILE (@@FETCH_STATUS <> -1)
	BEGIN
		IF (@@FETCH_STATUS <> -2)
		BEGIN

			INSERT INTO #T1 (LINK_VKR, MONTH_BASE, SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, DGH, SPO )
			SELECT 
				LINK_VKR = (CASE WHEN @DETAL_SOURCE = 1 THEN LINK_VKR ELSE 0 END),
				MONTH_BASE, SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, 0 , SPO = SPECO
			FROM DBO.SA_ESN_VIEW(@Y, @MAX_M, @LINK_DEP, 0) E 
			WHERE MONTH_BASE >= @MIN_M
					AND (@cVAL3 = '' OR @cVAL3 <> '' AND EXISTS (SELECT RECORD FROM DBO.OBJECT_VAR_SAL_SFIN V WHERE LINK_UP = @nOTBORLINK3 AND V.RECORD = E.LINK_VKR))
		END
	
		FETCH NEXT FROM @CUR1 INTO @Y, @MIN_M, @MAX_M
	END
	
	CLOSE @CUR1
	DEALLOCATE @CUR1

	DECLARE @LINK_OBJ__DOCUMENTS_DGH INT
	SELECT @LINK_OBJ__DOCUMENTS_DGH = LINK FROM dbo.S_OBJECTS WHERE CODE = 'DOCUMENTS_DGH' 

	---Суммы по договорникам
	IF @DGH = 1
		INSERT INTO #T1 (LINK_VKR, MONTH_BASE, SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, DGH)
		SELECT
			LINK_VKR = (CASE WHEN @DETAL_SOURCE = 1 THEN GT.LINK_VKR ELSE 0 END), 
			MONTH(G.[DATE]) AS MONTH_BASE, 
			GT.SUMMA_BASE, 
			DED_M = 0, 
			INV_M = 0, 
			GT.SUMMA, P.WAY_CALC, GT.PERS_LINK, 1
		FROM 
			dbo.SDOC G
			INNER JOIN dbo.SDOC_DGH_TABLE GT ON G.LINK = GT.LINK_UP
			INNER JOIN dbo.PAYS P ON P.LINK = GT.LINK_PAY
			INNER JOIN dbo.SAL_SFIN F ON F.LINK = GT.LINK_VKR
		WHERE
			G.[OBJECT] = @LINK_OBJ__DOCUMENTS_DGH
			AND GT.[OBJECT] = 3
			AND FLAG_JC = 1
			AND P.[OBJECT] = 3
			AND YEAR(G.[DATE]) = @Y
			AND MONTH(G.[DATE]) BETWEEN MONTH(@YEAR_BEG) AND @MAX_M
			AND LINK_DEP = @LINK_DEP
			AND (@cVAL3 = '' OR @cVAL3 <> '' AND EXISTS (SELECT RECORD FROM DBO.OBJECT_VAR_SAL_SFIN V WHERE LINK_UP = @nOTBORLINK3 AND V.RECORD = GT.LINK_VKR))
	--справочник баз для расчёта отчислений
	CREATE TABLE #BASE_PAYS (WAY_CALC TINYINT, LINK_PAYS INT)
	INSERT INTO #BASE_PAYS (P.WAY_CALC, LINK_PAYS)
	SELECT DISTINCT P.WAY_CALC, R.LINK_PAYS
	FROM 
		dbo.PAYS P INNER JOIN dbo.TAX_REF R ON R.link_tax = P.LINK 
	WHERE
		P.[OBJECT] = 3
		AND EXISTS ( SELECT * FROM @WAY W WHERE W.WAY_CALC = P.WAY_CALC )

	--фактическая база для договорников
	CREATE TABLE #DGH_FAKT_BASE (PERS_LINK INT, WAY_CALC TINYINT, LINK_PAY INT, Y INT, M TINYINT, LINK_VKR INT, SUMMA NUMERIC(18,2))
	INSERT INTO #DGH_FAKT_BASE (PERS_LINK, LINK_PAY, WAY_CALC, Y, M, LINK_VKR, SUMMA)
	SELECT 
		GT.PERS_LINK, GT1.LINK_PAY, GT.WAY_CALC, Y = YEAR(G.[DATE]), M = MONTH(G.[DATE]), 
		(CASE WHEN @DETAL_SOURCE = 1 THEN GT.LINK_VKR ELSE 0 END), 
		SUMMA_BASE = sum(GT.SUMMA_BASE)
	FROM 
		dbo.DOCUMENTS_DGH G 
		INNER JOIN dbo.DOCUMENTS_DGH_T1 GT1 ON G.LINK = GT1.LINK
		INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
	WHERE 
		FLAG_JC = 1
		AND YEAR(G.[DATE]) = @Y and MONTH(G.[DATE]) BETWEEN MONTH(@YEAR_BEG) AND @MAX_M 		
		AND (@cVAL3 = '' OR @cVAL3 <> '' AND EXISTS (SELECT RECORD FROM DBO.OBJECT_VAR_SAL_SFIN V WHERE LINK_UP = @nOTBORLINK3 AND V.RECORD = GT.LINK_VKR ))
		AND LINK_DEP = @LINK_DEP
	GROUP BY G.LINK, 
		GT.PERS_LINK, GT1.LINK_PAY, GT.WAY_CALC, YEAR(G.[DATE]), MONTH(G.[DATE]), GT.LINK_VKR

	--Начисленные суммы по лицам за период
	CREATE TABLE #CALC_OPER (PERS_LINK INT, LINK_PAYS INT, Y INT, M TINYINT, LINK_VKR INT, DGH TINYINT, SUMMA_ALL NUMERIC(18,2), SPO INT)
	INSERT INTO #CALC_OPER (PERS_LINK, LINK_PAYS, Y, M, LINK_VKR, DGH, SUMMA_ALL , SPO)
	--Сотрудники
	SELECT 
		E.PERS_LINK,
		cj.LINK_PAYS, Year(period_begin), Month(period_begin), 
		LINK_VKR = (CASE WHEN @DETAL_SOURCE = 1 THEN LINK_VKR ELSE 0 END),
		DGH = 0,
		SUMMA_ALL = SUM(CJ.SUMMA), 
		SPO = SPECO
	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
	WHERE 	
		Year(period_begin) = @Y and Month(period_begin) BETWEEN @MIN_M AND @MAX_M 
		AND CJ.LINK_DEP = @LINK_DEP
		AND P.[OBJECT] = 1
		AND (@cVAL3 = '' OR @cVAL3 <> '' AND EXISTS (SELECT RECORD FROM DBO.OBJECT_VAR_SAL_SFIN V WHERE LINK_UP = @nOTBORLINK3 AND V.RECORD = CJ.LINK_VKR))
		AND (LEN(@cVAL1) = 0 OR EXISTS (SELECT * FROM #EMPLS WHERE LINK_EMPL = E.LINK))
	GROUP BY
		E.PERS_LINK, cj.LINK_PAYS, period_begin, CJ.SPECO, (CASE WHEN @DETAL_SOURCE = 1 THEN LINK_VKR ELSE 0 END)


	
	INSERT INTO #CALC_OPER (PERS_LINK, LINK_PAYS, Y, M, LINK_VKR, DGH, SUMMA_ALL, SPO)
	--Договорники
	SELECT 
		CJ.PERS_LINK,
		cj.LINK_PAYS, Year(period_begin), Month(period_begin),
		LINK_VKR = (CASE WHEN @DETAL_SOURCE = 1 THEN LINK_VKR ELSE 0 END),
		DGH = 1,
		SUMMA_ALL = SUM(CJ.SUMMA),
		SPO = SPECO
	FROM 
		dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
	WHERE
		@DGH = 1
		AND CJ.PERS_LINK IS NOT NULL
		AND Year(period_begin) = @Y and Month(period_begin) BETWEEN @MIN_M AND @MAX_M 
		AND CJ.LINK_DEP = @LINK_DEP
		AND P.[OBJECT] = 1
		AND (@cVAL3 = '' OR @cVAL3 <> '' AND EXISTS (SELECT RECORD FROM DBO.OBJECT_VAR_SAL_SFIN V WHERE LINK_UP = @nOTBORLINK3 AND V.RECORD = CJ.LINK_VKR))
	GROUP BY
		CJ.PERS_LINK, cj.LINK_PAYS, period_begin, CJ.SPECO, (CASE WHEN @DETAL_SOURCE = 1 THEN LINK_VKR ELSE 0 END)

	-----------
	CREATE TABLE #CALC_OPER_W(PERS_LINK INT, LINK_PAYS INT, Y INT, M INT, LINK_VKR INT, DGH TINYINT, SUMMA NUMERIC(18,2), WAY_CALC TINYINT, WAY_NAME VARCHAR(50) , SPO int)
	INSERT INTO #CALC_OPER_W (PERS_LINK, LINK_PAYS, Y, M, LINK_VKR, DGH, SUMMA, WAY_CALC, WAY_NAME , SPO)
	SELECT PERS_LINK, LINK_PAYS, Y, M, LINK_VKR, DGH, SUMMA_ALL, WC.CODE, WAY_NAME = (CASE WHEN ISNULL(SPO,0) >0 
																THEN WC.NAME  + ' - ' + (SELECT CODE FROM  SA_SZV4_SPR  s4 WHERE  s4.link =  CO.SPO  AND s4.spr_code = 'SPO_USL_TRUDA') 
														     ELSE  WC.NAME  END), CO.SPO
	FROM #CALC_OPER CO INNER JOIN dbo.WAY_CALC WC ON 1=1
	WHERE WC.[TYPE] = 2 
		AND EXISTS ( SELECT * FROM @WAY W WHERE W.WAY_CALC = WC.CODE )

	-----------
	DELETE FROM #CALC_OPER_W
	WHERE 
		DGH = 0 AND EXISTS
			(SELECT * FROM #BASE_PAYS BP WHERE #CALC_OPER_W.LINK_PAYS = BP.LINK_PAYS AND #CALC_OPER_W.WAY_CALC = BP.WAY_CALC)

	-----------
	DELETE FROM #CALC_OPER_W
	WHERE 
		DGH = 1 AND EXISTS
			(SELECT * FROM #DGH_FAKT_BASE D 
				WHERE
					D.PERS_LINK = #CALC_OPER_W.PERS_LINK
					AND D.WAY_CALC = #CALC_OPER_W.WAY_CALC
					AND D.LINK_PAY = #CALC_OPER_W.LINK_PAYS
					AND D.Y = #CALC_OPER_W.Y
					AND D.M = #CALC_OPER_W.M
					AND D.LINK_VKR = #CALC_OPER_W.LINK_VKR
			)

	----------------------------------------------------------------------------------------
	CREATE TABLE #FACT_SUMMA (LINK_PERS INT, LINK_SFIN INT, SUMMA NUMERIC(18,2), DGH TINYINT, SPO INT)
	INSERT INTO #FACT_SUMMA (LINK_PERS, LINK_SFIN, SUMMA, DGH , SPO)
	SELECT PERS_LINK, LINK_VKR, SUMMA_ALL = SUM(SUMMA_ALL), DGH, SPO 
	FROM 
		#CALC_OPER
	WHERE
		M BETWEEN MONTH(@DATE1) AND MONTH(@DATE2)	 
	GROUP BY 
		PERS_LINK, DGH, LINK_VKR, SPO

	--------------------------------------------------------------
	CREATE TABLE #PERS (LINK_PERS INT, LINK_SFIN INT, DGH TINYINT, SPO INT)

	INSERT INTO #PERS (LINK_PERS, LINK_SFIN, DGH , SPO)
	SELECT DISTINCT LINK_PERS, LINK_SFIN, DGH , SPO
	FROM
	(
		SELECT LINK_PERS = REF_PHYS_PERS, LINK_SFIN = LINK_VKR, DGH , SPO FROM #T1 WHERE MONTH_BASE BETWEEN MONTH(@DATE1) AND MONTH(@DATE2)
		UNION 
		SELECT LINK_PERS, LINK_SFIN, DGH, SPO FROM #FACT_SUMMA -- по месяцам ограничено уже (выше)
	) T	
	--------------------------------------------------------------

	CREATE TABLE #PERS_INFO (
		LINK_PERS INT,REF_EMPL INT,
		TAB_NUMER VARCHAR(10),NAME_EMPL VARCHAR(254),
		LINK_SFIN INT, YEAR_B DATETIME, POL TINYINT, TYPE1 TINYINT, LINK_FACE INT, 
		NAME_SUB VARCHAR(254), CODE_SUB VARCHAR(5), DGH TINYINT, SPO INT)

	INSERT INTO #PERS_INFO (LINK_PERS, REF_EMPL, TAB_NUMER, NAME_EMPL, LINK_SFIN, YEAR_B, POL, TYPE1, LINK_FACE, NAME_SUB, CODE_SUB, DGH, SPO)
	SELECT  
		P.LINK_PERS,
		REF_EMPL = K1.LINK, 
		TAB_NUMER = CASE WHEN DGH = 0 THEN COALESCE(K1.TAB,'') ELSE '' END, 
		NAME_EMPL = RTRIM(K.FM) + ' ' + SUBSTRING(RTRIM(K.IM),1,1) + '.' + SUBSTRING(RTRIM(K.OT),1,1) + '.', 
		LINK_SFIN,
		[YEAR_B] = K.BIRTHDATE,
		[POL] = K.SEX,
		[TYPE1] = (CASE WHEN K.SEX = 1 AND YEAR(K.BIRTHDATE)<= 1952 THEN 1
					    WHEN K.SEX = 2 AND YEAR(K.BIRTHDATE)<= 1956 THEN 1
					    WHEN K.SEX = 1 AND (YEAR(K.BIRTHDATE) BETWEEN 1953 AND 1966) THEN 2
					    WHEN K.SEX = 2 AND (YEAR(K.BIRTHDATE) BETWEEN 1957 AND 1966) THEN 2
						WHEN YEAR(K.BIRTHDATE) >= 1967 THEN 3
					    ELSE 0
					END) ,
		[LINK_FACE] = K.LINK,
		NAME_SUB = CASE WHEN DGH = 0 THEN COALESCE(K1.SUBDIV_NAME,'По договору ГПХ') ELSE 'По договору ГПХ' END,
		CODE_SUB = CASE WHEN DGH = 0 THEN COALESCE(K1.SUBDIV_CODE,'ДГХ') ELSE 'ДГХ' END,
		DGH,
		P.SPO
	FROM 
		#PERS P
		INNER JOIN DBO.PERSON K ON  P.LINK_PERS = K.LINK
		LEFT JOIN DBO.SD_EMPL_FN(DEFAULT,@DATE2,DEFAULT,@LINK_DEP) K1 ON 
				P.LINK_PERS = K1.PERS_LINK
			AND
				K1.[STATUS_EMPL] IN (1,3) 
			AND 
				K1.DATE_BEGIN = 
					(SELECT MAX(K2.DATE_BEGIN) FROM DBO.SD_EMPL_FN(DEFAULT,@DATE2,DEFAULT,@LINK_DEP) K2 
					WHERE K2.[STATUS_EMPL] IN (1,3) AND K1.PERS_LINK = K2.PERS_LINK AND K2.DATE_BEGIN IS NOT NULL)
	WHERE
		P.DGH = 1
		OR
		(
			(LEN(@cVAL1) = 0 OR EXISTS (SELECT * FROM #EMPLS WHERE LINK_EMPL = K1.LINK))
			AND 
			(LEN(@cVAL2) = 0 OR EXISTS (SELECT * FROM #SUBDIV WHERE LINK_SUB = K1.SUBDIV_HEAD))	
		)

	--
	DECLARE @LIMIT NUMERIC(18,2)

	SELECT DISTINCT P.WAY_CALC, LIMIT = MIN(S.PREDEL), SPECO = null
	INTO #PREDEL
	FROM 
		dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.OBJECT = 3
	WHERE 
		[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S1 INNER JOIN DBO.PAYS P1 ON S1.LINK_PAYS = P1.LINK AND P1.[OBJECT] = 3 AND P1.WAY_CALC = P.WAY_CALC AND [DATE] < @DATE2 ORDER BY [DATE] DESC) 
		AND
		S.PERCENT1 > 0
		AND EXISTS ( SELECT * FROM @WAY W WHERE W.WAY_CALC = P.WAY_CALC )
	GROUP BY P.WAY_CALC	

	INSERT INTO #PREDEL
	SELECT DISTINCT P.WAY_CALC, LIMIT = MIN(S.PREDEL) , SPECO = (CASE WHEN S.SPECO = 0 then null else s.SPECO end)
	FROM 
		dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.OBJECT = 3
	WHERE 
		[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S1 INNER JOIN DBO.PAYS P1 ON S1.LINK_PAYS = P1.LINK AND P1.[OBJECT] = 3 AND P1.WAY_CALC = P.WAY_CALC AND [DATE] < @DATE2 ORDER BY [DATE] DESC) 
		AND
		(S.PERCENT1 > 0 OR S.PERCENT2 > 0 OR S.PERCENT3 > 0)
		AND EXISTS ( SELECT * FROM @WAY W WHERE W.WAY_CALC = P.WAY_CALC )		
	GROUP BY P.WAY_CALC	, S.SPECO	
	

	
	UPDATE #PREDEL
	SET LIMIT = 0
	WHERE LIMIT IS NULL




	SELECT MON = 1, REF_PHYS_PERS, DGH, T.WAY_CALC , T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END INTO #SPR_ESN1 FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 1 AND @MAX_M >= 1 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 2, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 2 AND @MAX_M >= 2 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 3, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 3 AND @MAX_M >= 3 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO 
	INSERT INTO #SPR_ESN1 SELECT MON = 4, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 4 AND @MAX_M >= 4 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 5, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 5 AND @MAX_M >= 5 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 6, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 6 AND @MAX_M >= 6 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 7, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 7 AND @MAX_M >= 6 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 8, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 8 AND @MAX_M >= 7 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 9, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 9 AND @MAX_M >= 8 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 10, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 10 AND @MAX_M >= 10 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 11, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 11 AND @MAX_M >= 11 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 12, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 12 AND @MAX_M >= 12 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO


	SELECT T.REF_PHYS_PERS, T.DGH, T.WAY_CALC, T.SPO, T.MON, SUMMA = SUM(SUMMA)
	INTO #SPR_ESN2
	FROM
	(
	SELECT DISTINCT T.REF_PHYS_PERS, T.DGH, T.WAY_CALC,T.SPO,  T1.MON, SUMMA = ISNULL(T1.SUMMA,0.00) - ISNULL(T2.SUMMA,0.00), 
		--Чтобы не потерять одинаковые суммы за разные месяцы
		 S1 = ISNULL(T1.SUMMA,0.00), S2 = ISNULL(T2.SUMMA,0.00), M1 = T1.MON, M2 = T2.MON
	FROM 
		#SPR_ESN1 T INNER JOIN dbo.months_ex(@YEAR_BEG, @DATE2) M ON 1=1
		LEFT JOIN #SPR_ESN1 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.DGH = T.DGH AND T1.WAY_CALC = T.WAY_CALC AND isnull(T1.SPO,0) = isnull(T.SPO,0) AND T1.MON = M.M
		LEFT JOIN #SPR_ESN1 T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.DGH = T.DGH AND T2.WAY_CALC = T.WAY_CALC AND isnull(T2.SPO,0) = isnull(T.SPO,0) AND T2.MON = M.M - 1
	WHERE
		(ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)) > 0
		AND M.Y = YEAR(@DATE2) AND M.M BETWEEN MONTH(@YEAR_BEG) AND MONTH(@DATE2)
	)t
	WHERE EXISTS ( SELECT * FROM @WAY W WHERE W.WAY_CALC = T.WAY_CALC )
	GROUP BY T.REF_PHYS_PERS, T.DGH, T.WAY_CALC, T.SPO, T.MON

---
	CREATE TABLE #T2 (REF_PHYS_PERS INT, DGH INT, MONTH_BASE TINYINT, WAY_CALC INT, SUMMA_BASE NUMERIC(18,2) , SPO INT)
	
	INSERT INTO #T2(REF_PHYS_PERS, DGH, MONTH_BASE, WAY_CALC, SUMMA_BASE , SPO)
	SELECT REF_PHYS_PERS, DGH, MONTH_BASE, WAY_CALC, SUMMA_BASE = SUM(SUMMA_BASE) , SPO  
	FROM #T1
	WHERE MONTH_BASE BETWEEN MONTH(@DATE1) AND MONTH(@DATE2)
	GROUP BY REF_PHYS_PERS, DGH, MONTH_BASE, WAY_CALC, SPO 



	--- Суммы с разбивкой по источникам финансирования
	SELECT LINK_FACE1, DGH, LINK_SFIN1, WAY_NAME = (CASE WHEN ISNULL(SPO,0) >0 
																THEN WAY_NAME + ' - ' + (SELECT CODE FROM  SA_SZV4_SPR  s4 WHERE  s4.link = TT.SPO  AND s4.spr_code = 'SPO_USL_TRUDA') 
														     ELSE  ISNULL(WAY_NAME,'') END),
		WAY_CALC, SPO, SS = SUM(SS), PAY = SUM(PAY), DED = SUM(DED), INV = SUM(INV), TAX = SUM(TAX),
		LIM = CONVERT(NUMERIC(18,2),
							CASE WHEN LINK_SFIN1 = 0 THEN SUM(SUM_LIM)
								ELSE SUM(SUM_LIM) * CASE WHEN SUM(BASE_ALL) > 0 AND SUM(BASE_FIN) > 0 THEN SUM(BASE_FIN) / SUM(BASE_ALL) ELSE 0 END 
							END
					)
	INTO #ESN 	
	FROM
		(
		SELECT  	
			LINK_FACE1 = T2.REF_PHYS_PERS,
			T2.DGH,
			LINK_SFIN1 = T3.LINK_VKR,
			WAY_NAME  = W.NAME,  
			T2.WAY_CALC,
			T2.MONTH_BASE,
			SS = SUM(CASE WHEN T2.WAY_CALC = 2 THEN T2.SUMMA_BASE ELSE 0 END),
	 		[PAY] = SUM(T3.SUMMA_BASE),
	 		[DED] = SUM(T3.DED_M),
	 		[INV] = SUM(T3.INV_M),
	 		SUM_LIM = CASE WHEN T2.DGH = 0 THEN ISNULL(MAX(L.SUMMA),0) 
	 					ELSE SUM( CASE WHEN T2.DGH > 0 AND ISNULL(L.SUMMA,0) > 0 THEN  T3.SUMMA_BASE ELSE  0 END )
	 					END,
	 		BASE_ALL = ISNULL(MAX(T2.SUMMA_BASE),0),
	 		BASE_FIN = ISNULL(SUM(T3.SUMMA_BASE),0),
	 		[TAX] = SUM(T3.SUMMA),	
	 		T2.SPO 	
		FROM 
			#T2 T2 -- доход сгруппирован по физ лицу, виду, договору и месяцу
			INNER JOIN dbo.WAY_CALC W ON W.CODE = T2.WAY_CALC AND W.[TYPE] = 2
			INNER JOIN #T1 T3 ON T2.REF_PHYS_PERS = T3.REF_PHYS_PERS AND T2.DGH = T3.DGH AND T2.MONTH_BASE = T3.MONTH_BASE AND T2.WAY_CALC = T3.WAY_CALC AND ISNULL(T2.SPO,0) = ISNULL(T3.SPO,0)
			LEFT JOIN #SPR_ESN2 L ON L.REF_PHYS_PERS = T2.REF_PHYS_PERS AND T2.DGH = L.DGH AND L.WAY_CALC = T2.WAY_CALC AND ISNULL(L.SPO,0) = ISNULL(T2.SPO,0) AND L.MON = T2.MONTH_BASE
		GROUP BY 
			T2.REF_PHYS_PERS, T2.DGH, T3.LINK_VKR, W.NAME, T2.WAY_CALC , T2.SPO, T2.MONTH_BASE
		) TT
	GROUP BY
		LINK_FACE1, DGH, LINK_SFIN1, WAY_NAME, WAY_CALC, SPO		



IF @SHOW_Data = '1' 
		DELETE FROM #ESN WHERE WAY_CALC IN (10, 11)
IF  @SHOW_Data = '2' 
		DELETE FROM #ESN WHERE WAY_CALC NOT IN (10, 11)
--<<<<<**********************
	--- переворачиваем поля в таблице 

	DECLARE @TABLE_1 VARCHAR(5000),
			@TABLE_2 varchar(5000)
	
	EXEC X_GET_TABLE_NAME @TABLE_1 OUTPUT
	EXEC X_GET_TABLE_NAME @TABLE_2 OUTPUT
	DECLARE @CNT1 INT
	SELECT @CNT1 = COUNT(DISTINCT WAY_NAME ) FROM #ESN 

	EXEC M_CROSS_TABLE
		'LINK_SFIN1, LINK_FACE1, DGH',  
		'WAY_NAME', 'VARCHAR(50)', 
		'SUMMA,PAY,DED,INV,LIM,TAX' , 'NUMERIC(20,2)#NUMERIC(20,2)#NUMERIC(20,2)#NUMERIC(20,2)#NUMERIC(20,2)#NUMERIC(20,2)',  'SUM(ss) AS ss, SUM(PAY) AS PAY, SUM(DED) AS DED, SUM(INV) AS INV, SUM(LIM) AS LIM, SUM(TAX) AS TAX ',
		'#ESN', @TABLE_1
	
	DECLARE @I1 INT, @SQLS1 VARCHAR(8000), @FIELD1 VARCHAR(4000)
	SET @I1=1
	WHILE @I1 <= @CNT1 BEGIN

		SET @FIELD1= 'WAY_NAME_'  +  RTRIM(LTRIM(STR(@I1)))
		SET @SQLS1= ' UPDATE '+@TABLE_1 + '  SET '+@FIELD1+ ' = (SELECT TOP 1 '+@FIELD1+' FROM ' +@TABLE_1 + ' WHERE '+ @FIELD1+ '  IS NOT NULL ) ' 
		
		EXEC (@SQLS1)
		
		SET @FIELD1= 'SUMMA_'  +  RTRIM(LTRIM(STR(@I1)))
		SET @SQLS1= ' UPDATE '+@TABLE_1 + '  SET '+@FIELD1+ ' = 0  WHERE ' + @FIELD1+ '  IS  NULL ' 
		
		EXEC (@SQLS1)

		SET @FIELD1= 'PAY_'  +  RTRIM(LTRIM(STR(@I1)))
		SET @SQLS1= ' UPDATE '+@TABLE_1 + '  SET '+@FIELD1+ ' = 0  WHERE ' + @FIELD1+ '  IS  NULL ' 

		EXEC (@SQLS1)

		SET @FIELD1= 'DED_'  +  RTRIM(LTRIM(STR(@I1)))
		SET @SQLS1= ' UPDATE '+@TABLE_1 + '  SET '+@FIELD1+ ' = 0  WHERE ' + @FIELD1+ '  IS  NULL ' 

		EXEC (@SQLS1)

		SET @FIELD1= 'INV_'  +  RTRIM(LTRIM(STR(@I1)))
		SET @SQLS1= ' UPDATE '+@TABLE_1 + '  SET '+@FIELD1+ ' = 0  WHERE ' + @FIELD1+ '  IS  NULL ' 

		EXEC (@SQLS1)
		
		SET @FIELD1= 'LIM_'  +  RTRIM(LTRIM(STR(@I1)))
		SET @SQLS1= ' UPDATE '+@TABLE_1 + '  SET '+@FIELD1+ ' = 0  WHERE ' + @FIELD1+ '  IS  NULL ' 

		EXEC (@SQLS1)				

		SET @FIELD1= 'TAX_'  +  RTRIM(LTRIM(STR(@I1)))
		SET @SQLS1= ' UPDATE '+@TABLE_1 + '  SET '+@FIELD1+ ' = 0  WHERE ' + @FIELD1+ '  IS  NULL ' 

		EXEC (@SQLS1)
						
		SET @I1=@I1+1
	END	



	-- приведение к нормальному виду и выборка данных из перевернутой  

	DECLARE @SQL NVARCHAR(4000), @ParmDefinition NVARCHAR(500)

	SET @SQL = N'SELECT LINK_SFIN = P.LINK_SFIN,'
	--
	IF @DETAL_SUB = 1
		SET @SQL = @SQL + ' NAME_SUB, CODE_SUB,'
	ELSE
		SET @SQL = @SQL + ' NAME_SUB = '' '', CODE_SUB = '' '','	
	--	
	IF @DETAL_FIO = 1
		/*<code begin> Шорков И.А. 10.10.2011 добавление в первую страницу поля Возрастная группа до 1967 ->1 , с 1967 -> 2  */
		SET @SQL = @SQL	+ ' [LINK_FACE] = P.LINK_PERS, [DGH1] = P.DGH, [TNum] = rtrim(ltrim(P.TAB_NUMER)), [LINK_EMPL] = P.REF_EMPL, [TN] = P.TAB_NUMER, [FIO]= P.NAME_EMPL, [SEX] = P.POL, [BIRTH] = P.YEAR_B,
						    [AGE_TYPE] = (CASE	WHEN P.TYPE1 = 1 THEN 1
												WHEN P.TYPE1 = 2 THEN 1
												WHEN P.TYPE1 = 3 THEN 2
										    ELSE 0
										  END),'
		/*<code end> Шорков И.А.  */							  
	ELSE
		SET @SQL = @SQL	+ ' [LINK_FACE] = 0, [LINK_EMPL] = 0, [TNUM] = 0, [TN] = '''', [FIO]= '''', [SEX] = 0, [BIRTH] = '''',[AGE_TYPE] = '''','

	IF @DETAL_SOURCE = 1
		SET @SQL = @SQL + ' [NAME_VKR] = F.CODE,'
	ELSE
		SET @SQL = @SQL + ' [NAME_VKR] = '' '','
		
	IF @CNT1 = 0 BEGIN
		SET @SQL =  @SQL + ' WAY_NAME_0 = '' '', SUMMA_0 = 0, PAY_0 =0, DED_0 =0, INV_0 = 0, LIM_0 =0, TAX_0 = 0,'
	END		
	--
	
		
	--
	SET @SQL = @SQL
			+ '
			O.*,
			SUMMA = (select sum(isnull(summa,0))			
			from  #FACT_SUMMA where P.LINK_PERS = LINK_PERS AND P.DGH = DGH AND LINK_SFIN = P.LINK_SFIN)
		into '+ @TABLE_2 +'	
		FROM
			#PERS_INFO P
			LEFT JOIN dbo.SAL_SFIN F ON F.LINK = P.LINK_SFIN
			LEFT JOIN ' + @TABLE_1 + ' O ON  O.LINK_FACE1 = P.LINK_PERS AND o.LINK_SFIN1 = P.LINK_SFIN  and o.dgh = p.dgh
			/*LEFT JOIN #ESN E ON O.LINK_FACE = E.LINK_FACE  AND O.LINK_SFIN = E.LINK_SFIN AND P.DGH = E.DGH*/
			--LEFT JOIN #FACT_SUMMA FS ON P.LINK_PERS = FS.LINK_PERS AND P.DGH = FS.DGH AND FS.LINK_SFIN = P.LINK_SFIN
		WHERE
			(@pCHECK1 = 1 AND TYPE1 = 1) OR (@pCHECK2 = 1 AND TYPE1 = 2) OR (@pCHECK3 = 1 AND  TYPE1 = 3)				
		GROUP BY
			'

	SET @SQL = @SQL + ' P.LINK_SFIN, F.CODE, o.LINK_SFIN1'
	
	SET @I1=1
	WHILE @I1 <= @CNT1 BEGIN
		
		SET @FIELD1 = 'o.WAY_NAME_' + RTRIM(LTRIM(STR(@I1)))
		SET @SQL = @SQL + ',' + @FIELD1	
		
		SET @FIELD1 = 'o.SUMMA_' + RTRIM(LTRIM(STR(@I1)))
		SET @SQL = @SQL + ',' + @FIELD1	

		SET @FIELD1 = 'o.PAY_' + RTRIM(LTRIM(STR(@I1)))
		SET @SQL = @SQL + ',' + @FIELD1	
		
		SET @FIELD1 = 'o.DED_' + RTRIM(LTRIM(STR(@I1)))
		SET @SQL = @SQL+ ',' + @FIELD1	
		
		SET @FIELD1 = 'o.INV_' + RTRIM(LTRIM(STR(@I1)))
		SET @SQL = @SQL + ',' + @FIELD1	
		
		SET @FIELD1 = 'o.LIM_' + RTRIM(LTRIM(STR(@I1)))
		SET @SQL = @SQL + ',' + @FIELD1	
		
		SET @FIELD1 = 'o.TAX_' + RTRIM(LTRIM(STR(@I1)))
		SET @SQL = @SQL + ',' + @FIELD1	
	
		
	SET @I1=@I1+1
	END	
	

	IF @DETAL_SUB = 1
		SET @SQL = @SQL + ' ,NAME_SUB, CODE_SUB'

	SET @SQL = @SQL + ' ,P.LINK_PERS, p.DGH   , O.LINK_FACE1 , o.DGH '
	
	IF @DETAL_FIO = 1
		/*<code begin>  Шорков И.А. 10.10.2011 добавление в первую страницу поля Возрастная группа , добавление в группировку  */
		SET @SQL = @SQL	+ ' , P.REF_EMPL ,  P.TAB_NUMER, P.NAME_EMPL, P.POL, P.YEAR_B, P.TYPE1/*, O.LINK_FACE1*/  '
		/* <coide end> Шорков И.А.*/

	SET @SQL = @SQL
			+ '
		ORDER BY 
			' 
	+ CASE @ORDERBY 
		WHEN 1 THEN 'SUMMA'
		WHEN 2 then ' TNum '
		WHEN 3 then 'FIO'
		ELSE 'NAME_SUB'
	END
	+ CASE WHEN @DETAL_SOURCE = 1 THEN ',F.CODE' ELSE '' END	

	PRINT   (@SQL)

	SET @ParmDefinition	= N'@pCHECK1 TINYINT, @pCHECK2 TINYINT, @pCHECK3 TINYINT'

	EXECUTE sp_executesql @SQL, @ParmDefinition, @pCHECK1 = @CHECK1, @pCHECK2 = @CHECK2, @pCHECK3 = @CHECK3


	SET @I1=1
	WHILE @I1 <= @CNT1 BEGIN
	
		SET @FIELD1= 'WAY_NAME_'  +  RTRIM(LTRIM(STR(@I1)))
		
		SET @SQLS1= ' UPDATE '+@TABLE_2 + '  SET '+@FIELD1+ ' = (SELECT TOP 1 '+@FIELD1+' FROM ' +@TABLE_2 + ' WHERE '+ @FIELD1+ '  IS NOT NULL ) ' 
		EXEC (@SQLS1)	
	SET @I1=@I1+1
	END		
	
	exec (' SELECT * FROM  ' + @TABLE_2 )

	DROP TABLE #T1
	DROP TABLE #PERS_INFO
	DROP TABLE #ESN
	DROP TABLE #FACT_SUMMA
	
	DECLARE @TABLE VARCHAR(100)
	EXEC X_GET_TABLE_NAME @TABLE OUTPUT
	DECLARE @CNT INT
	SELECT @CNT = COUNT(DISTINCT WAY_NAME) FROM #CALC_OPER_W

	
	EXEC M_CROSS_TABLE
		'PERS_LINK, LINK_PAYS, LINK_VKR, Y, M', 
		'WAY_NAME', 'VARCHAR(50)', 
		'SUMMA', 'NUMERIC(20,2)', 'SUM(SUMMA) AS SUMMA',
		'#CALC_OPER_W', @TABLE

	DECLARE @I INT, @SQLS VARCHAR(4000), @FIELD VARCHAR(100)
	SET @I=1
	WHILE @I <= @CNT BEGIN

		SET @FIELD= 'WAY_NAME_'  +  RTRIM(LTRIM(STR(@I)))
		SET @SQLS= ' UPDATE '+@TABLE + '  SET '+@FIELD+ ' = (SELECT TOP 1 '+@FIELD+' FROM ' +@TABLE + ' WHERE '+ @FIELD+ '  IS NOT NULL ) ' 

		EXEC (@SQLS)

		SET @FIELD= 'SUMMA_'  +  RTRIM(LTRIM(STR(@I)))
		SET @SQLS= ' UPDATE '+@TABLE + '  SET '+@FIELD+ ' = 0  WHERE ' + @FIELD+ '  IS  NULL ' 

		EXEC (@SQLS)

		SET @I=@I+1
	END			

	/* <coide begin> Шорков И.А. 10.10.2011 добавление во вторую страницу поля Возрастная группа до 1967 ->1 , с 1967 -> 2  */
	EXEC('
	IF EXISTS (SELECT * FROM ' + @TABLE + ')
		SELECT 
			NAME_EMPL = RTRIM(P.FM) + '' '' + SUBSTRING(RTRIM(P.IM),1,1) + ''.'' + SUBSTRING(RTRIM(P.OT),1,1) + ''.'',
			AGE_TYPE =  (CASE WHEN P.SEX = 1 AND YEAR(P.BIRTHDATE)<= 1952 THEN 1
					    WHEN P.SEX = 2 AND YEAR(P.BIRTHDATE)<= 1956 THEN 1
					    WHEN P.SEX = 1 AND (YEAR(P.BIRTHDATE) BETWEEN 1953 AND 1966) THEN 1
					    WHEN P.SEX = 2 AND (YEAR(P.BIRTHDATE) BETWEEN 1957 AND 1966) THEN 1
						WHEN YEAR(P.BIRTHDATE) >= 1967 THEN 2
					    ELSE 0
					END) ,
			BIRTH = P.BIRTHDATE,		
			PN.CODE, PN.NAME, SFIN_CODE = ISNULL(F.CODE,''ВСЕ''),
			O.*
		FROM
			dbo.PERSON P 
			INNER JOIN ' + @TABLE + ' O ON P.LINK = O.PERS_LINK
			INNER JOIN dbo.PAYS PN ON PN.LINK = O.LINK_PAYS
			LEFT JOIN dbo.SAL_SFIN F ON F.LINK = O.LINK_VKR
		ORDER BY 
			NAME_EMPL, Y, M, PN.CODE		
	ELSE		
		SELECT NAME_EMPL= '''', AGE_TYPE = '''', BIRTH = '''', CODE = '''', NAME = '''', SFIN_CODE = '''', PERS_LINK = 0, LINK_PAYS = 0, LINK_VKR = 0, Y = 0, M = 0, WAY_NAME_1  = '''', SUMMA_1 = 0	
	')	
	/* <coide end> Шорков И.А.*/
END






GO


GRANT EXECUTE ON dbo.[KIR_EXEC_SALARY_ESN_REPORT1] TO PUBLIC

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, 
	CASE WHEN WAY_CALC <> 15 THEN JC.PERIOD_BEGIN ELSE JC.DATE_BEGIN END, 
	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.DATE_BEGIN)=  YEAR(@D1) AND MONTH(JC.DATE_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

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

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,
		[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 = 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],
		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
	
	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 @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([INC_M1]+[INC_M2]+[INC_M3],0),
						   COL7 = ISNULL([B_BEF_M1]+[B_BEF_M2]+[B_BEF_M3],0),
						   COL8 = ISNULL((SELECT [B_BEF_M1]+[B_BEF_M2]+[B_BEF_M3] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER) ,0),
						   COL9 = 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 (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/*, [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*/

					
					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 k_PER_EDT FROM #TMP01 where ID=1),
						COL20 = (select k_YEAR_EDT FROM #TMP01 where ID=1),
						COL21 = (CASE WHEN (select k_YEAR_EDT FROM #TMP01 where ID=1) >= '2014' THEN (SELECT k_INSUR FROM #TMP01 where ID=1)  ELSE 0 END ),
						COL22 = (case when (select k_YEAR_EDT FROM #TMP01 where ID=1) < '2014' THEN (SELECT k_INSUR FROM #TMP01 where ID=1) ELSE 0 END ),
						COL23 = (case when (select k_YEAR_EDT FROM #TMP01 where ID=1) < '2014' THEN (SELECT k_GAIN FROM #TMP01 where ID=1) ELSE 0 END ), 
						COL24 = (SELECT k_PER_EDT FROM #TMP01 where ID=2),
					    COL25 = (select k_YEAR_EDT FROM #TMP01 where ID=2), 
					    COL26 = (CASE WHEN (select k_YEAR_EDT FROM #TMP01 where ID=2) >= '2014' THEN (SELECT k_INSUR FROM #TMP01 where ID=2)  ELSE 0 END ), 
					    COL27 = (case when (select k_YEAR_EDT FROM #TMP01 where ID=2) < '2014' THEN (SELECT k_INSUR FROM #TMP01 where ID=2) ELSE 0 END ), 
					    COL28 = (case when (select k_YEAR_EDT FROM #TMP01 where ID=2) < '2014' THEN (SELECT k_GAIN FROM #TMP01 where ID=2) ELSE 0 END ),
					    COL29 = (SELECT k_PER_EDT FROM #TMP01 where ID=3),
					    COL30 = (select k_YEAR_EDT FROM #TMP01 where ID=3), 
					    COL31 = (CASE WHEN (select k_YEAR_EDT FROM #TMP01 where ID=3) >= '2014' THEN (SELECT k_INSUR FROM #TMP01 where ID=3)  ELSE 0 END ), 
					    COL32 = (case when (select k_YEAR_EDT FROM #TMP01 where ID=3) < '2014' THEN (SELECT k_INSUR FROM #TMP01 where ID=3) ELSE 0 END ), 
					    COL33 = (case when (select k_YEAR_EDT FROM #TMP01 where ID=3) < '2014' THEN (SELECT k_GAIN FROM #TMP01 where ID=3) ELSE 0 END ),
					    COL34 = (SELECT k_PER_EDT FROM #TMP01 where ID=4),
					    COL35 = (select k_YEAR_EDT FROM #TMP01 where ID=4), 
					    COL36 = (CASE WHEN (select k_YEAR_EDT FROM #TMP01 where ID=4) >= '2014' THEN (SELECT k_INSUR FROM #TMP01 where ID=4)  ELSE 0 END ), 
					    COL37 = (case when (select k_YEAR_EDT FROM #TMP01 where ID=4) < '2014' THEN (SELECT k_INSUR FROM #TMP01 where ID=4) ELSE 0 END ), 
					    COL38 = (case when (select k_YEAR_EDT FROM #TMP01 where ID=4) < '2014' THEN (SELECT k_GAIN FROM #TMP01 where ID=4) ELSE 0 END ),
					    COL39 = (SELECT k_PER_EDT FROM #TMP01 where ID=5),
					    COL40 = (select k_YEAR_EDT FROM #TMP01 where ID=5), 
					    COL41 = (CASE WHEN (select k_YEAR_EDT FROM #TMP01 where ID=5) >= '2014' THEN (SELECT k_INSUR FROM #TMP01 where ID=5)  ELSE 0 END ), 
					    COL42 = (case when (select k_YEAR_EDT FROM #TMP01 where ID=5) < '2014' THEN (SELECT k_INSUR FROM #TMP01 where ID=5) ELSE 0 END ), 
					    COL43 = (case when (select k_YEAR_EDT FROM #TMP01 where ID=5) < '2014' THEN (SELECT 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((SELECT [B_BEF_M1] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER) ,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((SELECT [B_BEF_M2] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER) ,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((SELECT [B_BEF_M3] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER) ,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([INC_M1]+[INC_M2]+[INC_M3],0),
						  COL7 = ISNULL([B_BEF_M1]+[B_BEF_M2]+[B_BEF_M3],0),
						   COL8 = ISNULL((SELECT [B_BEF_M1]+[B_BEF_M2]+[B_BEF_M3] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER) ,0),
						   COL9 = 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 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_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), '1 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'411'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = isnull([INC_M1],0),
						   COL7 = ISNULL([B_BEF_M1],0),
						   COL8 = ISNULL((SELECT [B_BEF_M1] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER) ,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((SELECT [B_BEF_M2] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER) ,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((SELECT [B_BEF_M3] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER) ,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([INC_M1]+[INC_M2]+[INC_M3],0),
						   COL7 = ISNULL([B_BEF_M1]+[B_BEF_M2]+[B_BEF_M3],0),
						   COL8 = ISNULL((SELECT [B_BEF_M1]+[B_BEF_M2]+[B_BEF_M3] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER) ,0),
						   COL9 = 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),
						   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), '1 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'401'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = isnull([INC_M1],0),
						   COL7 = ISNULL([B_BEF_M1],0),
						   COL8 = ISNULL((SELECT [B_BEF_M1] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER) ,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),
						   COL5 = isnull([INC_M2],0),
						   COL6 = ISNULL([B_BEF_M2],0),
						   COL7 = ISNULL((SELECT [B_BEF_M2] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER) ,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],[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((SELECT [B_BEF_M3] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER) ,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([INC_M1]+[INC_M2]+[INC_M3],0),
						   COL7 = ISNULL([B_BEF_M1]+[B_BEF_M2]+[B_BEF_M3],0),
						   COL8 = ISNULL((SELECT [B_BEF_M1]+[B_BEF_M2]+[B_BEF_M3] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER) ,0),
						   COL9 = 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 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), '1 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'411'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = isnull([INC_M1],0),
						   COL7 = ISNULL([B_BEF_M1],0),
						   COL8 = ISNULL((SELECT [B_BEF_M1] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER) ,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((SELECT [B_BEF_M2] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER) ,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((SELECT [B_BEF_M3] FROM #SZV_ALL WHERE  code = @CODE and [TYPE] = @TYPE and T_DOG = 2 AND PFNUMBER = @PFNUMBER) ,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

		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           
		

		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 = 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))  
										   + (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))   
										   + (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(@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))    
										   + (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))   
										   + (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  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 = 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))    
										   + (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))   
										   + (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(@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))    
										   + (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))   
										   + (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
					
					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(@dDate2)<=YEAR(Date_END) and MONTH(@dDate1) <= MONTH(Date_END) and MONTH(@dDate2) >= MONTH(Date_BEGIN) and [TYPE] = @TYPE1 AND PFNUMBER = @PFNUMBER1 and fm = @FM1
					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 convert(varchar(10),DATE_BEGIN1,104 ) FROM #TMP03 where ID=1 and FM1= @FM1),
						COL11 = (SELECT convert(varchar(10),DATE_END1,104 ) FROM #TMP03 where ID=1 and FM1= @FM1),
						COL12 = (SELECT convert(varchar(10),TU_CODE1 ) FROM #TMP03 where ID=1 and FM1= @FM1) ,
						COL13 = (SELECT convert(varchar(20),OS_CODE1 ) FROM #TMP03 where ID=1 and FM1= @FM1),
						COL14 = (SELECT convert(varchar(10),EX_CODE1 ) FROM #TMP03 where ID=1 and FM1= @FM1), 
						COL15 = (SELECT convert(varchar(100),f_is_dop1 ) FROM #TMP03 where ID=1 and FM1= @FM1),
					    COL16 = (SELECT convert(varchar(10),P_CODE1) FROM #TMP03 where ID=1 and FM1= @FM1), 
					    COL17 = (SELECT convert(varchar(100),f_ud_dop1) FROM #TMP03 where ID=1 and FM1= @FM1), 
					    COL18 = (SELECT convert(varchar(10),DATE_BEGIN1,104 ) FROM #TMP03 where ID=2 and FM1= @FM1), 
					    COL19 = (SELECT convert(varchar(10),DATE_END1,104 ) FROM #TMP03 where ID=2 and FM1= @FM1),
					    COL20 = (SELECT convert(varchar(10),TU_CODE1 ) FROM #TMP03 where ID=2 and FM1= @FM1),
					    COL21 = (SELECT convert(varchar(20),OS_CODE1 ) FROM #TMP03 where ID=2 and FM1= @FM1),
						COL22 = (SELECT convert(varchar(10),EX_CODE1 ) FROM #TMP03 where ID=2 and FM1= @FM1), 
						COL23 = (SELECT convert(varchar(100),f_is_dop1 ) FROM #TMP03 where ID=2 and FM1= @FM1),
					    COL24 = (SELECT convert(varchar(10),P_CODE1) FROM #TMP03 where ID=2 and FM1= @FM1), 
					    COL25 = (SELECT convert(varchar(100),f_ud_dop1) FROM #TMP03 where ID=2 and FM1= @FM1),
					    COL26 = (SELECT convert(varchar(10),DATE_BEGIN1,104 ) FROM #TMP03 where ID=3 and FM1= @FM1), 
					    COL27 = (SELECT convert(varchar(10),DATE_END1,104 ) FROM #TMP03 where ID=3 and FM1= @FM1),
					    COL28 = (SELECT convert(varchar(10),TU_CODE1 ) FROM #TMP03 where ID=3 and FM1= @FM1),
					    COL29 = (SELECT convert(varchar(20),OS_CODE1 ) FROM #TMP03 where ID=3 and FM1= @FM1),
						COL30 = (SELECT convert(varchar(10),EX_CODE1 ) FROM #TMP03 where ID=3 and FM1= @FM1), 
						COL31 = (SELECT convert(varchar(100),f_is_dop1 ) FROM #TMP03 where ID=3 and FM1= @FM1),
					    COL32 = (SELECT convert(varchar(10),P_CODE1) FROM #TMP03 where ID=3 and FM1= @FM1), 
					    COL33 = (SELECT convert(varchar(100),f_ud_dop1) FROM #TMP03 where ID=3 and FM1= @FM1),
					    COL34 = (SELECT convert(varchar(10),DATE_BEGIN1,104 ) FROM #TMP03 where ID=4 and FM1= @FM1), 
					    COL35 = (SELECT convert(varchar(10),DATE_END1,104 ) FROM #TMP03 where ID=4 and FM1= @FM1),
					    COL36 = (SELECT convert(varchar(10),TU_CODE1 ) FROM #TMP03 where ID=4 and FM1= @FM1),
					    COL37 = (SELECT convert(varchar(20),OS_CODE1 ) FROM #TMP03 where ID=4 and FM1= @FM1),
						COL38 = (SELECT convert(varchar(10),EX_CODE1 ) FROM #TMP03 where ID=4 and FM1= @FM1), 
						COL39 = (SELECT convert(varchar(100),f_is_dop1 ) FROM #TMP03 where ID=4 and FM1= @FM1),
					    COL40 = (SELECT convert(varchar(10),P_CODE1) FROM #TMP03 where ID=4 and FM1= @FM1), 
					    COL41 = (SELECT 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 = '713' /*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 = 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))  
										   + (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)) 
										   + (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(@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))  
										   + (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)) 
										   + (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
					
					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 = 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))  
										   + (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)) 
										   + (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(@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))  
										   + (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)) 
										   + (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
					
					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 @dDate1 BETWEEN Date_BEGIN AND DATE_END and [TYPE] = @TYPE1 AND PFNUMBER = @PFNUMBER1 and fm = @FM1
					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 convert(varchar(10),DATE_BEGIN1, 104 ) FROM #TMP04 where ID=1 and FM1= @FM1),
						COL11 = (SELECT convert(varchar(10),DATE_END1, 104 ) FROM #TMP04 where ID=1 and FM1= @FM1),
						COL12 = (SELECT convert(varchar(10),TU_CODE1 ) FROM #TMP04 where ID=1 and FM1= @FM1) ,
						COL13 = (SELECT convert(varchar(20),OS_CODE1 ) FROM #TMP04 where ID=1 and FM1= @FM1),
						COL14 = (SELECT convert(varchar(10),EX_CODE1 ) FROM #TMP04 where ID=1 and FM1= @FM1), 
						COL15 = (SELECT convert(varchar(100),f_is_dop1 ) FROM #TMP04 where ID=1 and FM1= @FM1),
					    COL16 = (SELECT convert(varchar(10),P_CODE1) FROM #TMP04 where ID=1 and FM1= @FM1), 
					    COL17 = (SELECT convert(varchar(100),f_ud_dop1) FROM #TMP04 where ID=1 and FM1= @FM1), 
					    COL18 = (SELECT convert(varchar(10),DATE_BEGIN1 , 104 ) FROM #TMP04 where ID=2 and FM1= @FM1), 
					    COL19 = (SELECT convert(varchar(10),DATE_END1, 104 ) FROM #TMP04 where ID=2 and FM1= @FM1),
					    COL20 = (SELECT convert(varchar(10),TU_CODE1 ) FROM #TMP04 where ID=2 and FM1= @FM1),
					    COL21 = (SELECT convert(varchar(20),OS_CODE1 ) FROM #TMP04 where ID=2 and FM1= @FM1),
						COL22 = (SELECT convert(varchar(10),EX_CODE1 ) FROM #TMP04 where ID=2 and FM1= @FM1), 
						COL23 = (SELECT convert(varchar(100),f_is_dop1 ) FROM #TMP04 where ID=2 and FM1= @FM1),
					    COL24 = (SELECT convert(varchar(10),P_CODE1) FROM #TMP04 where ID=2 and FM1= @FM1), 
					    COL25 = (SELECT convert(varchar(100),f_ud_dop1) FROM #TMP04 where ID=2 and FM1= @FM1),
					    COL26 = (SELECT convert(varchar(10),DATE_BEGIN1, 104 ) FROM #TMP04 where ID=3 and FM1= @FM1), 
					    COL27 = (SELECT convert(varchar(10),DATE_END1, 104 ) FROM #TMP04 where ID=3 and FM1= @FM1),
					    COL28 = (SELECT convert(varchar(10),TU_CODE1 ) FROM #TMP04 where ID=3 and FM1= @FM1),
					    COL29 = (SELECT convert(varchar(20),OS_CODE1 ) FROM #TMP04 where ID=3 and FM1= @FM1),
						COL30 = (SELECT convert(varchar(10),EX_CODE1 ) FROM #TMP04 where ID=3 and FM1= @FM1), 
						COL31 = (SELECT convert(varchar(100),f_is_dop1 ) FROM #TMP04 where ID=3 and FM1= @FM1),
					    COL32 = (SELECT convert(varchar(10),P_CODE1) FROM #TMP04 where ID=3 and FM1= @FM1), 
					    COL33 = (SELECT convert(varchar(100),f_ud_dop1) FROM #TMP04 where ID=3 and FM1= @FM1),
					    COL34 = (SELECT convert(varchar(10),DATE_BEGIN1, 104 ) FROM #TMP04 where ID=4 and FM1= @FM1), 
					    COL35 = (SELECT convert(varchar(10),DATE_END1, 104 ) FROM #TMP04 where ID=4 and FM1= @FM1),
					    COL36 = (SELECT convert(varchar(10),TU_CODE1 ) FROM #TMP04 where ID=4 and FM1= @FM1),
					    COL37 = (SELECT convert(varchar(20),OS_CODE1 ) FROM #TMP04 where ID=4 and FM1= @FM1),
						COL38 = (SELECT convert(varchar(10),EX_CODE1 ) FROM #TMP04 where ID=4 and FM1= @FM1), 
						COL39 = (SELECT convert(varchar(100),f_is_dop1 ) FROM #TMP04 where ID=4 and FM1= @FM1),
					    COL40 = (SELECT convert(varchar(10),P_CODE1) FROM #TMP04 where ID=4 and FM1= @FM1), 
					    COL41 = (SELECT 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 = '713'

					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 * from #SZV_ALL order BY [TYPE],CODE,[FM],[IM],[OT],[PFNUMBER]	
			
		SELECT DISTINCT * FROM #TMP3 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 @dDate1 BETWEEN Date_BEGIN AND DATE_END
		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


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 142

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 @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 = 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 '03' WHEN 2 THEN '06' WHEN 3 THEN '09' ELSE '12' 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, 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	
			

					
			--- --- доп тариф 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 + '>'
				/***************************/	
			--- доп тариф 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(4), SUM_BASE NUMERIC(18,2), SUM_NACH NUMERIC(18,2), KOL_ZL NUMERIC(5), 
			NAME_FILE VARCHAR(254))

		CREATE TABLE #TAB3 (ROW_CODE VARCHAR(4), 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(4), 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(4), 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(4), 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(3), 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 ([TYPE],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 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	

	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
 

--exec SA_RSV1_EXPORT_0700_2014 41964

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
				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 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.04.'+@YEAR_BEGIN+' ПО 30.06.'+@YEAR_BEGIN
													WHEN '3' THEN 'С 01.07.'+@YEAR_BEGIN+' ПО 30.09.'+@YEAR_BEGIN
													WHEN '4' THEN 'С 01.10.'+@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.04.'+@YEAR_EDT+' ПО 30.06.'+@YEAR_EDT
																					WHEN '3' THEN 'С 01.07.'+@YEAR_EDT+' ПО 30.09.'+@YEAR_EDT
																					WHEN '4' THEN 'С 01.10.'+@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.04.'+@YEAR_BEGIN_R+' ПО 30.06.'+@YEAR_BEGIN_R
																											WHEN '3' THEN 'С 01.07.'+@YEAR_BEGIN_R+' ПО 30.09.'+@YEAR_BEGIN_R
																											WHEN '4' THEN 'С 01.10.'+@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.04.'+@YEAR_EDT_R+' ПО 30.06.'+@YEAR_EDT_R
																										WHEN '3' THEN 'С 01.07.'+@YEAR_EDT_R+' ПО 30.09.'+@YEAR_EDT_R
																										WHEN '4' THEN 'С 01.10.'+@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 '1' 
																									WHEN CODE_STR = '402' OR CODE_STR ='412' OR CODE_STR ='422' THEN '2'
																									ELSE '3'  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 NGROUP = @NOM_PACH_R*/
										
											
											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 NGROUP = @NOM_PACH_R*/	 
																	AND CODE_STR IN ('400','410','420')

												
											IF UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'КОРРЕКТИРУЮЩАЯ'
											begin
												INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT  @lcFNAME, 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) + '</СведенияОкорректировках>'	
													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, 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) + '</СведенияОкорректировках>'	
													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, 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) + '</СведенияОкорректировках>'	
													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, 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) + '</СведенияОкорректировках>'	
													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, 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) + '</СведенияОкорректировках>'	
													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, SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																			 SPACE(4) + '<НомерСтроки>' + '6' + '</НомерСтроки>' + CHAR(10)+
																			 SPACE(4) + '<ТипСтроки>'+'ИТОГ'+'</ТипСтроки>' + CHAR(10)+
																			 SPACE(4) + '<Квартал>' +	'' + '</Квартал>' + CHAR(10)+
																			 SPACE(4) + '<Год>' + '' + '</Год>' + 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) + '</СведенияОкорректировках>'	
													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  
										
											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 FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
													
													 
															
																						
													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)
														+						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)
														+ 					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  ='713'													

													/*вторая строка*/
													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) + '<НомерСтроки>' + '1' + '</НомерСтроки>' + 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)
														+						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)
														+ 					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  ='713'				
													
													/*третья строка*/
													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) + '<НомерСтроки>' + '1' + '</НомерСтроки>' + 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)
														+						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)
														+ 					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  ='713'	

													/*четвертая строка*/
													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) + '<НомерСтроки>' + '1' + '</НомерСтроки>' + 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)
														+						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)
														+ 					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  ='713'	
											
												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.[BK_CREATE_REST_DEL_DOC]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_CREATE_REST_DEL_DOC]

GO
-- ******************* Очистка Сметы-КС ************************
--- !!!ПЕРЕД ВЫПОЛНЕНИЕМ ОБЯЗАТЕЛЬНО СДЕЛАТЬ РЕЗЕРВНУЮ КОПИЮ!!! ---
CREATE PROCEDURE dbo.BK_CREATE_REST_DEL_DOC
	(@DATE_REST DATETIME = '20120101',
	@DEP_LINK	INT = -15)	-- Дата, на которую будут сформированы входящие остатки
AS
BEGIN
	DECLARE
		@DATE_REST_SAVE DATETIME,

		@ADM_DATE_BEGIN DATETIME,
		@ADM_DATE_END DATETIME,
		
		@ADM_DATE_START DATETIME,

		@intOBJ_TYPE_OPER	INT,
		
		@MinDate Datetime,
		@MaxDate Datetime,
		@Task int,
		@BB datetime,
		@BE datetime,
		@BB0	DATETIME

	SELECT
		@ADM_DATE_BEGIN = BEGINDATE,
		@ADM_DATE_END = ENDDATE
	FROM dbo.ADMIN_INFO
	
	SET @ADM_DATE_START = dbo.RestGetStartDate ()
	
	-- Изменяем рабочий период
	Select
		@Task = LINK
	FROM dbo.S_OBJECTS
	Where CODE = 'SMETA'

	SELECT
		@BB = '19000101',
		@BE = '21001231'
		
	SET @BB0 = DATEADD (DAY, -1, @BB)
	
	EXECUTE dbo.X_ADMIN_SET_START_DATE @BB0
	
	EXECUTE dbo.I_SET_ADMIN_DATE @Task, @BB, @BB, @BE

	SELECT
		@intOBJ_TYPE_OPER = SO.LINK
	FROM dbo.S_OBJECTS SO
	WHERE SO.CODE = 'SHABLON_DOCUMENTS_PROV'

	-- Организации --
	DECLARE @TAB_DEP TABLE 
		(LINK	INT)

	-- В обработку включаем все организации, по которым есть обороты, остатки --
	IF ISNULL (@DEP_LINK, 0) = -15
		INSERT INTO @TAB_DEP
			(LINK)
		SELECT
			DEP_LINK
		FROM dbo.SALDO
		WHERE [DATE] < = @DATE_REST

		UNION

		SELECT
			DEP
		FROM dbo.G_PROV
		WHERE DATE_PROV < = @DATE_REST
	ELSE
		INSERT INTO @TAB_DEP
			(LINK)
		SELECT
			@DEP_LINK

	-- Остатки --
	SET @DATE_REST_SAVE = DATEADD (DAY, -1, @DATE_REST)
	
	INSERT INTO dbo.SALDO ([DATE], ACCOUNT, D_SUMMA, K_SUMMA, R_SUMMA, D_QUANTITY, K_QUANTITY,
		ISOBOROT, KBK, EKR, DEP, SUB, EMP, NOMEN, INV, KAU, DEP_ACC, TMC, INDATE, SGU,
		AP1, AP2, AP3, DEP_LINK, PRICE)
	SELECT
		@DATE_REST_SAVE, T1.ACCOUNT, T1.D_SUMMA, T1.K_SUMMA, T1.R_SUMMA, T1.D_QUANTITY, T1.K_QUANTITY,
		 5, T1.KBK, T1.EKR, T1.DEP, T1.SUB, T1.EMP, T1.NOMEN, T1.INV, T1.KAU, T1.DEP_ACC, T1.TMC, T1.INDATE, T1.SGU,
		T1.AP1, T1.AP2, T1.AP3, T1.DEP_LINK, T1.PRICE
	FROM dbo.ARestTableByDate (@DATE_REST, DEFAULT) T1
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = T1.DEP_LINK)

	-- Удаляем операции --
	DELETE G1
	FROM dbo.G_PROV1 G1 
	INNER JOIN dbo.G_PROV G ON (G1.LINK_UP = G.LINK)
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = G.DEP)
	WHERE G.DATE_PROV < @DATE_REST
		AND G.[OBJECT] <> @intOBJ_TYPE_OPER

	-- Чистим остатки --
	DELETE T1
	FROM dbo.SALDO T1
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = T1.DEP_LINK)
	WHERE T1.ISOBOROT <> 5
		AND T1.[DATE] < @DATE_REST
		
	UPDATE T1
	SET ISOBOROT = 2
	FROM dbo.SALDO T1
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = T1.DEP_LINK)
	WHERE T1.ISOBOROT = 5
		AND T1.[DATE] < @DATE_REST

	--- УДАЛЕНИЕ ДОКУМЕНТОВ ОСНОВАНИЙ ---
	UPDATE T1
	SET OSNOV = NULL
	FROM dbo.G_PROV G
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = G.DEP)
	INNER JOIN dbo.G_PROV_OS1 T1 ON (T1.LINK_OS1 = G.LINK)
	WHERE T1.OSNOV IS NOT NULL
		AND G.[DATE] < @DATE_REST

	UPDATE T1
	SET DOC_LINK = NULL
	FROM dbo.G_PROV G
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = G.DEP)
	INNER JOIN dbo.CREDIT_HEAD T1 ON (T1.LINK = G.LINK)
	WHERE G.[DATE] < @DATE_REST
		AND T1.DOC_LINK IS NOT NULL

	UPDATE T1
	SET LINK_OSNOV = NULL
	FROM dbo.G_PROV G
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = G.DEP)
	INNER JOIN dbo.FINANSE_HEAD T1 ON (T1.LINK = G.LINK)
	WHERE G.[DATE] < @DATE_REST
		AND T1.LINK_OSNOV IS NOT NULL

	UPDATE T1
	SET AP1 = NULL
	FROM dbo.G_PROV G
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = G.DEP)
	INNER JOIN dbo.DOC_ANALIT_TABLE T1 ON (T1.LINK_DOC = G.LINK)
	WHERE G.[DATE] < @DATE_REST
		AND T1.AP1 IS NOT NULL

	UPDATE T1
	SET OSNOV = NULL
	FROM dbo.G_PROV G
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = G.DEP)
	INNER JOIN dbo.OUT_TABLE_ROW OTR ON (OTR.LINK_UP = G.LINK)
	INNER JOIN dbo.G_AVANSE_TABLE T1 ON (T1.LINK_UP = OTR.LINK)
	WHERE G.[DATE] < @DATE_REST
		AND T1.OSNOV IS NOT NULL

	UPDATE T1
	SET
		DOG_LINK = NULL,
		GZ_LINK = NULL
	FROM dbo.G_PROV G
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = G.DEP)
	INNER JOIN dbo.FINANSE_CONTRACT_HEAD T1 ON (T1.LINK_G_PROV = G.LINK)
	WHERE G.[DATE] < @DATE_REST
		AND (T1.DOG_LINK IS NOT NULL
			OR T1.GZ_LINK  IS NOT NULL)

	DELETE T1
	FROM dbo.G_PROV G
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = G.DEP)
	INNER JOIN dbo.G_PROV_OSNOV T1 ON (T1.DOC_LINK = G.LINK)
	WHERE G.[DATE] < @DATE_REST
		AND T1.OSNOV IS NOT NULL

	DELETE T1
	FROM dbo.G_PROV G
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = G.DEP)
	INNER JOIN dbo.ZAYAVKA_KR_OSNOV T1 ON (T1.LINK_UP = G.LINK)
	WHERE G.[DATE] < @DATE_REST
		AND T1.LINK_OSNOV IS NOT NULL

	-- Используемые документы основания --
	DECLARE @OSNOV_USED TABLE (LINK INT)

	INSERT INTO @OSNOV_USED
	SELECT OSNOV
	FROM dbo.G_PROV_OS1 T1
	WHERE T1.OSNOV IS NOT NULL
	UNION
	SELECT T1.DOC_LINK 
	FROM dbo.CREDIT_HEAD T1 
	WHERE T1.DOC_LINK IS NOT NULL
	UNION
	SELECT LINK_OSNOV
	FROM dbo.FINANSE_HEAD T1 
	WHERE T1.LINK_OSNOV IS NOT NULL
	UNION
	SELECT AP1
	FROM dbo.DOC_ANALIT_TABLE T1 
	WHERE AP1 IS NOT NULL
	UNION
	SELECT OSNOV
	FROM dbo.G_AVANSE_TABLE T1 
	WHERE OSNOV IS NOT NULL
	UNION
	SELECT AP1
	FROM dbo.SALDO
	WHERE AP1 IS NOT NULL
	UNION
	SELECT AP1
	FROM dbo.G_PROV_AP
	WHERE AP1 IS NOT NULL
	UNION
	SELECT OSNOV
	FROM dbo.G_PROV_OSNOV 
	WHERE OSNOV IS NOT NULL
	UNION
	SELECT LINK_OSNOV 
	FROM dbo.ZAYAVKA_KR_OSNOV
	WHERE LINK_OSNOV IS NOT NULL
	UNION
	SELECT
		T1.DOG_LINK
	FROM dbo.FINANSE_CONTRACT_HEAD T1 
	WHERE T1.DOG_LINK IS NOT NULL 
	UNION
	SELECT
		T1.GZ_LINK
	FROM dbo.FINANSE_CONTRACT_HEAD T1 
	WHERE T1.GZ_LINK IS NOT NULL 
	
	-- УДАЛЕНИЕ ДОКУМЕНТОВ --
	UPDATE T1
	SET LINK_REESTR = NULL
	FROM dbo.G_PROV G
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = G.DEP)
	INNER JOIN dbo.FINANSE_HEAD T1 ON (T1.LINK = G.LINK)
	WHERE G.[DATE] < @DATE_REST
		AND T1.LINK_REESTR IS NOT NULL

	UPDATE T1
	SET LINK_REESTR = NULL
	FROM dbo.G_PROV G
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = G.DEP)
	INNER JOIN dbo.FINANSE_PLAN T1 ON (T1.LINK = G.LINK)
	WHERE G.[DATE] < @DATE_REST
		AND T1.LINK_REESTR IS NOT NULL

	DELETE T1
	FROM dbo.G_PROV G
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = G.DEP)
	INNER JOIN dbo.GZ_EXPORT_EVENTS T1 ON (T1.LINK_G = G.LINK)
	WHERE G.[DATE] < @DATE_REST

	UPDATE T1
	SET LINK_CONTRACT = NULL
	FROM dbo.G_PROV G
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = G.DEP)
	INNER JOIN dbo.GZ_REESTR T1 ON (T1.LINK = G.LINK)
	WHERE G.[DATE] < @DATE_REST
		AND T1.LINK_CONTRACT IS NOT NULL

	DELETE OTR
	FROM dbo.G_PROV G
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = G.DEP)
	INNER JOIN dbo.OUT_TABLE_ROW OTR ON (OTR.LINK_UP = G.LINK)
	WHERE G.[DATE] < @DATE_REST

	UPDATE T1
	SET LINK_G = NULL
	FROM dbo.G_PROV G
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = G.DEP)
	INNER JOIN dbo.UVED_U_DOC T1 ON (T1.LINK_UP = G.LINK)
	WHERE G.[DATE] < @DATE_REST
		AND T1.LINK_G IS NOT NULL

	-- Используемые документы --
	DECLARE @G_PROV_USED TABLE (LINK INT)

	INSERT INTO @G_PROV_USED
	SELECT LINK_REESTR
	FROM dbo.FINANSE_HEAD T1 
	WHERE T1.LINK_REESTR IS NOT NULL

	UNION

	SELECT LINK_REESTR 
	FROM dbo.FINANSE_PLAN T1 
	WHERE T1.LINK_REESTR IS NOT NULL

	UNION

	SELECT LINK_G
	FROM dbo.GZ_EXPORT_EVENTS T1 
	WHERE LINK_G IS NOT NULL

	UNION

	SELECT LINK_CONTRACT
	FROM dbo.GZ_REESTR T1
	WHERE T1.LINK_CONTRACT IS NOT NULL

	UNION

	SELECT G_PROV
	FROM dbo.OUT_TABLE_G_PROV
	WHERE G_PROV IS NOT NULL 

	UNION

	SELECT T1.LINK_G 
	FROM dbo.UVED_U_DOC T1 
	WHERE T1.LINK_G IS NOT NULL

	DELETE G
	FROM dbo.G_PROV G
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = G.DEP)
	WHERE G.[DATE] < @DATE_REST
		AND G.OBJECT <> @intOBJ_TYPE_OPER
		AND NOT EXISTS (SELECT 1
				FROM dbo.OSNOV OSN
				INNER JOIN @OSNOV_USED T1 ON (T1.LINK = OSN.LINK)
				WHERE OSN.LINK_G_PROV = G.LINK)
		AND NOT EXISTS (SELECT 1
				FROM @G_PROV_USED T1
				WHERE T1.LINK = G.LINK)

	-- Удаление БО --
	DELETE JB
	FROM JURN_BO JB
	INNER JOIN dbo.OSNOV OSN ON (OSN.LINK = JB.LINK_DOC)
	INNER JOIN G_PROV G ON (G.LINK = OSN.LINK_G_PROV)
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = G.DEP)
	WHERE JB.DATE_DOC < @DATE_REST

	-- Удалить прочие документы основания --
	DELETE T0
	FROM dbo.OSNOV_OTHER T0
	INNER JOIN @TAB_DEP DEP ON (DEP.LINK = T0.DEP)
	WHERE T0.[DATE] < @DATE_REST
		AND NOT EXISTS (SELECT 1
				FROM dbo.OSNOV OSN
				INNER JOIN @OSNOV_USED T1 ON (T1.LINK = OSN.LINK)
				WHERE OSN.LINK_OTHER = T0.LINK)
	-- --
	SELECT
		@ADM_DATE_BEGIN = ISNULL (@ADM_DATE_BEGIN, @DATE_REST),
		@ADM_DATE_END =	ISNULL (@ADM_DATE_END, dbo.DateEndOFYear (@ADM_DATE_BEGIN)) ,
		@ADM_DATE_START = ISNULL (@ADM_DATE_START, '19000101')

	exec dbo.X_ADMIN_SET_START_DATE
		@ADM_DATE_START

	EXECUTE dbo.I_SET_ADMIN_DATE
			@Task,
			@ADM_DATE_BEGIN,
			@ADM_DATE_BEGIN,
			@ADM_DATE_END
END



GO


GRANT EXECUTE ON dbo.[BK_CREATE_REST_DEL_DOC] TO PUBLIC

GO


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


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

-- Печать авансового отчета --
CREATE PROCEDURE dbo.BK_PRINTDOC_AVANSE_REP
	@intLINK_DOC	INT
AS
BEGIN
	DECLARE
		@intPrintKBK TINYINT,
		@intPrintSGU TINYINT

	-- Титульный лист --
	DECLARE @TAB_TITLE TABLE 
		(
		LINK		INT,
		DOC_NUM		VARCHAR (60),
		DOC_DATE	DATETIME,
		WHY_AVA		VARCHAR (254),
		KA_CODE		VARCHAR (30),

		GET_SUM		NUMERIC (28,2),
		PREV_SUM1	NUMERIC (28,2),
		PREV_SUM2	NUMERIC (28,2),
		TOT_SUM		NUMERIC (28,2),
		REST_SUM	NUMERIC (28,2),
		OUT_SUM		NUMERIC (28,2),

		CNT_DOC		NUMERIC (5),
		CNT_SHEET	NUMERIC (5),
	
		EMP_CODE	VARCHAR (30),
		EMP_NAME	VARCHAR (254),
		EMPL_SIGN	VARCHAR (254),
		SUB_NAME	VARCHAR (254),
		POST_NAME	VARCHAR (254),
		EMP_FIO		VARCHAR (254),
		
		DEP_OKPO	VARCHAR (30),
		DEP_NAME	VARCHAR (254)
		)

	INSERT INTO @TAB_TITLE
	SELECT
		DOC.LINK,
		DOC.NUMBER,
		DOC.[DATE],
		ISNULL (DOC.[TARGET], ''),
		ISNULL (DOC.KTACCOUNT, ''),
		
		ISNULL (DOC.AVANSESUMMA, 0),
		CASE
			WHEN ISNULL (DOC.PREVSUMMA, 0) >= 0 THEN ISNULL (DOC.PREVSUMMA, 0)
			ELSE 0.00
		END,
		CASE	
			WHEN ISNULL (DOC.PREVSUMMA, 0) < 0 THEN ABS (ISNULL (DOC.PREVSUMMA, 0))
			ELSE 0.00
		END,
		ISNULL (DOC.ITOG_SUM, 0.00),
		ISNULL (DOC.REST_SUM, 0.00),
		ISNULL (DOC.RASHOD_SUM, 0.00),

		ISNULL (DOC.DOC, 0.00),
		ISNULL (DOC.PAGES, 0.00),

		DOC.EMP_CODE,
		DOC.EMP_NAME,
		CASE
			WHEN DOC.[OPTION] = 1 THEN dbo.BK_Get_EMPL_Signature (DOC.EMP_LINK, DEFAULT)
			WHEN DOC.[OPTION] = 2 THEN dbo.BK_Get_PERSON_Signature (DOC.EMP_LINK, DEFAULT)
		END,
		CASE
			WHEN DOC.[OPTION] = 1 THEN EMP.SUBDIV_NAME
			WHEN DOC.[OPTION] = 2 THEN ''
		END,	
		CASE
			WHEN DOC.[OPTION] = 1 THEN EMP.POST_NAME
			WHEN DOC.[OPTION] = 2 THEN ''
		END,
		CASE
			WHEN DOC.[OPTION] = 1 THEN EMP.FIO
			WHEN DOC.[OPTION] = 2 THEN LTRIM (RTRIM (PERS.FM)) + SPACE (1) + LTRIM (RTRIM (PERS.IM)) + SPACE (1) + LTRIM (RTRIM (PERS.OT))
		END,
		DEP.OKPO,
		dbo.BK_GET_PRINT_DEP_NAME (DEP.LINK)
	FROM dbo.BV_DOC_AVANSE_REP DOC
	INNER JOIN dbo.DEPARTMENTS DEP ON (DEP.LINK = DOC.DEP_LINK)
	LEFT JOIN dbo.KU_EMPL_PLACING EMP ON (DOC.[OPTION] = 1
		AND EMP.LINK = DOC.EMP_LINK)
	LEFT JOIN dbo.PERSON PERS ON (DOC.[OPTION] = 2
		AND PERS.LINK = DOC.EMP_LINK)
	WHERE DOC.LINK = @intLINK_DOC

	-- КО на перерасход\возврат --
	SELECT
		@intPrintKBK = PRN_KBK,
		@intPrintSGU = PRN_SGU
	FROM dbo.BK_GET_PRINT_NASTRDOC ('BV_DOC_AVANSE_REP')

	DECLARE @TAB_KO1 TABLE
		(	
		LINK_AO	INT,
		KO_NUM	VARCHAR (30),
		KO_DATE VARCHAR (10), 
		ACCT_CODE	VARCHAR (60),
		ACCT_GR	VARCHAR (20),
		PKO_SUM	NUMERIC (28,4),
		RKO_SUM NUMERIC (28,4)
		)

	INSERT INTO @TAB_KO1		
	SELECT
		T1.G_PRIMARY,
		T1.NUMBER,
		CONVERT (VARCHAR (10), T1.[DATE], 104),
		dbo.BK_GetAcctFullCode1 (GAP.ACCOUNT, GAP.KBK, GAP.SGU,
			@intPrintKBK, @intPrintSGU),
		SA.CODE,
		CASE
			WHEN T1.DOC_CODE = 'DOCUMENTS_PKO' THEN G2.SUMMA  ELSE 0 
		END,
		CASE
			WHEN T1.DOC_CODE = 'DOCUMENTS_RKO' THEN G2.SUMMA  ELSE 0 
		END
	FROM dbo.XK_GetTable_Doc_FOREIGN (@intLINK_DOC) T1
	INNER JOIN dbo.G_PROV1 G1 ON (G1.LINK_UP = T1.LINK)
	INNER JOIN dbo.G_PROV2 G2 ON (G2.LINK_UP = G1.LINK)
	INNER JOIN dbo.G_PROV_AP GAP ON (GAP.LINK_UP = G2.LINK)
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = GAP.ACCOUNT
			AND SA.cSINTH = '208')
	WHERE T1.DOC_CODE IN ('DOCUMENTS_PKO', 'DOCUMENTS_RKO')

	--- Проводки АО (на титульную страницу) ---
	DECLARE @TAB_TITLE_PROV TABLE
			(
			DB_ACCT	VARCHAR (60),
			KR_ACCT	VARCHAR (60),
			SUM_PROV NUMERIC (28,2)
			)
			
	IF EXISTS (SELECT * FROM dbo.BV_DOC_AO_OPTIONS WHERE ISNULL (TITLE_PROV, 0) = 1)
		-- Проводки из документов на выдачу аванса --
		INSERT INTO @TAB_TITLE_PROV		
		SELECT
			ISNULL (dbo.BK_GetAcctFullCode1 (GAP_D.ACCOUNT, GAP_D.KBK, GAP_D.SGU,
						@intPrintKBK, @intPrintSGU), ''),
			ISNULL (dbo.BK_GetAcctFullCode1 (GAP_K.ACCOUNT, GAP_K.KBK, GAP_K.SGU,
						@intPrintKBK, @intPrintSGU), ''),
			ISNULL (G2.SUMMA, 0)
		FROM dbo.DOC_AO_RKO_TABLE T1
		INNER JOIN dbo.OSNOV OSNOV ON (OSNOV.LINK = T1.OSNOV)
		INNER JOIN dbo.G_PROV G ON (G.LINK = OSNOV.LINK_G_PROV)
		INNER JOIN dbo.G_PROV1 G1 ON (G1.LINK_UP = G.LINK)
		INNER JOIN dbo.G_PROV2 G2 ON (G2.LINK_UP = G1.LINK)
		LEFT JOIN dbo.G_PROV_AP GAP_D ON (GAP_D.LINK_UP = G2.LINK
			AND GAP_D.DB_KR = 0)
		LEFT JOIN dbo.G_PROV_AP GAP_K ON (GAP_K.LINK_UP = G2.LINK
			AND GAP_K.DB_KR = 1)
		WHERE T1.LINK_UP = @intLINK_DOC
	ELSE
		-- Проводки из авансового отчета --
		INSERT INTO @TAB_TITLE_PROV		
		SELECT
			ISNULL (ACCT_CD_D, ''),
			ISNULL (ACCT_CD_K, ''),
			ISNULL (SUMMA, 0)
		FROM dbo.BK_PrintDocProv (@intLINK_DOC, DEFAULT)

	SELECT
		*,
		(SELECT
			SUM (SUM_PROV)
		FROM @TAB_TITLE_PROV) AS SUM_PROV0
	FROM @TAB_TITLE

	SELECT
		T1.EMP_NAME, 
		T1.DOC_NUM AS DOC_NUM,
		CONVERT (VARCHAR (10), T1.DOC_DATE, 104) AS DOC_DATE, 
		T1.CNT_DOC AS CNT_DOC, 
		ISNULL (T1.OUT_SUM, 0.00) AS OUT_SUM,
		ISNULL (T2.ACCT_CODE, '') AS ACCT_KO, 
		ISNULL (T2.PKO_SUM, 0.00) AS PKO_SUM, 
		ISNULL (T2.RKO_SUM, 0.00) AS RKO_SUM, 
		ISNULL (T2.KO_NUM, '') AS KO_NUM, 
		ISNULL (T2.KO_DATE, '') AS KO_DATE, 
		0 AS T0
	FROM @TAB_TITLE T1 
	LEFT OUTER JOIN @TAB_KO1 T2 ON (T2.LINK_AO = T1.LINK) 
	WHERE T1.LINK = @intLINK_DOC 

	SELECT
		DB_ACCT,
		KR_ACCT,
		SUM (SUM_PROV) AS SUM_PROV
	FROM @TAB_TITLE_PROV
	GROUP BY
		DB_ACCT,
		KR_ACCT

--- Оборотная сторона ---
	SELECT 
		ISNULL (T1.NUMBER, 0) AS NUM_POS,
		ISNULL (CONVERT (VARCHAR (10), (T1.DATEDOC), 104), '') AS D_DATE,
		ISNULL (T1.NUMDOC, '') AS D_NUM,
		ISNULL (T1.NAMEDOC, '') AS D_NAME,
		ISNULL (T1.SUMREPORT, 0.00) AS SUMMA1,
		ISNULL (T1.SUMACCEPTED, 0.00) AS SUMMA2,
		COALESCE (T3.ACCT_CD_D, T1.DTACCOUNT, '') AS D_ACCT,
		COALESCE (T3.ACCT_CD_K, T1.KTACCOUNT, '') AS K_ACCT,
		T2.EMP_NAME AS E_NAME, 
		T2.EMPL_SIGN AS E_SIGN,
		CASE
			WHEN T2.REST_SUM > 0 THEN T2.REST_SUM
			ELSE 0.00
		END	 AS REST_D,
		CASE
			WHEN T2.REST_SUM < 0 THEN ABS (T2.REST_SUM)
			ELSE 0.00
		END AS REST_K 
	FROM dbo.BK_DOC_TABLE_AO_FN (@intLINK_DOC) T1
	INNER JOIN @TAB_TITLE T2 ON (T2.LINK = T1.LINK_UP)
	LEFT JOIN dbo.BK_PrintDocProv (@intLINK_DOC, DEFAULT) T3 ON (T3.LINK_G1 = T1.LINK_OPER)

END

GO

GRANT EXECUTE ON dbo.[BK_PRINTDOC_AVANSE_REP] TO PUBLIC

GO

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

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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
--[dbo].SD_REP_SVOD2 '20130101', '20130131', 1, 0, '', 0, '', 0
CREATE    PROCEDURE dbo.SD_REP_SVOD2
	@varKSstart_date DATETIME, @varKSEND_DATE DATETIME,	
	@varKSnMode int,
	@varKSnMode1 int, -- в разрезе категорий работников	 (инвалиды , наемные рабочие и т.д.)						
	@varKScVal1 char(1), @varKSnOtborLink1 int,	
	@varKScVal2 char(1), @varKSnOtborLink2 int	
AS
BEGIN

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output

	CREATE TABLE #EMPLS(LINK_EMPL INT)
	IF LEN(@varKScVal1) <> 0 
		INSERT INTO #EMPLS
		SELECT RECORD FROM OBJECT_VAR_EMPL WHERE LINK_UP = @varKSnOtborLink1
	ELSE
		INSERT INTO #EMPLS
		SELECT E.LINK FROM dbo.EMPL E where E.DEP_LINK = @DEP_LINK
				

	SELECT --По сотрудникам
		SJC.LINK_PAYS,
		SJC.TYP_OPER, 
		[CODE] = SJC.CODE_PAYS,
		[NAME] = SJC.NAME_PAYS,
		[HOURS] = SUM(SJC.HOURS),
		[DAYS] = SUM(SJC.DAYS),
		[SUM_PAY] = SUM(CASE WHEN SJC.TYP_OPER = 1 OR SJC.TYP_OPER = 3 THEN SJC.SUMMA ELSE 0 END),
		[SUM_TAX] = SUM(CASE WHEN SJC.TYP_OPER = 2 THEN SJC.SUMMA ELSE 0 END),
		COALESCE(EKR.CODE,'') as EKR_CODE,
		LINK_KAT = CASE when @varKSnMode1 = 1	then sp.link else  0 end,
		NAME_KAT = CASE when @varKSnMode1 = 1	then sp.NAME else  '' end,	
		CODE_KAT = CASE when @varKSnMode1 = 1	then sp.CODE else  '' end	
	INTO #TMP
	FROM dbo.S_J_C_Short SJC inner join #EMPLS E on SJC.LINK_EMPL = E.LINK_EMPL
		inner join dbo.kosgu EKR on EKR.link = LINK_EKR

		INNER JOIN dbo.SAL_SFIN F ON F.LINK = sjc.LINK_VKR
		LEFT JOIN dbo.pers_invalid I ON sjc.LINK_FACE = I.PERS_LINK AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,month(@varKSEND_DATE),year(@varKSEND_DATE))) BETWEEN I.DATE_BEGIN AND COALESCE(I.DATE_END,'29990101')
		left join dbo.SA_PFR_KATEG sp on  (CASE WHEN I.LINK IS NULL THEN (F.ENVD + 1) ELSE 3 END)	= sp.link2 	 and sp.yEND >= year(@varKSEND_DATE)	
	WHERE 
		SJC.LINK_DEP = @DEP_LINK
		AND SJC.PERIOD_BEGIN >= @varKSstart_date 
		AND SJC.PERIOD_END <= @varKSEND_DATE
		AND ( (@varKSnMode = 1 AND TYP_OPER <3 ) OR (@varKSnMode = 2 AND TYP_OPER = 3))
		AND (
			LEN(@varKScVal2) = 0
			OR SJC.LINK_VKR IN (SELECT RECORD FROM dbo.OBJECT_VAR_SAL_SFIN WHERE LINK_UP = @varKSnOtborLink2 )
		)
		
	GROUP BY LINK_PAYS, TYP_OPER, CODE_PAYS, NAME_PAYS, COALESCE(EKR.CODE,''), (case when @varKSnMode1 = 1 then sp.link else 0 end) , (case when @varKSnMode1 = 1 then sp.NAME else  '' end) ,(case when @varKSnMode1 = 1 then sp.CODE else  '' end)  
	UNION
	SELECT --По Внештатникам
		LINK_PAYS,
		TYP_OPER, 
		[CODE] = CODE_PAYS,
		[NAME] = NAME_PAYS,
		[HOURS] = SUM(HOURS),
		[DAYS] = SUM(DAYS),
		[SUM_PAY] = SUM(CASE WHEN TYP_OPER = 1 OR TYP_OPER = 3 THEN SUMMA ELSE 0 END),
		[SUM_TAX] = SUM(CASE WHEN TYP_OPER = 2 THEN SUMMA ELSE 0 END),
		COALESCE(EKR.CODE,'') as EKR_CODE,
		LINK_KAT = (CASE when @varKSnMode1 = 1	then sp.link else  0 end),
		NAME_KAT = CASE when @varKSnMode1 = 1	then sp.NAME else  '' end,
		CODE_KAT = CASE when @varKSnMode1 = 1	then sp.CODE else  '' end		
	FROM S_J_C_Short SJC inner join dbo.kosgu EKR on EKR.link = LINK_EKR
		INNER JOIN dbo.SAL_SFIN F ON F.LINK = sjc.LINK_VKR
		LEFT JOIN dbo.pers_invalid I ON sjc.LINK_FACE = I.PERS_LINK AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,SJC.MONTH_END,SJC.MONTH_END)) BETWEEN I.DATE_BEGIN AND COALESCE(I.DATE_END,'29990101')
		left join dbo.SA_PFR_KATEG sp on  (CASE WHEN I.LINK IS NULL THEN (F.ENVD + 1) ELSE 3 END)	= sp.link2 	 and sp.yEND >= year(@varKSEND_DATE)	
	WHERE 
		SJC.LINK_DEP = @DEP_LINK
		AND COALESCE(SJC.LINK_EMPL,0) = 0 AND COALESCE(SJC.LINK_FACE,0) = 0 AND COALESCE(SJC.PERS_LINK,0) <> 0
		AND SJC.PERIOD_BEGIN >= @varKSstart_date 
		AND SJC.PERIOD_END <= @varKSEND_DATE
		AND ( (@varKSnMode = 1 AND TYP_OPER <3 ) OR (@varKSnMode = 2 AND TYP_OPER = 3))
		AND (
			LEN(@varKScVal2) = 0
			OR SJC.LINK_VKR IN (SELECT RECORD FROM dbo.OBJECT_VAR_SAL_SFIN WHERE LINK_UP = @varKSnOtborLink2 )
		)
		AND LEN(@varKScVal1) = 0 
	GROUP BY LINK_PAYS, TYP_OPER, CODE_PAYS, NAME_PAYS, COALESCE(EKR.CODE,''), (case when @varKSnMode1 = 1 then sp.link else 0 end) , (case when @varKSnMode1 = 1 then sp.NAME else  '' end) ,(case when @varKSnMode1 = 1 then sp.CODE else  '' end)  
	UNION
	SELECT --Травматизм
		LINK_PAYS,
		TYP_OPER, 
		[CODE] = CODE_PAYS,
		[NAME] = NAME_PAYS,
		[HOURS] = 0,
		[DAYS] = 0,
		[SUM_PAY] = SUM(CASE WHEN TYP_OPER = 1 OR TYP_OPER = 3 THEN SUMMA ELSE 0 END),
		[SUM_TAX] = SUM(CASE WHEN TYP_OPER = 2 THEN SUMMA ELSE 0 END),
		COALESCE(EKR.CODE,'') as EKR_CODE,
		LINK_KAT = CASE when @varKSnMode1 = 1	then sp.link else 0 end,
		NAME_KAT = CASE when @varKSnMode1 = 1	then sp.NAME else '' end,
		CODE_KAT = CASE when @varKSnMode1 = 1	then sp.CODE else '' end	
	FROM S_J_C_Short SJC inner join dbo.kosgu EKR on EKR.link = LINK_EKR
		INNER JOIN dbo.SAL_SFIN F ON F.LINK = sjc.LINK_VKR
		LEFT JOIN dbo.pers_invalid I ON I.PERS_LINK = (select top 1 link_pers from SDOC_DOT_SKIDKI_FIO  where LINK =   SJC.LINK_DOC and LINK_VKR = sjc.LINK_VKR and LINK_EKR = SJC.LINK_EKR) AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,month( @varKSEND_DATE),year( SJC.MONTH_END))) BETWEEN I.DATE_BEGIN AND COALESCE(I.DATE_END,'29990101')
		left join SA_PFR_KATEG sp on  (CASE WHEN I.LINK IS NULL THEN (F.ENVD + 1) ELSE 3 END)	= sp.link2 and SJC.YEAR_END <=  sp.YEND and SJC.YEAR_END >= sp.YBEG   /*and sp.CODE like '%ОИ'   */  
	WHERE
		SJC.LINK_DEP = @DEP_LINK 
		AND COALESCE(SJC.LINK_EMPL,0) = 0 AND COALESCE(SJC.LINK_FACE,0) = 0 AND COALESCE(SJC.PERS_LINK,0) = 0 
		AND SJC.PERIOD_BEGIN >= @varKSstart_date 
		AND SJC.PERIOD_END <= @varKSEND_DATE
		AND @varKSnMode = 2 
		AND TYP_OPER = 3
		AND (
			LEN(@varKScVal2) = 0
			OR SJC.LINK_VKR IN (SELECT RECORD FROM dbo.OBJECT_VAR_SAL_SFIN WHERE LINK_UP = @varKSnOtborLink2 )
		)
		
	GROUP BY LINK_PAYS, TYP_OPER, CODE_PAYS, NAME_PAYS, COALESCE(EKR.CODE,'') , (case when @varKSnMode1 = 1 then sp.link else 0 end) , (case when @varKSnMode1 = 1 then sp.NAME else  '' end) ,(case when @varKSnMode1 = 1 then sp.CODE else  '' end)  

	-----
	DECLARE @SALARY_PROV_OPT4 TINYINT
	SET @SALARY_PROV_OPT4 = dbo.sa_get_option_by_code('SALARY_PROV_OPT4')
	
	SELECT 
		LINK_PAYS,
		[TYP_OPER], 
		[CODE],
		[NAME],
		[EKR] =  CASE WHEN TYP_OPER = 3 THEN
							CASE WHEN @SALARY_PROV_OPT4 = 0 THEN 
									CASE WHEN ISNULL(EKR_CODE,'213') = '211' THEN '213' ELSE ISNULL(EKR_CODE,'213') END
								ELSE 
									CASE WHEN ISNULL(EKR_CODE,'213') IN ('211', '212') THEN '213' ELSE ISNULL(EKR_CODE,'213') END
							END
						ELSE EKR_CODE
					END, 	
		[HOURS] = SUM(HOURS),
		[DAYS] = SUM(DAYS),
		[SP] = SUM(SUM_PAY),
		[SUM_TAX] = SUM(SUM_TAX),
		[SUM_PAY] = SUM(SUM_PAY),
		LINK_KAT ,
		NAME_KAT,
		CODE_KAT
	INTO #RES
	FROM #TMP 
	GROUP BY
		LINK_PAYS, 
		TYP_OPER, 
		[CODE],
		[NAME],
		[EKR_CODE],
		LINK_KAT,
		NAME_KAT,
		CODE_KAT
	ORDER BY TYP_OPER, CODE, EKR

	Select LINK_PAYS, TYP_OPER, CODE, [NAME], HOURS = sum(HOURS), DAYS = sum(DAYS), SUM_PAY= sum(SUM_PAY), SUM_TAX= sum(SUM_TAX),LINK_KAT ,	NAME_KAT, CODE_KAT
	into #RES1
	from #RES
	GROUP by LINK_PAYS, TYP_OPER, CODE, [NAME],LINK_KAT ,	NAME_KAT, CODE_KAT

	DECLARE @varKSTABLE_N VARCHAR(100)
	DECLARE @varKSTABLE_U VARCHAR(100)
	EXEC X_GET_TABLE_NAME @varKSTABLE_N OUTPUT
	SET @varKSTABLE_U = @varKSTABLE_N + '1'

	DECLARE @varKSCNT_N INT
	SELECT @varKSCNT_N = COUNT(DISTINCT EKR) FROM #RES 

		EXEC M_CROSS_TABLE
			'LINK_PAYS,LINK_KAT', 
			'EKR', 'VARCHAR(3)', 
			'SP', 'NUMERIC(20,2)', 'SUM(SP) AS SP',
			'#RES', @varKSTABLE_N

		if @varKSnMode1 = 1
			EXEC (' SELECT R.TYP_OPER, R.CODE, R.NAME, R.NAME_KAT, R.CODE_KAT, R.HOURS, R.DAYS,  R.SUM_PAY, R.SUM_TAX, N.* FROM #RES1 R left join ' + @varKSTABLE_N + ' N ON N.LINK_PAYS  =R.LINK_PAYS and N.LINK_KAT  =R.LINK_KAT 
					order by R.NAME_KAT, R.TYP_OPER, R.CODE,R.NAME ')
		else 
			EXEC (' SELECT R.TYP_OPER, R.CODE, R.NAME, R.NAME_KAT, R.CODE_KAT, R.HOURS, R.DAYS,  R.SUM_PAY, R.SUM_TAX, N.* FROM #RES1 R left join ' + @varKSTABLE_N + ' N ON N.LINK_PAYS  =R.LINK_PAYS and N.LINK_KAT  =R.LINK_KAT 
					order by  R.TYP_OPER, R.CODE, R.NAME ')
END






GO


GRANT EXECUTE ON dbo.[SD_REP_SVOD2] 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.[RA_EXPORT_FORM_FNS_130]') AND 
                 OBJECTPROPERTY(ID, N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_EXPORT_FORM_FNS_130]
END
GO
----------------------
CREATE PROCEDURE [dbo].[RA_EXPORT_FORM_FNS_130]
 @iLINK_SAVED_FORM INT,                   -- Линк выгружаемой формы  
 @vcFILE_NAME     VARCHAR(100)='' OUTPUT,  -- Имя текстового файла  
 @iMODE            INT=1                   -- Формат: 2-внутренний, 1-минфиновский   
 AS
SET NOCOUNT ON  
SET DATEFORMAT dmy  

DECLARE @iLINK_FORM		 INT,
      	@iLINK_TABLE	 INT,
        @iLINK_ORG       INT,
        @iLINK_BUDGET    INT, 
        @vcBudgetName    VARCHAR(100), 
        @dBEGIN_DATE     DATETIME,
        @dFORM_DATE      DATETIME,
        @sYear           SMALLINT, 
        @vcOrgname       VARCHAR(1000),
        @vcKOD_ORGAN     VARCHAR(8000),
        @vcVersion       VARCHAR(8000),
        @vcProgramName   VARCHAR(100),
        @vcCRC           VARCHAR(8000),  
        @vcInn           VARCHAR(50),
        @vcKpp           VARCHAR(9),
        @vcOkpo          VARCHAR(20),
        @vcOkato         VARCHAR(11),
        @vcPPP           VARCHAR(50),
        @vcSurname       VARCHAR(60),
        @vcFirstName     VARCHAR(60),
        @vcMiddleName    VARCHAR(60),
        @vcSurname_GB    VARCHAR(60),
        @vcFirstName_GB  VARCHAR(60),
        @vcMiddleName_GB VARCHAR(60),
        @vcDateRegl      VARCHAR(10),
        @vcExec          VARCHAR(8000),  
        @bCancel         BIT,
        @iReturn         INT,
        @vcNAME          VARCHAR(8000),
        @vcFORM_CODE     VARCHAR(8000),  
        @vcFILE_NAME_XSD VARCHAR(100),    
        @vcTableName     VARCHAR(8000), 
        @CODE            VARCHAR(10),
        @v_code          VARCHAR(10),
        @C_CODE          VARCHAR(10),
        @vc_code         VARCHAR(10),
        @vcAcc           VARCHAR(2)
DECLARE @val             VARCHAR(8000), 
        @val2            VARCHAR(8000), 
        @str             VARCHAR(8000), 
        @str1            VARCHAR(8000)
          
CREATE TABLE #tabXML ([TXT]	  VARCHAR(8000),
							 [ORDERS] INT IDENTITY(1,1))

IF OBJECT_ID('tempdb..#tabExportOutput') IS NOT NULL 
BEGIN  
   SELECT @vcVersion = [VERSION]  
   FROM #tabExportOutput   
END  
  
--IF @iMODE = 2  
--BEGIN  
-- EXEC @iReturn = dbo.[RN_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,  
--                 @vcFILE_NAME OUTPUT,  
--                 @iMODE  
-- RETURN @iReturn  
--END  
  
IF @bCancel = 1  
BEGIN  
   RETURN 0  
END  
  
SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_ORG  = [Link_Organization],
       @vcBudgetName = ISNULL(CASE WHEN [C].[NAME] IS NULL 
                                   THEN (SELECT [NAME]
                                         FROM dbo.[RA_VIEW_EMPTY_BUDGET])
                                   ELSE [C].[NAME]
                              END,'Бюджет не определен')        
FROM dbo.[report_saved_forms] A  
LEFT JOIN dbo.[KL_BUDG_TYPE]  [C] ON [A].[LINK_TYPE_SVOD] = [C].[LINK]
WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM   
  
SET @bCancel = 0         
SET @vcNAME = 'Баланс (гл)распоряд., получ бюдж. ср-в'
SET @vcFORM_CODE = '0503130'  
SET @vcVersion = '5.01'  
SELECT @vcProgramName = CASE WHEN CODE_TASK = 'SMETA'   THEN 'СМЕТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'KADRY'   THEN 'КАДРЫ-КС'
                             WHEN CODE_TASK = 'SALARY'  THEN 'ЗАРПЛАТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'DELO'    THEN 'ДЕЛО-КС'
                             WHEN CODE_TASK = 'ADMIN'   THEN 'АДМИНИСТРАТОР'
                             ELSE ''
                        END       
FROM [dbo].USER_INFO                                  
--Таблица
SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 1

CREATE TABLE #tabAttr ([CHECKED] INT, 
                       [UPD]     INT, 
                       [DEL]     INT, 
                       [LINK_SAVED_FORM] INT, 
                       [LINK_ROW] INT, 
                       [ORDERS]   INT, 
                       [CALC_ORDERS] INT, 
                       [PRINT_NULL] INT, 
                       [CODE] VARCHAR(50), COL1 VARCHAR(8000), 
                       COL2 VARCHAR(8000), COL3 VARCHAR(8000), COL4 VARCHAR(8000), 
                       COL5 VARCHAR(8000), COL6 VARCHAR(8000), COL7 VARCHAR(8000), 
                       COL8 VARCHAR(8000), itog VARCHAR(8000))
  SET @vcExec = 'INSERT #tabAttr
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  EXEC(@vcExec)
--Справка
SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 2

CREATE TABLE #tabAttr1 ([CHECKED] INT, 
                        [UPD]     INT, 
                        [DEL]     INT, 
                        [LINK_SAVED_FORM] INT, 
                        [LINK_ROW] INT, 
                        [ORDERS]   INT, 
                        [CALC_ORDERS] INT, 
                        [PRINT_NULL] INT, 
                        [CODE] VARCHAR(50), COL1 VARCHAR(8000), 
                        COL2 VARCHAR(8000), COL3 VARCHAR(8000), COL4 VARCHAR(8000), 
                        COL5 VARCHAR(8000), itog VARCHAR(8000))
  SET @vcExec = 'INSERT #tabAttr1
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  EXEC(@vcExec)
-- Выгрузка подписей.
 SELECT   @vcOrgname = substring(dbo.[RA_XML_MASK](d.[FULL_NAME]),1,1000),
          @vcInn     = RTRIM(LTRIM(d.[INN])),
          @vcKpp     = RTRIM(LTRIM(d.[KPP])),
          @vcOkpo    = d.[OKPO],
          @vcOkato   = d.[OKATO]
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iLINK_ORG
 SELECT @vcKOD_ORGAN = [SONO],
        @vcPPP       = [VED]
 FROM PrintDoc_GetDepData2(@iLINK_ORG)   
 SELECT @vcSurname=ch.[FM],
        @vcFirstName=ch.[IM],
        @vcMiddleName=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Руководитель') ch
 WHERE ch.link_dep = @iLINK_ORG
 SELECT @vcSurname_GB=ch.[FM],
        @vcFirstName_GB=ch.[IM],
        @vcMiddleName_GB=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Главный бухгалтер') ch
 WHERE ch.link_dep = @iLINK_ORG
 IF (@vcSurname='' OR @vcSurname IS NULL OR LEN(@vcSurname)=0) SELECT @vcSurname='A'
 IF (@vcFirstName='' OR @vcFirstName IS NULL OR LEN(@vcFirstName)=0) SELECT @vcFirstName='A'
 IF (@vcInn='' OR @vcInn IS NULL) SELECT @vcInn='9999999999'
 IF (@vcKpp='' OR @vcKpp IS NULL) SELECT @vcKpp='999999999'
 IF @vcKOD_ORGAN IS NULL SELECT @vcKOD_ORGAN=''
--Дата начала   
SELECT @dBEGIN_DATE = A.[Begin_Date],
       @sYear = CAST(YEAR(@dBEGIN_DATE) AS VARCHAR(4)),  
       @vcDateRegl = convert(varchar(12), @dBEGIN_DATE+1, 104) 
  FROM dbo.[report_saved_forms] A
  WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM
--Дата документа
 SELECT @dFORM_DATE=GETDATE()
  
SET @vcCRC = RTRIM(CONVERT(VARCHAR(100), NEWID()))  
--Имя файла
SELECT @vcExec =  'NO_BOBUDG_' +  @vcKOD_ORGAN+ '_' +  
                  @vcKOD_ORGAN+ '_' + @vcINN + @vcKPP + '_' +  
                  CAST(YEAR(@dFORM_DATE) AS VARCHAR(4)) + 
                  RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '_' + @vcCRC,
       @vcFILE_NAME =  @vcExec + '.xml'
--Вставка XML
INSERT #tabXML([TXT]) VALUES ('<?xml  version ="1.0"  encoding ="windows-1251"?>')
INSERT #tabXML([TXT]) VALUES ('<Файл ИдФайл="'+@vcExec+'" '+'ВерсПрог="'+@vcProgramName+'" '+'ВерсФорм="'+@vcVersion+'">')
INSERT #tabXML([TXT]) VALUES ('  <Документ КНД="'+@vcFORM_CODE+'" ДатаДок="'+RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '.' +  
                               RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ '.' + CAST(YEAR(@dFORM_DATE) AS VARCHAR(4))+
                               '" НаимБюдж="'+RTRIM(LTRIM(@vcBudgetName))+'"'+' Период="34" ОтчетГод="'+CAST(@sYear AS VARCHAR(4))+'" НомКорр="0" ОКЕИ="383">')
INSERT #tabXML([TXT]) VALUES ('    <СвНП')
IF @vcOkpo<>'' AND LEN(@vcOkpo) BETWEEN 8 AND 10 
INSERT #tabXML([TXT]) VALUES (' ОКПО="'+LTRIM(RTRIM(@vcOkpo))+'"') 
IF @vcOkato<>'' AND LEN(@vcOkato)=11
INSERT #tabXML([TXT]) VALUES (' ОКАТО="'+@vcOkato+'"')
IF @vcPPP<>'' AND LEN(@vcPPP)<4
INSERT #tabXML([TXT]) VALUES (' ГлаваБК="' + @vcPPP + '"')
INSERT #tabXML([TXT]) VALUES ('>')
INSERT #tabXML([TXT]) VALUES ('<НПЮЛ НаимОрг="'+@vcOrgname+'" ИННЮЛ="'+@vcInn+'" КПП="'+@vcKpp+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('</СвНП>')
INSERT #tabXML([TXT]) VALUES ('<Подписант ПрПодп="3">')
INSERT #tabXML([TXT]) VALUES ('<ФИО Фамилия="'+@vcSurname+'" Имя="'+@vcFirstName+'"')
IF @vcMiddleName<>''
INSERT #tabXML([TXT]) VALUES ('           Отчество="'+@vcMiddleName+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('</Подписант>')
IF @vcSurname_GB<>'' AND @vcFirstName_GB<>''
begin
INSERT #tabXML([TXT]) VALUES ('<Подписант ПрПодп="4">')
INSERT #tabXML([TXT]) VALUES ('<ФИО Фамилия="'+@vcSurname_GB+'" Имя="'+@vcFirstName_GB+'"')
IF @vcMiddleName_GB<>''
INSERT #tabXML([TXT]) VALUES ('Отчество="'+@vcMiddleName_GB+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('</Подписант>')
end
INSERT #tabXML([TXT]) VALUES ('<БалансБдж ДатаОтч="'+@vcDateRegl+'" >')
INSERT #tabXML([TXT]) VALUES ('<Актив>')
-----------------------------------------------
IF EXISTS (SELECT * FROM #tabAttr WHERE CODE<=150)
begin
INSERT #tabXML([TXT]) VALUES ('<НефинАктив>')
DECLARE B_CURSOR CURSOR FOR      
SELECT CODE FROM #tabAttr 
  WHERE CODE LIKE '__0' AND CODE<=150 ORDER BY [CODE] ASC
OPEN B_CURSOR      
FETCH NEXT FROM B_CURSOR INTO @CODE      
WHILE @@FETCH_STATUS = 0         
BEGIN  
  SELECT @str1='',@v_code=''
  IF      @CODE='010' SELECT @str1='<БалансОС>'    ,@v_code=@CODE
  ELSE IF @CODE='020' SELECT @str1='<АмортОС>'     ,@v_code=@CODE
  ELSE IF @CODE='030' SELECT @str1='<ОстатОС>'     ,@v_code=@CODE
  ELSE IF @code='040' SELECT @str1='<НеМатАктБС>'  ,@v_code=@CODE
  ELSE IF @code='050' SELECT @str1='<АмортНмА>'    ,@v_code=@CODE
  ELSE IF @code='060' SELECT @str1='<НеМатАктОС>'  ,@v_code=@CODE
  ELSE IF @code='070' SELECT @str1='<НеПроизвАкт>' ,@v_code=@CODE
  ELSE IF @code='080' SELECT @str1='<МатЗапас>'    ,@v_code=@CODE
  ELSE IF @code='090' SELECT @str1='<ВложНеФинАкт>',@v_code=@CODE
  ELSE IF @code='100' SELECT @str1='<НеФинАктП>'   ,@v_code=@CODE
  ELSE IF @code='110' SELECT @str1='<НеФинАктИмКзБС>',@v_code=@CODE
  ELSE IF @code='120' SELECT @str1='<АмортИмКазн>'   ,@v_code=@CODE
  ELSE IF @code='130' SELECT @str1='<НеФинАктИмКзОС>',@v_code=@CODE
  ELSE IF @code='140' SELECT @str1='<ИзгГотовПрод>',@v_code=@CODE
  ELSE IF @code='150' SELECT @str1='<Итого>'       ,@v_code=@CODE
  ELSE                SELECT @str1=''            ,@v_code=''
  INSERT #tabXML([TXT]) SELECT @str1
 DECLARE C_CURSOR CURSOR FOR      
 SELECT [CODE] FROM #tabAttr WHERE [CODE] LIKE SUBSTRING(@v_code,1,2)+'_' ORDER BY [CODE] ASC
 OPEN C_CURSOR      
 FETCH NEXT FROM C_CURSOR INTO @C_CODE      
 WHILE @@FETCH_STATUS = 0         
 BEGIN
SELECT @str1='',@vc_code=''
IF      @c_code IN ('070','080','110','120','130','140','150') SELECT @vc_code=@c_code      
ELSE IF @c_code in ('010','020','030','040','050','060','090','100')                   
                                             SELECT @str1='<Всего>', @vc_code=@c_code
ELSE IF @c_code in ('011','021','031')       SELECT @str1='<НедИмущУчр>', @vc_code=@c_code
ELSE IF @c_code in ('013','023','033','093') SELECT @str1='<ИнДИмущУчр>' , @vc_code=@c_code
ELSE IF @c_code in ('014','024','034','094') SELECT @str1='<ПрЛизинг>' , @vc_code=@c_code
ELSE IF @c_code in ('042','052','062')       SELECT @str1='<ИнДИмущУчр>', @vc_code=@c_code
ELSE IF @c_code in ('043','053','063')       SELECT @str1='<ПрЛизинг>' , @vc_code=@c_code
ELSE IF @c_code='091'                        SELECT @str1='<НеДИмущУчр>', @vc_code=@c_code
ELSE IF @c_code='101'                        SELECT @str1='<НеДИмущУчрП>', @vc_code=@c_code
ELSE IF @c_code='103'                        SELECT @str1='<ИнДИмущУчрП>', @vc_code=@c_code
ELSE IF @c_code='104'                        SELECT @str1='<ПрЛизингП>', @vc_code=@c_code
ELSE SELECT @str1='', @vc_code='' 
INSERT #tabXML([TXT]) SELECT @str1
SELECT @val='', @val2='', @str=''
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' ДеятБдж = "' + @val  + '"'END
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val  + '"'END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL5]+'"/>' FROM #tabAttr WHERE [CODE]	=@vc_code
end
SELECT @val='', @val2='', @str=''
SELECT @val=[COL6] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' ДеятБдж = "' + @val  + '"'END
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val  + '"'END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL8]+'"/>' FROM #tabAttr WHERE [CODE]=@vc_code
SELECT @str1=''
IF @c_code in ('010','020','030','040','050','060','090','100')                   
                                             SELECT @str1='</Всего>'
ELSE IF @c_code in ('011','021','031')       SELECT @str1='</НедИмущУчр>'
ELSE IF @c_code in ('013','023','033','093') SELECT @str1='</ИнДИмущУчр>'
ELSE IF @c_code in ('014','024','034','094') SELECT @str1='</ПрЛизинг>' 
ELSE IF @c_code in ('042','052','062')       SELECT @str1='</ИнДИмущУчр>'
ELSE IF @c_code in ('043','053','063')       SELECT @str1='</ПрЛизинг>' 
ELSE IF @c_code='091'                        SELECT @str1='</НеДИмущУчр>'
ELSE IF @c_code='101'                        SELECT @str1='</НеДИмущУчрП>'
ELSE IF @c_code='103'                        SELECT @str1='</ИнДИмущУчрП>'
ELSE IF @c_code='104'                        SELECT @str1='</ПрЛизингП>'
ELSE SELECT @str1=''
INSERT #tabXML([TXT]) SELECT @str1

FETCH NEXT FROM C_CURSOR INTO @C_CODE      
END      
CLOSE C_CURSOR      
DEALLOCATE C_CURSOR   
  SELECT @str1=''
  IF      @CODE='010' SELECT @str1='</БалансОС>'    
  ELSE IF @CODE='020' SELECT @str1='</АмортОС>'     
  ELSE IF @CODE='030' SELECT @str1='</ОстатОС>'     
  ELSE IF @code='040' SELECT @str1='</НеМатАктБС>'  
  ELSE IF @code='050' SELECT @str1='</АмортНмА>'    
  ELSE IF @code='060' SELECT @str1='</НеМатАктОС>'  
  ELSE IF @code='070' SELECT @str1='</НеПроизвАкт>' 
  ELSE IF @code='080' SELECT @str1='</МатЗапас>'    
  ELSE IF @code='090' SELECT @str1='</ВложНеФинАкт>'
  ELSE IF @code='100' SELECT @str1='</НеФинАктП>'   
  ELSE IF @code='110' SELECT @str1='</НеФинАктИмКзБС>'
  ELSE IF @code='120' SELECT @str1='</АмортИмКазн>'   
  ELSE IF @code='130' SELECT @str1='</НеФинАктИмКзОС>'
  ELSE IF @code='140' SELECT @str1='</ИзгГотовПрод>'
  ELSE IF @code='150' SELECT @str1='</Итого>'       
  ELSE                SELECT @str1=''
  INSERT #tabXML([TXT]) SELECT @str1

FETCH NEXT FROM B_CURSOR INTO @CODE      
END      
CLOSE B_CURSOR      
DEALLOCATE B_CURSOR
INSERT #tabXML([TXT]) VALUES('</НефинАктив>')
end
------------------------------------------------
IF EXISTS (SELECT * FROM #tabAttr WHERE CODE BETWEEN 170 AND 400)
begin
INSERT #tabXML([TXT]) VALUES('<ФинАктив>')
DECLARE B_CURSOR CURSOR FOR      
SELECT CODE FROM #tabAttr WHERE CODE LIKE '__0' AND CODE BETWEEN 170 AND 400  ORDER BY [CODE] ASC
OPEN B_CURSOR      
FETCH NEXT FROM B_CURSOR INTO @CODE      
WHILE @@FETCH_STATUS = 0         
BEGIN  
  SELECT @str1='',@v_code=''
  IF @code='170'      SELECT @str1='<ДенСрУчр>'     ,@v_code=@CODE
  ELSE IF @CODE='210' SELECT @str1='<ФинВлож>'      ,@v_code=@CODE
  ELSE IF @CODE='230' SELECT @str1='<РасчДоход>'    ,@v_code=@CODE
  ELSE IF @code='260' SELECT @str1='<РасчВыдАванс>' ,@v_code=@CODE
  ELSE IF @code='290' SELECT @str1='<РасчКредит>'   ,@v_code=@CODE
  ELSE IF @code='310' SELECT @str1='<РасчПОтчЛиц>'  ,@v_code=@CODE
  ELSE IF @code='320' SELECT @str1='<РасчУщербИмущ>',@v_code=@CODE
  ELSE IF @code='330' SELECT @str1='<ПрочРасчДеб>'  ,@v_code=@CODE
  ELSE IF @code='370' SELECT @str1='<ВложФинАкт>'   ,@v_code=@CODE
  ELSE IF @code='400' SELECT @str1='<Итого>'        ,@v_code=@CODE
  ELSE SELECT @str1='',@v_code=''
  INSERT #tabXML([TXT]) SELECT @str1

DECLARE C_CURSOR CURSOR FOR      
SELECT [CODE] FROM #tabAttr WHERE [CODE] LIKE SUBSTRING(@v_code,1,2)+'_'  ORDER BY [CODE] ASC
OPEN C_CURSOR      
FETCH NEXT FROM C_CURSOR INTO @C_CODE      
WHILE @@FETCH_STATUS = 0         
BEGIN  
  SELECT @str1='',@vc_code=''
  IF @c_code IN ('230','260','310','320','400') 
                             SELECT @vc_code=@c_code
  ELSE IF @c_code in ('170','210','290','330','370')  
                             SELECT @str1='<Всего>', @vc_code=@c_code
  ELSE IF @c_code='171'      SELECT @str1='<ЛицСчОргКазн>', @vc_code=@c_code
  ELSE IF @c_code='172'      SELECT @str1='<ОргКазнПут>', @vc_code=@c_code
  ELSE IF @c_code='173'      SELECT @str1='<СчетКО>', @vc_code=@c_code
  ELSE IF @c_code='174'      SELECT @str1='<КОПут>', @vc_code=@c_code
  ELSE IF @c_code='175'      SELECT @str1='<АккрСчетКО>', @vc_code=@c_code
  ELSE IF @c_code='176'      SELECT @str1='<ИнВалСчКО>' , @vc_code=@c_code
  ELSE IF @c_code='177'      SELECT @str1='<Касса>', @vc_code=@c_code
  ELSE IF @c_code='178'      SELECT @str1='<ДенДокум>', @vc_code=@c_code
  ELSE IF @c_code='179'      SELECT @str1='<РазмДепКО>', @vc_code=@c_code
  ELSE IF @c_code IN ('211','371') SELECT @str1='<ЦенБумКрАкц>', @vc_code=@c_code
  ELSE IF @c_code IN ('212','372') SELECT @str1='<АкцИнКапит>', @vc_code=@c_code
  ELSE IF @c_code IN ('213','373') SELECT @str1='<ИнФинАктив>', @vc_code=@c_code
  ELSE IF @c_code='291'      SELECT @str1='<ПредстКредит>', @vc_code=@c_code
  ELSE IF @c_code='292'      SELECT @str1='<ЦелИнКредит>', @vc_code=@c_code
  ELSE IF @c_code='293'      SELECT @str1='<ДебитГосГар>', @vc_code=@c_code
  ELSE IF @c_code='331'      SELECT @str1='<РасчНДС>', @vc_code=@c_code
  ELSE IF @c_code='333'      SELECT @str1='<РасчФОДен>', @vc_code=@c_code
  ELSE SELECT @str1='', @vc_code='' 
  INSERT #tabXML([TXT]) SELECT @str1
SELECT @val='', @val2='', @str=''
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' ДеятБдж = "' + @val  + '"'END
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val  + '"'END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL5]+'"/>' FROM #tabAttr WHERE [CODE]	=@vc_code
end
SELECT @val='', @val2='', @str=''
SELECT @val=[COL6] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' ДеятБдж = "' + @val  + '"'END
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val  + '"'END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL8]+'"/>' FROM #tabAttr WHERE [CODE]=@vc_code

  SELECT @str1=''
  IF @c_code in ('170','210','290','330','370') 
                             SELECT @str1='</Всего>'
  ELSE IF @c_code='171'      SELECT @str1='</ЛицСчОргКазн>'
  ELSE IF @c_code='172'      SELECT @str1='</ОргКазнПут>'
  ELSE IF @c_code='173'      SELECT @str1='</СчетКО>'
  ELSE IF @c_code='174'      SELECT @str1='</КОПут>'
  ELSE IF @c_code='175'      SELECT @str1='</АккрСчетКО>'
  ELSE IF @c_code='176'      SELECT @str1='</ИнВалСчКО>' 
  ELSE IF @c_code='177'      SELECT @str1='</Касса>'
  ELSE IF @c_code='178'      SELECT @str1='</ДенДокум>'
  ELSE IF @c_code='179'      SELECT @str1='</РазмДепКО>'
  ELSE IF @c_code IN ('211','371') SELECT @str1='</ЦенБумКрАкц>'
  ELSE IF @c_code IN ('212','372') SELECT @str1='</АкцИнКапит>'
  ELSE IF @c_code IN ('213','373') SELECT @str1='</ИнФинАктив>'
  ELSE IF @c_code='291'      SELECT @str1='</ПредстКредит>'
  ELSE IF @c_code='292'      SELECT @str1='</ЦелИнКредит>'
  ELSE IF @c_code='293'      SELECT @str1='</ДебитГосГар>'
  ELSE IF @c_code='331'      SELECT @str1='</РасчНДС>'
  ELSE IF @c_code='333'      SELECT @str1='</РасчФОДен>'
  ELSE SELECT @str1='' 
  INSERT #tabXML([TXT]) SELECT @str1

FETCH NEXT FROM C_CURSOR INTO @C_CODE      
END      
CLOSE C_CURSOR      
DEALLOCATE C_CURSOR   
SELECT @str1=''
IF @code='170'      SELECT @str1='</ДенСрУчр>'
ELSE IF @CODE='210' SELECT @str1='</ФинВлож>'
ELSE IF @CODE='230' SELECT @str1='</РасчДоход>'
ELSE IF @code='260' SELECT @str1='</РасчВыдАванс>'
ELSE IF @code='290' SELECT @str1='</РасчКредит>'
ELSE IF @code='310' SELECT @str1='</РасчПОтчЛиц>'
ELSE IF @code='320' SELECT @str1='</РасчУщербИмущ>'
ELSE IF @code='330' SELECT @str1='</ПрочРасчДеб>'
ELSE IF @code='370' SELECT @str1='</ВложФинАкт>'
ELSE IF @code='400' SELECT @str1='</Итого>'
ELSE SELECT @str1=''
INSERT #tabXML([TXT]) SELECT @str1

FETCH NEXT FROM B_CURSOR INTO @CODE      
END      
CLOSE B_CURSOR      
DEALLOCATE B_CURSOR
INSERT #tabXML([TXT]) VALUES('</ФинАктив>')
end
---------------------------------------------
INSERT INTO #tabXML([TXT]) VALUES('<Баланс>')
SELECT @val='', @val2='', @str='',@str1=''
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=410
if @val<>'0.00' begin set @str = @str + ' ДеятБдж = "' + @val + '"' END
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=410
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val + '"' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL5]+'"/>' FROM #tabAttr WHERE [CODE]	=410
end
SELECT @val='', @val2='', @str=''
SELECT @val=[COL6] FROM #tabAttr WHERE  [CODE]=410
if @val<>'0.00' begin set @str = @str + ' ДеятБдж = "' + @val + '"' END
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=410
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val + '"' END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL8]+'"/>' FROM #tabAttr WHERE [CODE]	=410
INSERT INTO #tabXML([TXT]) VALUES('</Баланс>')
----------------------------------------------
INSERT #tabXML([TXT]) VALUES ('</Актив>')
INSERT #tabXML([TXT]) VALUES ('<Пассив>')
----------------------------------------------
IF EXISTS (SELECT * FROM #tabAttr WHERE CODE BETWEEN 470 AND 600)
begin
INSERT #tabXML([TXT]) VALUES ('<Обязат>')
DECLARE B_CURSOR CURSOR FOR      
SELECT CODE FROM #tabAttr WHERE CODE LIKE '__0' AND CODE BETWEEN 470 AND 600  ORDER BY [CODE] ASC
OPEN B_CURSOR      
FETCH NEXT FROM B_CURSOR INTO @CODE      
WHILE @@FETCH_STATUS = 0         
BEGIN  
  SELECT @str1='',@v_code=''
  IF      @code='470' SELECT @str1='<РасчКДолгОбяз>',@v_code=@code
  ELSE IF @CODE='490' SELECT @str1='<РасчПрОбяз>'   ,@v_code=@code
  ELSE IF @CODE='510' SELECT @str1='<РасчПлатБюдж>' ,@v_code=@code
  ELSE IF @code='530' SELECT @str1='<ПрРасчКредит>' ,@v_code=@code
  ELSE IF @code='600' SELECT @str1='<Итого>'        ,@v_code=@code
  ELSE SELECT @str1='',@v_code='' 
  INSERT #tabXML([TXT]) SELECT @str1

DECLARE C_CURSOR CURSOR FOR      
SELECT [CODE] FROM #tabAttr WHERE [CODE] LIKE SUBSTRING(@v_code,1,2)+'_'  ORDER BY [CODE] ASC
OPEN C_CURSOR      
FETCH NEXT FROM C_CURSOR INTO @C_CODE      
WHILE @@FETCH_STATUS = 0         
BEGIN
  SELECT @str1='',@vc_code=''
  IF @c_code IN ('490','600') SELECT @vc_code=@c_code
  ELSE IF @c_code in ('470','510','530') 
                        SELECT @str1='<Всего>', @vc_code=@c_code
  ELSE IF @c_code='471' SELECT @str1='<ДолгОбязРуб>', @vc_code=@c_code
  ELSE IF @c_code='472' SELECT @str1='<ДолгОбязИнКр>', @vc_code=@c_code
  ELSE IF @c_code='473' SELECT @str1='<ГосГарант>', @vc_code=@c_code
  ELSE IF @c_code='474' SELECT @str1='<ДолгОбязВал>', @vc_code=@c_code
  ELSE IF @c_code='511' SELECT @str1='<РасчНДФЛ>', @vc_code=@c_code
  ELSE IF @c_code='512' SELECT @str1='<РасчВзнОСС>', @vc_code=@c_code
  ELSE IF @c_code='513' SELECT @str1='<РасчПриб>', @vc_code=@c_code
  ELSE IF @c_code='514' SELECT @str1='<РасчНДС>', @vc_code=@c_code
  ELSE IF @c_code='515' SELECT @str1='<РасчИнПлат>', @vc_code=@c_code
  ELSE IF @c_code='516' SELECT @str1='<РасчВзнМПС>', @vc_code=@c_code
  ELSE IF @c_code='531' SELECT @str1='<РасчВремСр>', @vc_code=@c_code
  ELSE IF @c_code='532' SELECT @str1='<РасчДепонент>', @vc_code=@c_code
  ELSE IF @c_code='533' SELECT @str1='<РасчУдержОТ>', @vc_code=@c_code
  ELSE IF @c_code='534' SELECT @str1='<РасчВнВедоств>', @vc_code=@c_code
  ELSE SELECT @str1='', @vc_code='' 
  INSERT #tabXML([TXT]) SELECT @str1
SELECT @val='', @val2='', @str=''
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' ДеятБдж = "' + @val  + '"'END
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val  + '"'END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL5]+'"/>' FROM #tabAttr WHERE [CODE]	= @vc_code
end
SELECT @val='', @val2='', @str=''
SELECT @val=[COL6] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' ДеятБдж = "' + @val  + '"'END
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val  + '"'END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL8]+'"/>' FROM #tabAttr WHERE [CODE] = @vc_code

  SELECT @str1=''
  IF @c_code in ('470','510','530') SELECT @str1='</Всего>'
  ELSE IF @c_code='471' SELECT @str1='</ДолгОбязРуб>'
  ELSE IF @c_code='472' SELECT @str1='</ДолгОбязИнКр>'
  ELSE IF @c_code='473' SELECT @str1='</ГосГарант>'
  ELSE IF @c_code='474' SELECT @str1='</ДолгОбязВал>'
  ELSE IF @c_code='511' SELECT @str1='</РасчНДФЛ>'
  ELSE IF @c_code='512' SELECT @str1='</РасчВзнОСС>'
  ELSE IF @c_code='513' SELECT @str1='</РасчПриб>'
  ELSE IF @c_code='514' SELECT @str1='</РасчНДС>'
  ELSE IF @c_code='515' SELECT @str1='</РасчИнПлат>'
  ELSE IF @c_code='516' SELECT @str1='</РасчВзнМПС>'
  ELSE IF @c_code='531' SELECT @str1='</РасчВремСр>'
  ELSE IF @c_code='532' SELECT @str1='</РасчДепонент>'
  ELSE IF @c_code='533' SELECT @str1='</РасчУдержОТ>'
  ELSE IF @c_code='534' SELECT @str1='</РасчВнВедоств>'
  ELSE SELECT @str1='' 
  INSERT #tabXML([TXT]) SELECT @str1
  
FETCH NEXT FROM C_CURSOR INTO @C_CODE      
END      
CLOSE C_CURSOR      
DEALLOCATE C_CURSOR   
  SELECT @str1=''
  IF      @code='470' SELECT @str1='</РасчКДолгОбяз>'
  else IF @CODE='490' SELECT @str1='</РасчПрОбяз>'
  else IF @CODE='510' SELECT @str1='</РасчПлатБюдж>'
  else IF @code='530' SELECT @str1='</ПрРасчКредит>'
  else IF @code='600' SELECT @str1='</Итого>'
  ELSE SELECT @str1='' 
  INSERT #tabXML([TXT]) SELECT @str1

FETCH NEXT FROM B_CURSOR INTO @CODE      
END      
CLOSE B_CURSOR      
DEALLOCATE B_CURSOR
INSERT #tabXML([TXT]) VALUES ('</Обязат>')
end
---------------------------------------------  
IF EXISTS (SELECT * FROM #tabAttr WHERE [CODE] LIKE '62%')
begin
INSERT #tabXML([TXT]) VALUES ('<ФинРезул>')
INSERT INTO #tabXML([TXT]) VALUES('<ФинРезХозСуб>')
DECLARE FA_CURSOR CURSOR FOR      
 SELECT CODE      
 FROM #tabAttr      WHERE [CODE] LIKE '62%'  ORDER BY [CODE] ASC
 OPEN FA_CURSOR      
 FETCH NEXT FROM FA_CURSOR INTO @CODE      
 WHILE @@FETCH_STATUS = 0         
 BEGIN  
SELECT @val=[COL8] FROM #tabAttr WHERE  [CODE]=@CODE
 
begin 
SELECT @str1='',@v_code=''
IF      @code='620'  SELECT @str1='<Всего>',@v_code=@code
else IF @code='623'  SELECT @str1='<ФинРезПрОПер>',@v_code=@code
else IF @code='624'  SELECT @str1='<ДохБудПер>',@v_code=@code
else IF @code='625'  SELECT @str1='<РасхБудПер>',@v_code=@code
ELSE SELECT @str1='',@v_code=''  
INSERT INTO #tabXML([TXT]) SELECT @str1
end
SELECT @val='', @val2='', @str=''
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=@v_CODE
if @val<>'0.00' begin set @str = @str + ' ДеятБдж = "' + @val + '"' END
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=@v_CODE
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val + '"' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL5]+'"/>' FROM #tabAttr WHERE [CODE]	=@v_CODE
end
SELECT @val='', @val2='', @str=''
SELECT @val=[COL6] FROM #tabAttr WHERE  [CODE]=@v_CODE
if @val<>'0.00' begin set @str = @str + ' ДеятБдж = "' + @val + '"' END
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=@v_CODE
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val + '"' END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL8]+'"/>' FROM #tabAttr WHERE [CODE]	=@v_CODE

SELECT @val='', @val2='', @str=''
SELECT @val=[COL8] FROM #tabAttr WHERE  [CODE]=@v_CODE
 
begin 
SELECT @str1=''   
IF      @code='620'  SELECT @str1='</Всего>'
ELSE IF @code='623'  SELECT @str1='</ФинРезПрОПер>'
ELSE IF @code='624'  SELECT @str1='</ДохБудПер>'
ELSE IF @code='625'  SELECT @str1='</РасхБудПер>'
ELSE SELECT @str1='' 
INSERT INTO #tabXML([TXT]) SELECT @str1
end

FETCH NEXT FROM FA_CURSOR INTO @CODE      
END      
CLOSE FA_CURSOR      
DEALLOCATE FA_CURSOR   
INSERT INTO #tabXML([TXT]) VALUES('</ФинРезХозСуб>')
INSERT #tabXML([TXT]) VALUES ('</ФинРезул>')
end
-------------------------------------------------
INSERT INTO #tabXML([TXT]) VALUES('<Баланс>')
SELECT @val='', @val2='', @str='',@str1=''
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=900
if @val<>'0.00' begin set @str = @str + ' ДеятБдж = "' + @val + '"' END
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=900
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val + '"' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL5]+'"/>' FROM #tabAttr WHERE [CODE]	=900
end
SELECT @val='', @val2='', @str=''
SELECT @val=[COL6] FROM #tabAttr WHERE  [CODE]=900
if @val<>'0.00' begin set @str = @str + ' ДеятБдж = "' + @val + '"' END
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=900
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val + '"' END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL8]+'"/>' FROM #tabAttr WHERE [CODE]	=900
INSERT INTO #tabXML([TXT]) VALUES('</Баланс>')
---------------------------------------------------
INSERT #tabXML([TXT]) VALUES ('</Пассив>')
INSERT #tabXML([TXT]) VALUES ('<СпрИмущОбЗС>')
----------------------------------------------------
DECLARE B_CURSOR CURSOR FOR      
 SELECT CODE      
 FROM #tabAttr1 WHERE [CODE] LIKE '__0'  ORDER BY [CODE] ASC
 OPEN B_CURSOR      
 FETCH NEXT FROM B_CURSOR INTO @CODE      
 WHILE @@FETCH_STATUS = 0         
 BEGIN
SELECT @vcAcc = COL1 FROM #tabAttr1 WHERE CODE=@CODE
SELECT @str1='',@v_code=''
IF      @code='010' SELECT @str1='<ИмущПолПольз НомСчетЗаб = "'      + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='020' SELECT @str1='<МатЦенХран НомСчетЗаб = "'        + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='030' SELECT @str1='<БланкСтрОтч НомСчетЗаб = "'       + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='040' SELECT @str1='<ДолгНД НомСчетЗаб = "'            + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='050' SELECT @str1='<МатЦенОплЦС НомСчетЗаб = "'       + @vcAcc + '">',  @v_code=@CODE                 
ELSE IF @code='060' SELECT @str1='<ДолгНеМатЦен НомСчетЗаб = "'      + @vcAcc + '"' ,  @v_code=@CODE
ELSE IF @code='070' SELECT @str1='<НагрПриз НомСчетЗаб = "'          + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='080' SELECT @str1='<ПутевНеОпл НомСчетЗаб = "'        + @vcAcc + '"' ,  @v_code=@CODE
ELSE IF @code='090' SELECT @str1='<ЗапЧастТС НомСчетЗаб = "'         + @vcAcc + '"' ,  @v_code=@CODE
ELSE IF @code='100' SELECT @str1='<ИспОбяз НомСчетЗаб = "'           + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='110' SELECT @str1='<ГосМнцпГарант НомСчетЗаб = "'     + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='120' SELECT @str1='<СпецНИРДог НомСчетЗаб = "'        + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='130' SELECT @str1='<ЭксперУстр НомСчетЗаб = "'        + @vcAcc + '"' ,  @v_code=@CODE
ELSE IF @code='140' SELECT @str1='<РасчДокОжИсп НомСчетЗаб = "'      + @vcAcc + '"' ,  @v_code=@CODE
ELSE IF @code='150' SELECT @str1='<РасчДокНеОплСр НомСчетЗаб = "'    + @vcAcc + '"' ,  @v_code=@CODE
ELSE IF @code='160' SELECT @str1='<ПерепПенсНеЗак НомСчетЗаб = "'    + @vcAcc + '"' ,  @v_code=@CODE
ELSE IF @code='170' SELECT @str1='<ПостДССчетУчр НомСчетЗаб = "'     + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='180' SELECT @str1='<ВыбДССчетУчр НомСчетЗаб = "'      + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='190' SELECT @str1='<НеяснПостПр НомСчетЗаб = "'       + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='200' SELECT @str1='<ДолгНеКред НомСчетЗаб = "'        + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='210' SELECT @str1='<ОснСр3000Экспл НомСчетЗаб = "'    + @vcAcc + '"' ,  @v_code=@CODE
ELSE IF @code='220' SELECT @str1='<МатЦенЦСнаб НомСчетЗаб = "'       + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='230' SELECT @str1='<ПериодИзд НомСчетЗаб = "'         + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='240' SELECT @str1='<ИмущДовУпр НомСчетЗаб = "'        + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='250' SELECT @str1='<ИмущВозмПольз НомСчетЗаб = "'     + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='260' SELECT @str1='<ИмущБВозмПольз НомСчетЗаб = "'    + @vcAcc + '">',  @v_code=@CODE
ELSE                SELECT @str1='', @v_code=''
                
INSERT INTO #tabXML([TXT]) VALUES(@str1)

 DECLARE C_CURSOR CURSOR FOR      
 SELECT [CODE] FROM #tabAttr1 WHERE [CODE] LIKE SUBSTRING(@v_code,1,2)+'_'  ORDER BY [CODE] ASC
 OPEN C_CURSOR      
 FETCH NEXT FROM C_CURSOR INTO @C_CODE      
 WHILE @@FETCH_STATUS = 0         
 BEGIN  
 SELECT @str1=''
IF      @c_code IN ('060','080','090','130','140','150','160','210') 
                           SELECT @vc_code=@c_code      
ELSE IF @c_code in ('010','020','030','040','050','070','100','110','120','170','180','190','200','220','230','240','250','260') 
                           SELECT @str1='<Всего'             , @vc_code=@c_code
ELSE IF @c_code='011'      SELECT @str1='<Недвиж'            , @vc_code=@c_code
ELSE IF @c_code='012'      SELECT @str1='<НедвижНепр'        , @vc_code=@c_code
ELSE IF @c_code='015'      SELECT @str1='<Движ'              , @vc_code=@c_code
ELSE IF @c_code='055'      SELECT @str1='<ЦенДвИмущМЗ'       , @vc_code=@c_code
ELSE IF @c_code='071'      SELECT @str1='<УсловОцен'         , @vc_code=@c_code
ELSE IF @c_code='072'      SELECT @str1='<СтоимПриобр'       , @vc_code=@c_code
ELSE IF @c_code='101'      SELECT @str1='<Задаток'           , @vc_code=@c_code
ELSE IF @c_code='102'      SELECT @str1='<Залог'             , @vc_code=@c_code
ELSE IF @c_code='103'      SELECT @str1='<БанкГарант'        , @vc_code=@c_code
ELSE IF @c_code='104'      SELECT @str1='<Поручит'           , @vc_code=@c_code
ELSE IF @c_code='105'      SELECT @str1='<ИнОбеспеч'         , @vc_code=@c_code
ELSE IF @c_code='111'      SELECT @str1='<ГосГарант'         , @vc_code=@c_code
ELSE IF @c_code='112'      SELECT @str1='<МнцпГарант'        , @vc_code=@c_code
ELSE IF @c_code='171'      SELECT @str1='<Доходы'            , @vc_code=@c_code
ELSE IF @c_code IN ('172','181') SELECT @str1='<Расходы'     , @vc_code=@c_code
ELSE IF @c_code IN ('173','182') SELECT @str1='<ИстФинДефБдж', @vc_code=@c_code
ELSE IF @c_code='211'      SELECT @str1='<ОсЦенДИмущ'        , @vc_code=@c_code
ELSE IF @c_code='212'      SELECT @str1='<ИнДИмущ'           , @vc_code=@c_code
ELSE IF @c_code IN ('051','221','241','251','261') SELECT @str1='<ОснСредств'  , @vc_code=@c_code
ELSE IF @c_code IN (            '242','252','262') SELECT @str1='<НедвижИмущОС', @vc_code=@c_code
ELSE IF @c_code IN (            '244','254','264') SELECT @str1='<НематАктив'  , @vc_code=@c_code
ELSE IF @c_code IN ('052','222','246','256','266') SELECT @str1='<МатЗапас'    , @vc_code=@c_code
ELSE SELECT @str1='', @vc_code='' 
INSERT INTO #tabXML([TXT]) SELECT @str1
SELECT @val='', @val2='', @str=''
SELECT @val=[COL4] FROM #tabAttr1 WHERE  [CODE] = @vc_code
if @val<>'0.00' begin set @str = @str + ' СумНачГод="' + @val + '"' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT @str
end
SELECT @val='', @val2='', @str=''
SELECT @val=[COL5] FROM #tabAttr1 WHERE  [CODE] = @vc_code
 begin set @str = @str + ' СумКонПер="' + @val + '"' end
INSERT #tabXML([TXT]) SELECT @str
SELECT @str1=''
SELECT @str1='/>'
INSERT INTO #tabXML([TXT]) SELECT @str1

FETCH NEXT FROM C_CURSOR INTO @C_CODE      
END      
CLOSE C_CURSOR      
DEALLOCATE C_CURSOR   
SELECT @str1='',@v_code=''
IF      @code='010' SELECT @str1='</ИмущПолПольз>'
ELSE IF @code='020' SELECT @str1='</МатЦенХран>'
ELSE IF @code='030' SELECT @str1='</БланкСтрОтч>'
ELSE IF @code='040' SELECT @str1='</ДолгНД>'
ELSE IF @code='050' SELECT @str1='</МатЦенОплЦС>'
ELSE IF @code='070' SELECT @str1='</НагрПриз>'
ELSE IF @code='100' SELECT @str1='</ИспОбяз>'
ELSE IF @code='110' SELECT @str1='</ГосМнцпГарант>'
ELSE IF @code='120' SELECT @str1='</СпецНИРДог>'
ELSE IF @code='170' SELECT @str1='</ПостДССчетУчр>'
ELSE IF @code='180' SELECT @str1='</ВыбДССчетУчр>'
ELSE IF @code='190' SELECT @str1='</НеяснПостПр>'
ELSE IF @code='200' SELECT @str1='</ДолгНеКред>'
ELSE IF @code='220' SELECT @str1='</МатЦенЦСнаб>'
ELSE IF @code='230' SELECT @str1='</ПериодИзд>'
ELSE IF @code='240' SELECT @str1='</ИмущДовУпр>'
ELSE IF @code='250' SELECT @str1='</ИмущВозмПольз>'
ELSE IF @code='260' SELECT @str1='</ИмущБВозмПольз>'
ELSE                SELECT @str1=''
                
INSERT INTO #tabXML([TXT]) VALUES(@str1)

FETCH NEXT FROM B_CURSOR INTO @CODE      
END      
CLOSE B_CURSOR      
DEALLOCATE B_CURSOR
-----------------------------------------------------
INSERT #tabXML([TXT]) VALUES ('</СпрИмущОбЗС>')
INSERT #tabXML([TXT]) VALUES ('</БалансБдж>')
INSERT #tabXML([TXT]) VALUES ('</Документ>')
INSERT #tabXML([TXT]) VALUES ('</Файл>')

INSERT #Files ([TXT], [NAMEFILE],  [NAMEFILE_ARH],  [OrderFile],[LINK_SAVED_FORM])
SELECT         [TXT], @vcFILE_NAME,@vcFILE_NAME_XSD,[ORDERS],   @iLINK_SAVED_FORM
FROM #tabXML
DROP TABLE #tabXML  

GO
GRANT ALL ON dbo.[RA_EXPORT_FORM_FNS_130] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
IF EXISTS (SELECT * 
           FROM dbo.[SYSOBJECTS]
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_EXPORT_FORM_FNS_721]') AND 
                 OBJECTPROPERTY(ID, N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_EXPORT_FORM_FNS_721]
END
GO
----------------------
CREATE PROCEDURE [dbo].[RA_EXPORT_FORM_FNS_721]
	@iLINK_SAVED_FORM	INT						-- Линк выгружаемой формы  
	,@vcFILE_NAME		VARCHAR(100)='' OUTPUT	-- Имя текстового файла  
	,@iMODE				INT=1					-- Формат: 2-внутренний, 1-минфиновский  
AS  
  
SET NOCOUNT ON  
SET DATEFORMAT dmy  

DECLARE @iLINK_FORM		 INT,
      	@iLINK_TABLE	 INT,
        @iLINK_ORG       INT, 
        @dBEGIN_DATE     DATETIME,
        @dFORM_DATE      DATETIME,
        @sYear           SMALLINT, 
        @vcOrgname       VARCHAR(1000),
        @vcKOD_ORGAN     VARCHAR(8000),
        @vcVersion       VARCHAR(8000),
        @vcProgramName   VARCHAR(100),
        @vcCRC           VARCHAR(8000),  
        @vcInn           VARCHAR(50),
        @vcKpp           VARCHAR(9),
        @vcOkpo          VARCHAR(10),
        @vcOkato         VARCHAR(11),
        @vcPPP           VARCHAR(50),
        @iUchr_Link      INT,
        @vcOrgname_Uchr  VARCHAR(1000),
        @vcInn_Uchr      VARCHAR(50),
        @vcKpp_Uchr      VARCHAR(9),
        @vcOKPO_UCHR     VARCHAR(10),
        @vcSurname       VARCHAR(60),
        @vcFirstName     VARCHAR(60),
        @vcMiddleName    VARCHAR(60),
        @vcSurname_GB    VARCHAR(60),
        @vcFirstName_GB  VARCHAR(60),
        @vcMiddleName_GB VARCHAR(60),
        @vcDateRegl      VARCHAR(10),
        @vcExec          VARCHAR(8000),  
        @bCancel         BIT,
        @iReturn         INT,
        @vcNAME          VARCHAR(8000),
        @vcFORM_CODE     VARCHAR(8000),  
        @vcFILE_NAME_XSD VARCHAR(100),    
        @CODE            VARCHAR(100),
        @v_code          VARCHAR(100),
        @c_code          VARCHAR(100),
        @vc_code         VARCHAR(100),
        @vcc_code        VARCHAR(100)
DECLARE @val             VARCHAR(8000), 
        @val2            VARCHAR(8000), 
        @str             VARCHAR(8000),
        @str1            VARCHAR(8000) 
          
CREATE TABLE #tabXML ([TXT]	  VARCHAR(8000),
							 [ORDERS] INT IDENTITY(1,1))

IF OBJECT_ID('tempdb..#tabExportOutput') IS NOT NULL  
BEGIN  
   SELECT @vcVersion = [VERSION]  
   FROM #tabExportOutput   
END  
  
IF @bCancel = 1  
BEGIN  
   RETURN 0  
END  
  
SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_ORG  = [Link_Organization],
       --Дата начала
       @dBEGIN_DATE = A.[Begin_Date],
       @sYear = CAST(YEAR(@dBEGIN_DATE) AS VARCHAR(4)),  
       @vcDateRegl = convert(varchar(12), @dBEGIN_DATE+1, 104) 
FROM dbo.[report_saved_forms] A  
WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM   

SET @bCancel = 0         
SET @vcNAME = 'Отчет о финансовых результатах деятельности учреждения'  
SET @vcFORM_CODE = '0503721'  
SET @vcVersion = '5.02'
SELECT @vcProgramName = CASE WHEN CODE_TASK = 'SMETA'   THEN 'СМЕТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'KADRY'   THEN 'КАДРЫ-КС'
                             WHEN CODE_TASK = 'SALARY'  THEN 'ЗАРПЛАТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'DELO'    THEN 'ДЕЛО-КС'
                             WHEN CODE_TASK = 'ADMIN'   THEN 'АДМИНИСТРАТОР'
                             ELSE ''
                        END       
FROM [dbo].USER_INFO                                  

--Таблица
SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 1

CREATE TABLE #tabAttr ([CHECKED] INT, 
                       [UPD]     INT, 
                       [DEL]     INT, 
                       [LINK_SAVED_FORM] INT, 
                       [LINK_ROW] INT, 
                       [ORDERS]   INT, 
                       [CALC_ORDERS] INT, 
                       [PRINT_NULL] INT, 
                       [CODE] VARCHAR(50), 
                       COL1 VARCHAR(8000), COL2 VARCHAR(8000), COL3 VARCHAR(8000), COL4 VARCHAR(8000), 
                       COL5 VARCHAR(8000), COL6 VARCHAR(8000), COL7 VARCHAR(8000), itog INT)
                       
  SET @vcExec = 'INSERT #tabAttr
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  EXEC(@vcExec)
  
-- Выгрузка подписей.
 SELECT   @vcOrgname = substring(dbo.[RA_XML_MASK](d.[FULL_NAME]),1,1000),
          @vcInn     = rtrim(ltrim(d.[INN])),
          @vcKpp     = rtrim(ltrim(d.[KPP])),
          @vcOkpo    = d.[OKPO],
          @vcOkato   = d.[OKATO],
          @iUchr_Link    = d.[UCHR_LINK]
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iLINK_ORG
 SELECT   @vcInn_Uchr     = isnull(d.[INN],''),
          @vcKpp_Uchr     = isnull(d.[KPP],''),
          @vcOkpo_Uchr    = isnull(d.[OKPO],''),
          @vcOrgName_Uchr = isnull(dbo.[RA_XML_MASK](d.[FULL_NAME]),'')
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iUchr_Link
 SELECT @vcKOD_ORGAN = [SONO],
        @vcPPP       = [VED]
 FROM PrintDoc_GetDepData2(@iLINK_ORG)   
 SELECT @vcSurname=ch.[FM],
        @vcFirstName=ch.[IM],
        @vcMiddleName=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Руководитель') ch
 WHERE ch.link_dep = @iLINK_ORG
 SELECT @vcSurname_GB=ch.[FM],
        @vcFirstName_GB=ch.[IM],
        @vcMiddleName_GB=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Главный бухгалтер') ch
 WHERE ch.link_dep = @iLINK_ORG
 IF (@vcSurname='' OR @vcSurname IS NULL OR LEN(@vcSurname)=0) SELECT @vcSurname='A'
 IF (@vcFirstName='' OR @vcFirstName IS NULL OR LEN(@vcFirstName)=0) SELECT @vcFirstName='A'
IF (@vcInn is null or @vcInn = '') SELECT @vcInn='9999999999'
 IF (@vcKpp IS NULL OR @vcKpp = '') SELECT @vcKpp='999999999'
 IF @vcKOD_ORGAN IS NULL SELECT @vcKOD_ORGAN=''
--Дата документа
 SELECT @dFORM_DATE=GETDATE()
  
SET @vcCRC = RTRIM(CONVERT(VARCHAR(100), NEWID()))  
--Имя файла
SELECT @vcExec =  'NO_BOUCHR7_' +  @vcKOD_ORGAN+ '_' +  
                  @vcKOD_ORGAN+ '_' + @vcINN + @vcKPP + '_' +  
                  CAST(YEAR(@dFORM_DATE) AS VARCHAR(4)) + 
                  RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '_' + @vcCRC,
       @vcFILE_NAME =  @vcExec + '.xml'
--Вставка XML
INSERT #tabXML([TXT]) VALUES ('<?xml  version ="1.0"  encoding ="windows-1251"?>')
INSERT #tabXML([TXT]) VALUES ('<Файл ИдФайл="'+@vcExec+'" '+'ВерсПрог="'+@vcProgramName+'" '+'ВерсФорм="'+@vcVersion+'">')
INSERT #tabXML([TXT]) VALUES ('  <Документ КНД="'+@vcFORM_CODE+'" ДатаДок="'+RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '.' +  
                               RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ '.' + CAST(YEAR(@dFORM_DATE) AS VARCHAR(4))+
                               '" Период="34" ОтчетГод="'+CAST(@sYear AS VARCHAR(4))+'" НомКорр="0">')
INSERT #tabXML([TXT]) VALUES ('    <СвНП')
IF @vcOkpo<>'' AND LEN(@vcOkpo) BETWEEN 8 AND 10 
INSERT #tabXML([TXT]) VALUES (' ОКПО="'+LTRIM(RTRIM(@vcOkpo))+'"') 
IF @vcOkato<>'' AND LEN(@vcOkato)=11
INSERT #tabXML([TXT]) VALUES (' ОКАТО="'+@vcOkato+'"')
IF @vcOkpo_Uchr<>'' AND LEN(@vcOkpo_Uchr) BETWEEN 8 AND 10 
INSERT #tabXML([TXT]) VALUES (' ОКПО_Учр="'+LTRIM(RTRIM(@vcOkpo_Uchr))+'"') 
IF @vcPPP<>'' AND LEN(@vcPPP)<4
INSERT #tabXML([TXT]) VALUES (' ГлаваБК="' + @vcPPP + '"')
INSERT #tabXML([TXT]) VALUES ('>')
INSERT #tabXML([TXT]) VALUES ('<НПЮЛ НаимОрг="'+@vcOrgname+'" ИННЮЛ="'+@vcInn+'" КПП="'+@vcKpp+'"')
IF @vcOrgName_Uchr<>'' 
INSERT #tabXML([TXT]) VALUES (' Учредит="'+@vcOrgName_Uchr+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('</СвНП>')
INSERT #tabXML([TXT]) VALUES ('<Подписант ПрПодп="1">')
INSERT #tabXML([TXT]) VALUES ('<ФИО Фамилия="'+@vcSurname+'" Имя="'+@vcFirstName+'"')
IF @vcMiddleName<>''
INSERT #tabXML([TXT]) VALUES ('Отчество="'+@vcMiddleName+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
IF @vcSurname_GB<>'' AND @vcFirstName_GB<>''
begin
INSERT #tabXML([TXT]) VALUES ('<ФИОГлБух Фамилия="'+@vcSurname_GB+'" Имя="'+@vcFirstName_GB+'"')
IF @vcMiddleName_GB<>''
INSERT #tabXML([TXT]) VALUES ('Отчество="'+@vcMiddleName_GB+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
end
INSERT #tabXML([TXT]) VALUES ('</Подписант>')
INSERT #tabXML([TXT]) VALUES ('<ОтчетФинРез ДатаОтч="'+@vcDateRegl+'" ОКЕИ="383">')
-----------------------------------------
INSERT #tabXML([TXT]) VALUES ('            <Доход>')
INSERT INTO #tabXML(TXT)SELECT'                <ДохВс'+
                        CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END
                        + ' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '010' 
INSERT INTO #tabXML(TXT)SELECT'                <ДохСобств'+
                        CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  
                        + ' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '030'
INSERT INTO #tabXML(TXT)SELECT'                <ДохПлатУсл'+
                        CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  
                        + ' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '040'
INSERT INTO #tabXML(TXT)SELECT'                <ДохШтраф'+
                        CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  
                        +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '050'
INSERT #tabXML([TXT]) VALUES ('                <БВПостБюдж>')
INSERT INTO #tabXML(TXT)SELECT'                    <БВПостБюджВс'+
                        CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  
                        +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '060'
INSERT INTO #tabXML(TXT)SELECT'                    <ПостИно'+
                        CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  
                        +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '062'
INSERT INTO #tabXML(TXT)SELECT'                    <ПостМФО'+
                        CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  
                        +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '063'
INSERT #tabXML([TXT]) VALUES ('                </БВПостБюдж>')
INSERT #tabXML([TXT]) VALUES ('                <ДохАктив>')
INSERT INTO #tabXML(TXT)SELECT'                    <ДохАктивВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END
                        +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '090'
INSERT INTO #tabXML(TXT)SELECT'                    <ПереоцАкт'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '091'
INSERT INTO #tabXML(TXT)SELECT'                    <РеализАкт'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '092'
INSERT INTO #tabXML(TXT)SELECT'                    <ДохРеализНеФА'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '093'
INSERT INTO #tabXML(TXT)SELECT'                    <ДохРеализФА'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '096'
INSERT INTO #tabXML(TXT)SELECT'                    <ЧрДохОпАкт'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '099'                        
INSERT #tabXML([TXT]) VALUES ('                </ДохАктив>')
INSERT #tabXML([TXT]) VALUES ('                <ДохПроч>')
INSERT INTO #tabXML(TXT)SELECT'                    <ДохПрочВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '100'
INSERT INTO #tabXML(TXT)SELECT'                    <СубГосЗадан'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '101'
INSERT INTO #tabXML(TXT)SELECT'                    <СубИнЦел'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '102'
INSERT INTO #tabXML(TXT)SELECT'                    <БюджИнвест'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '103'
INSERT INTO #tabXML(TXT)SELECT'                    <ДохИные'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '104'
INSERT #tabXML([TXT]) VALUES ('                </ДохПроч>')
INSERT INTO #tabXML(TXT)SELECT'                <ДохБудущПер'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '110'
INSERT #tabXML([TXT]) VALUES ('            </Доход>')
INSERT #tabXML([TXT]) VALUES ('            <Расход>')
INSERT INTO #tabXML(TXT)SELECT'                <РасхВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '150'
INSERT #tabXML([TXT]) VALUES ('                <ОплатТруд>')
INSERT INTO #tabXML(TXT)SELECT'                    <ОплатТрудВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '160'
INSERT INTO #tabXML(TXT)SELECT'                    <ЗарабПлат'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '161'
INSERT INTO #tabXML(TXT)SELECT'                    <ПрочВыпл'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '162'
INSERT INTO #tabXML(TXT)SELECT'                    <НачислВыплОТ'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '163'
INSERT #tabXML([TXT]) VALUES ('                </ОплатТруд>')
INSERT #tabXML([TXT]) VALUES ('                <ПриобРаб>')
INSERT INTO #tabXML(TXT)SELECT'                    <ПриобРабВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '170'
INSERT INTO #tabXML(TXT)SELECT'                    <УслугСвяз'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '171'
INSERT INTO #tabXML(TXT)SELECT'                    <ТранспУслуг'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '172'
INSERT INTO #tabXML(TXT)SELECT'                    <КоммунУслуг'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '173'
INSERT INTO #tabXML(TXT)SELECT'                    <АрендПлатИм'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '174'
INSERT INTO #tabXML(TXT)SELECT'                    <РабСодержИм'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '175'
INSERT INTO #tabXML(TXT)SELECT'                    <ПрочРаб'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '176'
INSERT #tabXML([TXT]) VALUES ('                </ПриобРаб>')
INSERT #tabXML([TXT]) VALUES ('                <ОбслДолг>')
INSERT INTO #tabXML(TXT)SELECT'                    <ОбслДолгВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '190'
INSERT INTO #tabXML(TXT)SELECT'                    <ОбслДолгРез'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '191'
INSERT INTO #tabXML(TXT)SELECT'                    <ОбслДолгНеРез'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '192'
INSERT #tabXML([TXT]) VALUES ('                </ОбслДолг>')
INSERT #tabXML([TXT]) VALUES ('                <ПеречОрг>')
INSERT INTO #tabXML(TXT)SELECT'                    <ПеречОргВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '210'
INSERT INTO #tabXML(TXT)SELECT'                    <ПеречГосОрг'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '211'
INSERT INTO #tabXML(TXT)SELECT'                    <ПеречКрГосОрг'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '212'
INSERT #tabXML([TXT]) VALUES ('                </ПеречОрг>')
INSERT #tabXML([TXT]) VALUES ('                <ПеречБюдж>')
INSERT INTO #tabXML(TXT)SELECT'                    <ПеречБюджВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '230'
INSERT INTO #tabXML(TXT)SELECT'                    <ПеречИно'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '232'
INSERT INTO #tabXML(TXT)SELECT'                    <ПеречМО'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '233'                        
INSERT #tabXML([TXT]) VALUES ('                </ПеречБюдж>')
INSERT #tabXML([TXT]) VALUES ('                <СоцОбесп>')
INSERT INTO #tabXML(TXT)SELECT'                    <СоцОбеспВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '240'
INSERT INTO #tabXML(TXT)SELECT'                    <ПомНасел'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '242'
INSERT INTO #tabXML(TXT)SELECT'                    <ПособГосУпр'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '243'
INSERT #tabXML([TXT]) VALUES ('                </СоцОбесп>')
INSERT INTO #tabXML(TXT)SELECT'                <РасхПроч'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '250'                        
INSERT #tabXML([TXT]) VALUES ('                <РасхОпАкт>')
INSERT INTO #tabXML(TXT)SELECT'                    <РасхОпАктВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '260'
INSERT INTO #tabXML(TXT)SELECT'                    <АмортОСиНМА'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '261'
INSERT INTO #tabXML(TXT)SELECT'                    <РасхМатЗ'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '264'
INSERT INTO #tabXML(TXT)SELECT'                    <ЧрРасхОпАкт'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '269'
INSERT #tabXML([TXT]) VALUES ('                </РасхОпАкт>')
INSERT INTO #tabXML(TXT)SELECT'                <РасхБудущПер'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '290'
INSERT #tabXML([TXT]) VALUES ('            </Расход>')
INSERT #tabXML([TXT]) VALUES ('            <ЧистОперРез>')
INSERT INTO #tabXML(TXT)SELECT'                <ЧистОперРезВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '300'
INSERT INTO #tabXML(TXT)SELECT'                <ОперРезДоНал'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '301'
INSERT INTO #tabXML(TXT)SELECT'                <НалогПриб'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '302'
INSERT #tabXML([TXT]) VALUES ('                <ОперНеФА>')
INSERT INTO #tabXML(TXT)SELECT'                    <ОперНеФАВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '310'
INSERT #tabXML([TXT]) VALUES ('                    <ЧистПостОС>')
INSERT INTO #tabXML(TXT)SELECT'                        <ЧистПоступ'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '320'
INSERT INTO #tabXML(TXT)SELECT'                        <УвелСтоим'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '321'
INSERT INTO #tabXML(TXT)SELECT'                        <УменСтоим'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '322'
INSERT #tabXML([TXT]) VALUES ('                    </ЧистПостОС>')
INSERT #tabXML([TXT]) VALUES ('                    <ЧистПостНМА>')
INSERT INTO #tabXML(TXT)SELECT'                        <ЧистПоступ'+
                        CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  
                        +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '330'
INSERT INTO #tabXML(TXT)SELECT'                        <УвелСтоим'+
                        CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  
                        +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '331'
INSERT INTO #tabXML(TXT)SELECT'                        <УменСтоим'+
                        CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  
                        +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '332'
INSERT #tabXML([TXT]) VALUES ('                    </ЧистПостНМА>')
INSERT #tabXML([TXT]) VALUES ('                    <ЧистПостНПрА>')
INSERT INTO #tabXML(TXT)SELECT'                        <ЧистПоступ'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '350'
INSERT INTO #tabXML(TXT)SELECT'                        <УвелСтоим'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '351'
INSERT INTO #tabXML(TXT)SELECT'                        <УменСтоим'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '352'
INSERT #tabXML([TXT]) VALUES ('                    </ЧистПостНПрА>')
INSERT #tabXML([TXT]) VALUES ('                    <ЧистПостМатЗ>')
INSERT INTO #tabXML(TXT)SELECT'                        <ЧистПоступ'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '360'
INSERT INTO #tabXML(TXT)SELECT'                        <УвелСтоим'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '361'
INSERT INTO #tabXML(TXT)SELECT'                        <УменСтоим'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '362'
INSERT #tabXML([TXT]) VALUES ('                    </ЧистПостМатЗ>')
INSERT #tabXML([TXT]) VALUES ('                    <ЧистИзмЗатр>')
INSERT INTO #tabXML(TXT)SELECT'                        <ЧистИзмЗатрВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '370'
INSERT INTO #tabXML(TXT)SELECT'                        <УвелЗатр ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '371'
INSERT INTO #tabXML(TXT)SELECT'                        <УменЗатр ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '372'
INSERT #tabXML([TXT]) VALUES ('                    </ЧистИзмЗатр>')
INSERT #tabXML([TXT]) VALUES ('                </ОперНеФА>')
INSERT #tabXML([TXT]) VALUES ('                <ОперФинАктОб>')                       
INSERT INTO #tabXML(TXT)SELECT'                    <ОперФинАктОбВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '380'
INSERT #tabXML([TXT]) VALUES ('                    <ОперФинАкт>')
INSERT INTO #tabXML(TXT)SELECT'                        <ОперФинАктВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '390'
INSERT #tabXML([TXT]) VALUES ('                        <ЧистПостСрУчр>')
INSERT INTO #tabXML(TXT)SELECT'                            <ЧистПостСрУчрВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '410'
INSERT INTO #tabXML(TXT)SELECT'                            <ПостСред'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '411'
INSERT INTO #tabXML(TXT)SELECT'                            <ВыбытСред'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '412'
INSERT #tabXML([TXT]) VALUES ('                        </ЧистПостСрУчр>')
INSERT #tabXML([TXT]) VALUES ('                        <ЧистПостЦБ>')
INSERT INTO #tabXML(TXT)SELECT'                            <ЧистПоступ'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '420'
INSERT INTO #tabXML(TXT)SELECT'                            <УвелСтоим'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '421'
INSERT INTO #tabXML(TXT)SELECT'                            <УменСтоим'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '422'
INSERT #tabXML([TXT]) VALUES ('                        </ЧистПостЦБ>')
INSERT #tabXML([TXT]) VALUES ('                        <ЧистПостАкц>')
INSERT INTO #tabXML(TXT)SELECT'                            <ЧистПоступ'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '440'
INSERT INTO #tabXML(TXT)SELECT'                            <УвелСтоим'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '441'
INSERT INTO #tabXML(TXT)SELECT'                            <УменСтоим'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '442'
INSERT #tabXML([TXT]) VALUES ('                        </ЧистПостАкц>')
INSERT #tabXML([TXT]) VALUES ('                        <ЧистПредЗайм>')
INSERT INTO #tabXML(TXT)SELECT'                            <ЧистПредЗаймВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '460'
INSERT INTO #tabXML(TXT)SELECT'                            <УвелЗадолжЗайм'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '461'
INSERT INTO #tabXML(TXT)SELECT'                            <УменЗадолжЗайм'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '462'
INSERT #tabXML([TXT]) VALUES ('                        </ЧистПредЗайм>')
INSERT #tabXML([TXT]) VALUES ('                        <ЧистПостИнФА>')
INSERT INTO #tabXML(TXT)SELECT'                            <ЧистПоступ'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '470'
INSERT INTO #tabXML(TXT)SELECT'                            <УвелСтоим'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '471'
INSERT INTO #tabXML(TXT)SELECT'                            <УменСтоим'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '472'
INSERT #tabXML([TXT]) VALUES ('                        </ЧистПостИнФА>')
INSERT #tabXML([TXT]) VALUES ('                        <ЧистУвДебЗад>')
INSERT INTO #tabXML(TXT)SELECT'                            <ЧистУвелЗадВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '480'
INSERT INTO #tabXML(TXT)SELECT'                            <УвелЗадолж'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '481'
INSERT INTO #tabXML(TXT)SELECT'                            <УменЗадолж'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '482'
INSERT #tabXML([TXT]) VALUES ('                        </ЧистУвДебЗад>')
INSERT #tabXML([TXT]) VALUES ('                    </ОперФинАкт>')
INSERT #tabXML([TXT]) VALUES ('                    <ОперОбяз>')
INSERT INTO #tabXML(TXT)SELECT'                            <ОперОбязВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '510'
INSERT #tabXML([TXT]) VALUES ('                        <ЧистУвЗадРез>')
INSERT INTO #tabXML(TXT)SELECT'                            <ЧистУвелЗадВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '520'
INSERT INTO #tabXML(TXT)SELECT'                            <УвелЗадолж'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '521'
INSERT INTO #tabXML(TXT)SELECT'                            <УменЗадолж'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '522'
INSERT #tabXML([TXT]) VALUES ('                        </ЧистУвЗадРез>')
INSERT #tabXML([TXT]) VALUES ('                        <ЧистУвЗадНеРез>')
INSERT INTO #tabXML(TXT)SELECT'                            <ЧистУвелЗадВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '530'
INSERT INTO #tabXML(TXT)SELECT'                            <УвелЗадолж'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '531'
INSERT INTO #tabXML(TXT)SELECT'                            <УменЗадолж'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '532'
INSERT #tabXML([TXT]) VALUES ('                        </ЧистУвЗадНеРез>')
INSERT #tabXML([TXT]) VALUES ('                        <ЧистУвПрочЗад>')
INSERT INTO #tabXML(TXT)SELECT'                            <ЧистУвелЗадВс'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '540'
INSERT INTO #tabXML(TXT)SELECT'                            <УвелЗадолж'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '541'
INSERT INTO #tabXML(TXT)SELECT'                            <УменЗадолж'+ CASE WHEN ta.COL3<>'' THEN ' КодАналит="'+LEFT(ta.COL3,3)+'"' ELSE '' END  +' ЦелевСред="'+ta.COL4+'" ОказУслуг="'+ta.COL5+'" СрВремРасп="'+ta.COL6+'" Итого="'+ta.COL7+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '542'
INSERT #tabXML([TXT]) VALUES ('                        </ЧистУвПрочЗад>')
INSERT #tabXML([TXT]) VALUES ('                    </ОперОбяз>')
INSERT #tabXML([TXT]) VALUES ('                </ОперФинАктОб>')
INSERT #tabXML([TXT]) VALUES ('            </ЧистОперРез>')
--------------------------------------------
INSERT #tabXML([TXT]) VALUES ('</ОтчетФинРез>')
INSERT #tabXML([TXT]) VALUES ('</Документ>')
INSERT #tabXML([TXT]) VALUES ('</Файл>')
----------------------------------------
INSERT #Files ([TXT], [NAMEFILE],  [NAMEFILE_ARH],  [OrderFile],[LINK_SAVED_FORM])
SELECT         [TXT], @vcFILE_NAME,@vcFILE_NAME_XSD,[ORDERS],   @iLINK_SAVED_FORM
FROM #tabXML
DROP TABLE #tabXML  

GO
GRANT ALL ON dbo.[RA_EXPORT_FORM_FNS_721] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
IF EXISTS (SELECT * 
           FROM dbo.[SYSOBJECTS]
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_EXPORT_FORM_FNS_737]') AND 
                 OBJECTPROPERTY(ID, N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_EXPORT_FORM_FNS_737]
END
GO
----------------------
CREATE PROCEDURE [dbo].[RA_EXPORT_FORM_FNS_737]
	@iLINK_SAVED_FORM	INT						-- Линк выгружаемой формы  
	,@vcFILE_NAME		VARCHAR(100)='' OUTPUT	-- Имя текстового файла  
	,@iMODE				INT=1					-- Формат: 2-внутренний, 1-минфиновский  
AS  
  
SET NOCOUNT ON  
SET DATEFORMAT dmy  

DECLARE @iLINK_FORM		 INT,
      	@iLINK_TABLE	 INT,
        @iLINK_ORG       INT, 
        @dBEGIN_DATE     DATETIME,
        @dFORM_DATE      DATETIME,
        @sYear           SMALLINT, 
        @vcOrgname       VARCHAR(1000),
        @vcKOD_ORGAN     VARCHAR(8000),
        @vcVersion       VARCHAR(8000),
        @vcProgramName   VARCHAR(100),
        @vcCRC           VARCHAR(8000),  
        @vcInn           VARCHAR(50),
        @vcKpp           VARCHAR(9),
        @vcOkpo          VARCHAR(10),
        @vcOkato         VARCHAR(11),
        @vcFO            VARCHAR(2),
        @vcPPP           VARCHAR(50),
        @iUchr_Link      INT,
        @vcOrgname_Uchr  VARCHAR(1000),
        @vcInn_Uchr      VARCHAR(50),
        @vcKpp_Uchr      VARCHAR(9),
        @vcOKPO_UCHR	 VARCHAR(10),
        @vcSurname       VARCHAR(60),
        @vcFirstName     VARCHAR(60),
        @vcMiddleName    VARCHAR(60),
        @vcSurname_GB    VARCHAR(60),
        @vcFirstName_GB  VARCHAR(60),
        @vcMiddleName_GB VARCHAR(60),
        @vcDateRegl      VARCHAR(10),
        @vcExec          VARCHAR(8000),  
        @bCancel         BIT,
        @iReturn         INT,
        @vcNAME          VARCHAR(8000),
        @vcFORM_CODE     VARCHAR(8000),  
        @vcFILE_NAME_XSD VARCHAR(100),    
        @vcTableName     VARCHAR(8000), 
        @CODE            VARCHAR(100)
DECLARE @val             VARCHAR(8000), 
        @val2            VARCHAR(8000), 
        @str             VARCHAR(8000)
          
CREATE TABLE #tabXML ([TXT]	  VARCHAR(8000),
							 [ORDERS] INT IDENTITY(1,1))

IF OBJECT_ID('tempdb..#tabExportOutput') IS NOT NULL  
BEGIN  
   SELECT @vcVersion = [VERSION]  
   FROM #tabExportOutput   
END  
  
IF @bCancel = 1  
BEGIN  
   RETURN 0  
END  
  
SET @bCancel = 0         
SET @vcNAME = 'Отчет об исполнении учреждением плана его финансово-хозяйственной деятельности'  
SET @vcFORM_CODE = '0503737'  
SET @vcVersion = '5.02'
SELECT @vcProgramName = CASE WHEN CODE_TASK = 'SMETA'   THEN 'СМЕТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'KADRY'   THEN 'КАДРЫ-КС'
                             WHEN CODE_TASK = 'SALARY'  THEN 'ЗАРПЛАТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'DELO'    THEN 'ДЕЛО-КС'
                             WHEN CODE_TASK = 'ADMIN'   THEN 'АДМИНИСТРАТОР'
                             ELSE ''
                        END       
FROM [dbo].USER_INFO                                  
SELECT @vcFO = RTRIM(dbo.[RN_GET_ATR_VALUE](@iLINK_SAVED_FORM,'REPORTS_ATR_VID'))

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_ORG  = [Link_Organization],         
	--Дата начала   
	   @dBEGIN_DATE	= A.Begin_date,
	   @sYear = CAST(YEAR(@dBEGIN_DATE) AS VARCHAR(4)),  
       @vcDateRegl = convert(varchar(12), @dBEGIN_DATE+1, 104) 
FROM dbo.[report_saved_forms] A  
WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM   

SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 1

CREATE TABLE #tabAttr ([CHECKED] INT, 
                       [UPD]     INT, 
                       [DEL]     INT, 
                       [LINK_SAVED_FORM] INT, 
                       [LINK_ROW] INT, 
                       [ORDERS]   INT, 
                       [CALC_ORDERS] INT, 
                       [PRINT_NULL] INT, 
                       [CODE] VARCHAR(50), COL1 VARCHAR(8000), 
                       COL2 VARCHAR(8000), COL3 VARCHAR(8000), COL4 VARCHAR(8000), 
                       COL5 VARCHAR(8000), COL6 VARCHAR(8000), COL7 VARCHAR(8000), 
                       COL8 VARCHAR(8000), COL9 VARCHAR(8000), COL10 VARCHAR(8000), 
                       itog VARCHAR(8000))
  SET @vcExec = 'INSERT #tabAttr
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  EXEC(@vcExec)

-- Выгрузка подписей.
 SELECT   @vcOrgname = substring(dbo.[RA_XML_MASK](d.[FULL_NAME]),1,1000),
          @vcInn     = rtrim(ltrim(d.[INN])),
          @vcKpp     = rtrim(ltrim(d.[KPP])),
          @vcOkpo    = d.[OKPO],
          @vcOkato   = d.[OKATO],
          @iUchr_Link    = d.[UCHR_LINK]
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iLINK_ORG
 SELECT   @vcInn_Uchr     = isnull(d.[INN],''),
          @vcKpp_Uchr     = isnull(d.[KPP],''),
          @vcOkpo_Uchr    = isnull(d.[OKPO],''),
          @vcOrgName_Uchr = isnull(dbo.[RA_XML_MASK](d.[FULL_NAME]),'')
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iUchr_Link
 SELECT @vcKOD_ORGAN = [SONO],
        @vcPPP       = [VED]
 FROM PrintDoc_GetDepData2(@iLINK_ORG)   
 SELECT @vcSurname=ch.[FM],
        @vcFirstName=ch.[IM],
        @vcMiddleName=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Руководитель') ch
 WHERE ch.link_dep = @iLINK_ORG
 SELECT @vcSurname_GB=ch.[FM],
        @vcFirstName_GB=ch.[IM],
        @vcMiddleName_GB=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Главный бухгалтер') ch
 WHERE ch.link_dep = @iLINK_ORG
 IF (@vcSurname='' OR @vcSurname IS NULL OR LEN(@vcSurname)=0) SELECT @vcSurname='A'
 IF (@vcFirstName='' OR @vcFirstName IS NULL OR LEN(@vcFirstName)=0) SELECT @vcFirstName='A'
 IF @vcInn IS NULL SELECT @vcInn='9999999999'
 IF @vcKpp IS NULL SELECT @vcKpp='999999999'
 IF @vcKOD_ORGAN IS NULL SELECT @vcKOD_ORGAN=''

--Дата документа
 SELECT @dFORM_DATE=GETDATE()
  
SET @vcCRC = RTRIM(CONVERT(VARCHAR(100), NEWID()))  
--Имя файла
SELECT @vcExec =  'NO_BOUCHR6.' +  @vcFO + '_' + @vcKOD_ORGAN+ '_' +  
                  @vcKOD_ORGAN+ '_' + @vcINN + @vcKPP + '_' +  
                  CAST(YEAR(@dFORM_DATE) AS VARCHAR(4)) + 
                  RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '_' + @vcCRC,
       @vcFILE_NAME =  @vcExec + '.xml',
       @vcFILE_NAME_XSD =  @vcExec + '.xsd'
--Вставка XML
INSERT #tabXML([TXT]) VALUES ('<?xml  version ="1.0"  encoding ="windows-1251"?>')
INSERT #tabXML([TXT]) VALUES ('<Файл ИдФайл="'+@vcExec+'" '+'ВерсПрог="'+@vcProgramName+'" '+'ВерсФорм="'+@vcVersion+'">')
INSERT #tabXML([TXT]) VALUES ('  <Документ КНД="' + @vcFORM_CODE + '" ДатаДок="'+RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '.' +  
                               RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ '.' + CAST(YEAR(@dFORM_DATE) AS VARCHAR(4))+
                               '" Период="34" ОтчетГод="'+CAST(@sYear AS VARCHAR(4))+'" НомКорр="0">')
INSERT #tabXML([TXT]) VALUES ('    <СвНП')
IF @vcOkpo<>'' AND LEN(@vcOkpo) BETWEEN 8 AND 10 
begin INSERT #tabXML([TXT]) VALUES (' ОКПО="'+LTRIM(RTRIM(@vcOkpo))+'"') end
IF @vcOkato<>'' AND LEN(@vcOkato)=11
begin INSERT #tabXML([TXT]) VALUES (' ОКАТО="'+@vcOkato+'"') END
IF @vcOkpo_Uchr<>'' AND LEN(@vcOkpo_Uchr) BETWEEN 8 AND 10 
INSERT #tabXML([TXT]) VALUES (' ОКПО_Учр="'+LTRIM(RTRIM(@vcOkpo_Uchr))+'"') 
INSERT #tabXML([TXT]) VALUES (' ВидФО="' + @vcFO + '"')
IF @vcPPP<>'' AND LEN(@vcPPP)<4
INSERT #tabXML([TXT]) VALUES (' ГлаваБК="' + @vcPPP + '"')
INSERT #tabXML([TXT]) VALUES ('>')
INSERT #tabXML([TXT]) VALUES ('      <НПЮЛ НаимОрг="'+@vcOrgname+'" ИННЮЛ="'+@vcInn+'" КПП="'+@vcKpp+'"')
IF @vcOrgName_Uchr<>'' 
begin INSERT #tabXML([TXT]) VALUES (' Учредит="'+@vcOrgName_Uchr+'"') end
IF @vcInn_Uchr<>''
begin INSERT #tabXML([TXT]) VALUES (' ИННЮЛ_Учр="'+@vcInn_Uchr+'"') end
IF @vcKpp_Uchr<>''
begin INSERT #tabXML([TXT]) VALUES (' КПП_Учр="'+@vcKpp_Uchr+'"') end
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('    </СвНП>')
INSERT #tabXML([TXT]) VALUES ('	   <Подписант ПрПодп="1">')
INSERT #tabXML([TXT]) VALUES ('	     <ФИО Фамилия="'+@vcSurname+'" Имя="'+@vcFirstName+'"')
IF @vcMiddleName<>''
INSERT #tabXML([TXT]) VALUES ('           Отчество="'+@vcMiddleName+'"')
INSERT #tabXML([TXT]) VALUES ('      />')
IF @vcSurname_GB<>'' AND @vcFirstName_GB<>''
begin
INSERT #tabXML([TXT]) VALUES ('	     <ФИОГлБух Фамилия="'+@vcSurname_GB+'" Имя="'+@vcFirstName_GB+'"')
IF @vcMiddleName_GB<>''
INSERT #tabXML([TXT]) VALUES ('           Отчество="'+@vcMiddleName_GB+'"')
INSERT #tabXML([TXT]) VALUES ('      />')
end
INSERT #tabXML([TXT]) VALUES ('	   </Подписант>')
INSERT #tabXML([TXT]) VALUES ('        <ОтчетПланФХД ДатаОтч="'+@vcDateRegl+'" ОКЕИ="383">')
INSERT #tabXML([TXT]) VALUES ('            <Доход>')
INSERT INTO #tabXML(TXT)SELECT'                <ДохВс КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '010' 
INSERT #tabXML([TXT]) VALUES ('                <ДохСобств>')
INSERT INTO #tabXML(TXT)SELECT'                    <ДохСобствВс КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '030' 
INSERT INTO #tabXML(TXT)SELECT'                    <ДохАрендАкт КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '031'
INSERT #tabXML([TXT]) VALUES ('                </ДохСобств>')
INSERT INTO #tabXML(TXT)SELECT'                <ДохПлатУсл КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '040' 
INSERT INTO #tabXML(TXT)SELECT'                <ДохШтраф КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '050'
INSERT #tabXML([TXT]) VALUES ('                <БВПостБюдж>')
INSERT INTO #tabXML(TXT)SELECT'                    <БВПостБюджВс КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '060' 
INSERT INTO #tabXML(TXT)SELECT'                    <ПостИно КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '062'
INSERT INTO #tabXML(TXT)SELECT'                    <ПостМФО КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '063'
INSERT #tabXML([TXT]) VALUES ('                </БВПостБюдж>')
INSERT #tabXML([TXT]) VALUES ('                <ДохАктив>')
INSERT INTO #tabXML(TXT)SELECT'                    <ДохАктивВс УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '090' 
INSERT INTO #tabXML(TXT)SELECT'                    <ВыбытОС КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '092'
INSERT INTO #tabXML(TXT)SELECT'                    <ВыбытНМА КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '093'
INSERT INTO #tabXML(TXT)SELECT'                    <ВыбНПрА КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '094' 
INSERT INTO #tabXML(TXT)SELECT'                    <ВыбМатЗ КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '095'
INSERT INTO #tabXML(TXT)SELECT'                    <ВыбЦБ КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '096'
INSERT INTO #tabXML(TXT)SELECT'                    <ВыбАкц КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '097'
INSERT INTO #tabXML(TXT)SELECT'                    <ВыбИнФА КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '098'
INSERT #tabXML([TXT]) VALUES ('                </ДохАктив>')
INSERT #tabXML([TXT]) VALUES ('                <ДохПроч>')
INSERT INTO #tabXML(TXT)SELECT'                    <ДохПрочВс КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '100' 
INSERT INTO #tabXML(TXT)SELECT'                    <СубГосЗадан КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '101'
INSERT INTO #tabXML(TXT)SELECT'                    <СубИнЦел КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '102'
INSERT INTO #tabXML(TXT)SELECT'                    <БюджИнвест КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '103' 
INSERT INTO #tabXML(TXT)SELECT'                    <ДохИные КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '104'
INSERT #tabXML([TXT]) VALUES ('                </ДохПроч>')
INSERT #tabXML([TXT]) VALUES ('            </Доход>')
INSERT #tabXML([TXT]) VALUES ('            <Расход>')
INSERT INTO #tabXML(TXT)SELECT'                <РасхВс УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '200'
INSERT #tabXML([TXT]) VALUES ('                <ОплатТруд>')
INSERT INTO #tabXML(TXT)SELECT'                    <ОплатТрудВс КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '160'
INSERT INTO #tabXML(TXT)SELECT'                    <ЗарабПлат КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '161'
INSERT INTO #tabXML(TXT)SELECT'                    <ПрочВыпл КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '162' 
INSERT INTO #tabXML(TXT)SELECT'                    <НачислВыплОТ КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '163'
INSERT #tabXML([TXT]) VALUES ('                </ОплатТруд>')
INSERT #tabXML([TXT]) VALUES ('                <ПриобРаб>')
INSERT INTO #tabXML(TXT)SELECT'                    <ПриобРабВс КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '170'
INSERT INTO #tabXML(TXT)SELECT'                    <УслугСвяз КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '171'
INSERT INTO #tabXML(TXT)SELECT'                    <ТранспУслуг КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '172' 
INSERT INTO #tabXML(TXT)SELECT'                    <КоммунУслуг КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '173'
INSERT INTO #tabXML(TXT)SELECT'                    <АрендПлатИм КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '174'
INSERT INTO #tabXML(TXT)SELECT'                    <РабСодержИм КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '175'
INSERT INTO #tabXML(TXT)SELECT'                    <ПрочРаб КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '176' 
INSERT #tabXML([TXT]) VALUES ('                </ПриобРаб>')
INSERT #tabXML([TXT]) VALUES ('                <ОбслДолг>')
INSERT INTO #tabXML(TXT)SELECT'                    <ОбслДолгВс КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '190'
INSERT INTO #tabXML(TXT)SELECT'                    <ОбслДолгРез КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '191'
INSERT INTO #tabXML(TXT)SELECT'                    <ОбслДолгНеРез КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '192' 
INSERT #tabXML([TXT]) VALUES ('                </ОбслДолг>')
INSERT #tabXML([TXT]) VALUES ('                <ПеречОрг>')
INSERT INTO #tabXML(TXT)SELECT'                    <ПеречОргВс КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '210'
INSERT INTO #tabXML(TXT)SELECT'                    <ПеречГосОрг КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '211'
INSERT INTO #tabXML(TXT)SELECT'                    <ПеречКрГосОрг КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '212' 
INSERT #tabXML([TXT]) VALUES ('                </ПеречОрг>')
INSERT #tabXML([TXT]) VALUES ('                <ПеречБюдж>')
INSERT INTO #tabXML(TXT)SELECT'                    <ПеречБюджВс КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '230'
INSERT INTO #tabXML(TXT)SELECT'                    <ПеречИно КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '232'
INSERT INTO #tabXML(TXT)SELECT'                    <ПеречМО КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '233' 
INSERT #tabXML([TXT]) VALUES ('                </ПеречБюдж>')
INSERT #tabXML([TXT]) VALUES ('                <СоцОбесп>')
INSERT INTO #tabXML(TXT)SELECT'                    <СоцОбеспВс КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '240'
INSERT INTO #tabXML(TXT)SELECT'                    <ПомНасел КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '242'
INSERT INTO #tabXML(TXT)SELECT'                    <ПособГосУпр КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '243' 
INSERT #tabXML([TXT]) VALUES ('                </СоцОбесп>')
INSERT INTO #tabXML(TXT)SELECT'                <РасхПроч КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '250'
INSERT #tabXML([TXT]) VALUES ('                <ПриобрНФА>')
INSERT INTO #tabXML(TXT)SELECT'                    <ПриобрНФАВс КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '260'
INSERT INTO #tabXML(TXT)SELECT'                    <ПриобрОС КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '261'
INSERT INTO #tabXML(TXT)SELECT'                    <ПриобрНМА КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '262'
INSERT INTO #tabXML(TXT)SELECT'                    <ПриобрНПрА КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '263'
INSERT INTO #tabXML(TXT)SELECT'                    <ПриобрМатЗ КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '264'  
INSERT #tabXML([TXT]) VALUES ('                </ПриобрНФА>')
INSERT #tabXML([TXT]) VALUES ('                <ПриобрФА>')
INSERT INTO #tabXML(TXT)SELECT'                    <ПриобрФАВс КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '270'
INSERT INTO #tabXML(TXT)SELECT'                    <ПриобрЦБ КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '271'
INSERT INTO #tabXML(TXT)SELECT'                    <ПриобрАкц КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '272'
INSERT INTO #tabXML(TXT)SELECT'                    <ПриобрИнФА КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '273' 
INSERT #tabXML([TXT]) VALUES ('                </ПриобрФА>')
INSERT #tabXML([TXT]) VALUES ('            </Расход>')
INSERT INTO #tabXML(TXT)SELECT'            <РезИсполн УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '450' 
INSERT #tabXML([TXT]) VALUES ('            <ИстФинанс>')
INSERT INTO #tabXML(TXT)SELECT'                <ИстФинансВс КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '500' 
INSERT #tabXML([TXT]) VALUES ('                <ВнутрИст>')
INSERT INTO #tabXML(TXT)SELECT'                    <ВнутрИстВс КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '520'
INSERT INTO #tabXML(TXT)SELECT'                    <КурсРазн КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '521'
INSERT INTO #tabXML(TXT)SELECT'                    <ПостЗайм КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '525'
INSERT INTO #tabXML(TXT)SELECT'                    <ВыплЗайм КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '526' 
INSERT INTO #tabXML(TXT)SELECT'                    <ПостРез КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '527'
INSERT INTO #tabXML(TXT)SELECT'                    <ПогашРез КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '528' 
INSERT #tabXML([TXT]) VALUES ('                </ВнутрИст>')                        
INSERT #tabXML([TXT]) VALUES ('                <ВнешнИст>')
INSERT INTO #tabXML(TXT)SELECT'                    <ВнешнИстВс КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '620'
INSERT INTO #tabXML(TXT)SELECT'                    <КурсРазн КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '621'
INSERT INTO #tabXML(TXT)SELECT'                    <ПостРез КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '625'
INSERT INTO #tabXML(TXT)SELECT'                    <ПогашНеРез КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '626'  
INSERT #tabXML([TXT]) VALUES ('                </ВнешнИст>')                          
INSERT #tabXML([TXT]) VALUES ('                <ИзмОстСр>')
INSERT INTO #tabXML(TXT)SELECT'                    <ИзмОстСрВс ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '700'
INSERT INTO #tabXML(TXT)SELECT'                    <УвОстСрВс КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '710'
INSERT INTO #tabXML(TXT)SELECT'                    <УмОстСрВс КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '720'
INSERT #tabXML([TXT]) VALUES ('                </ИзмОстСр>')                         
INSERT #tabXML([TXT]) VALUES ('                <ИзмВнутрОб>')
INSERT INTO #tabXML(TXT)SELECT'                    <ИзмВнутрОбВс УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '730'
INSERT INTO #tabXML(TXT)SELECT'                    <УвОстСрУч КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '731'
INSERT INTO #tabXML(TXT)SELECT'                    <УмОстСрВс КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '732'
INSERT #tabXML([TXT]) VALUES ('                </ИзмВнутрОб>')                         
INSERT #tabXML([TXT]) VALUES ('                <ИзмВнутрРасч>')
INSERT INTO #tabXML(TXT)SELECT'                    <ИзмВнутрРасчВс УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '820'
INSERT INTO #tabXML(TXT)SELECT'                    <УвОстВнуРасч КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '821'
INSERT INTO #tabXML(TXT)SELECT'                    <УмОстВнуРасч КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '822'
INSERT #tabXML([TXT]) VALUES ('                </ИзмВнутрРасч>')                       
INSERT #tabXML([TXT]) VALUES ('                <ИзмВнутрПрив>')
INSERT INTO #tabXML(TXT)SELECT'                    <ИзмВнутрПривВс УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '830'
INSERT INTO #tabXML(TXT)SELECT'                    <УвОстВнуРасч КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '831'
INSERT INTO #tabXML(TXT)SELECT'                    <УмОстВнуРасч КодАналит="'+case when ta.COL3 like '' then 'Х' else ta.COL3 end+'" УтвПланНазн="'+ta.COL4+'" ИспЛицСч="'+ta.COL5+'" ИспБанкСч="'+ta.COL6+'" ИспКасУчр="'+ta.COL7+'" ИспНекасОп="'+ta.COL8+'" ИспИтого="'+ta.COL9+'" НеИспПланНазн="'+ta.COL10+'" />'
                        FROM #tabAttr ta
                        WHERE ta.CODE LIKE '832'
INSERT #tabXML([TXT]) VALUES ('                </ИзмВнутрПрив>')                       
INSERT #tabXML([TXT]) VALUES ('            </ИстФинанс>') 
INSERT #tabXML([TXT]) VALUES ('        </ОтчетПланФХД>') 
INSERT #tabXML([TXT]) VALUES ('    </Документ>') 
INSERT #tabXML([TXT]) VALUES ('</Файл>')                         

----------------------------------------
INSERT #Files ([TXT], [NAMEFILE],  [NAMEFILE_ARH],  [OrderFile],[LINK_SAVED_FORM])
SELECT         [TXT], @vcFILE_NAME,@vcFILE_NAME_XSD,[ORDERS],   @iLINK_SAVED_FORM
FROM #tabXML
DROP TABLE #tabXML  

GO
GRANT ALL ON dbo.[RA_EXPORT_FORM_FNS_737] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
IF EXISTS (SELECT * 
           FROM dbo.[SYSOBJECTS]
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_EXPORT_FORM_FNS_738]') AND 
                 OBJECTPROPERTY(ID, N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_EXPORT_FORM_FNS_738]
END
GO
----------------------
CREATE PROCEDURE [dbo].[RA_EXPORT_FORM_FNS_738]
 @iLINK_SAVED_FORM INT,                    -- Линк выгружаемой формы  
 @vcFILE_NAME     VARCHAR(100)='' OUTPUT, -- Имя текстового файла  
 @iMODE           INT=1,                   -- Формат: 2-внутренний, 1-минфиновский  
 @vcResultTableName       VARCHAR(8000) = NULL
AS  
  
SET NOCOUNT ON  
SET DATEFORMAT dmy  

DECLARE @iLINK_FORM		 INT,
        @iLINK_TASK      INT,
        @iLINK_ORG       INT,
      	@iLINK_TABLE	 INT,
        @dBEGIN_DATE     DATETIME,
        @dFORM_DATE      DATETIME,
        @sYear           SMALLINT, 
        @vcOrgname       VARCHAR(1000),
        @vcKOD_ORGAN     VARCHAR(8000),
        @vcVersion       VARCHAR(8000),
        @vcProgramName   VARCHAR(100),
        @vcCRC           VARCHAR(8000),  
        @vcInn           VARCHAR(10),
        @vcKpp           VARCHAR(9),
        @vcOkpo          VARCHAR(10),
        @vcOkato         VARCHAR(11),
        @vcPPP           VARCHAR(50), 
        @iUchr_Link      INT,
        @vcOrgname_Uchr  VARCHAR(1000),
        @vcInn_Uchr      VARCHAR(10),
        @vcKpp_Uchr      VARCHAR(9),
        @vcOkpo_Uchr     VARCHAR(10),
        @vcSurname       VARCHAR(60),
        @vcFirstName     VARCHAR(60),
        @vcMiddleName    VARCHAR(60),
        @vcSurname_GB    VARCHAR(60),
        @vcFirstName_GB  VARCHAR(60),
        @vcMiddleName_GB VARCHAR(60),
        @vcDateRegl      VARCHAR(10),
        @vcExec          VARCHAR(8000),  
        @vcnExec         VARCHAR(8000),
        @vcKodCBU        VARCHAR(9), 
        @vcFO            VARCHAR(1), 
        @bCancel         BIT,
        @iReturn         INT,
        @vcNAME          VARCHAR(8000),
        @vcFORM_CODE     VARCHAR(8000),  
        @vcFILE_NAME_XSD VARCHAR(100),    
        @vcTableName     VARCHAR(8000), 
        @CODE            VARCHAR(100)
DECLARE @val             VARCHAR(8000), 
        @val2            VARCHAR(8000), 
        @str             VARCHAR(8000),
        @str1            VARCHAR(8000)
          
CREATE TABLE #tabXML ([TXT]	  VARCHAR(8000),
					  [ORDERS] INT IDENTITY(1,1))

IF OBJECT_ID('tempdb..#tabExportOutput') IS NOT NULL  
BEGIN  
   SELECT @vcVersion = [VERSION]  
   FROM #tabExportOutput   
END  
  
SET @vcNAME = 'Отчет об обязательствах, принятых учреждением'
SET @vcFORM_CODE = '0503738'  
SET @vcVersion='5.01'  
SELECT @vcFO = RTRIM(dbo.[RN_GET_ATR_VALUE](@iLINK_SAVED_FORM,'REPORTS_ATR_VID'))
SELECT @vcProgramName = CASE WHEN CODE_TASK = 'SMETA'   THEN 'СМЕТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'KADRY'   THEN 'КАДРЫ-КС'
                             WHEN CODE_TASK = 'SALARY'  THEN 'ЗАРПЛАТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'DELO'    THEN 'ДЕЛО-КС'
                             WHEN CODE_TASK = 'ADMIN'   THEN 'АДМИНИСТРАТОР'
                             ELSE ''
                        END       
FROM [dbo].USER_INFO                                  

--Таблица Расходы бюджета
SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_ORG  = [Link_Organization]         
FROM dbo.[report_saved_forms] A  
WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM   

SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 1

CREATE TABLE #tabAttr ([CHECKED]         INT, 
                       [UPD]             INT, 
                       [DEL]             INT, 
                       [LINK_SAVED_FORM] INT, 
                       [LINK_ROW]        INT, 
                       [ORDERS]          INT, 
                       [CALC_ORDERS]     INT, 
                       [PRINT_NULL]      INT, 
                       [CODE]            VARCHAR(50),
                       COL1 VARCHAR(8000), COL2 VARCHAR(8000), COL3 VARCHAR(8000), COL4 NUMERIC(20,2), 
                       COL5 NUMERIC(20,2), COL6 NUMERIC(20,2), COL7 NUMERIC(20,2), COL8 NUMERIC(20,2), 
                       COL9 NUMERIC(20,2), COL10 NUMERIC(20,2), COL11 NUMERIC(20,2))

  SET @vcExec = 'INSERT #tabAttr
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  --PRINT @vcExec
  EXEC(@vcExec)

-- Выгрузка подписей.
-- Выгрузка подписей.
 SELECT   @vcOrgname = substring(dbo.[RA_XML_MASK](d.[FULL_NAME]),1,1000),
          @vcInn     = rtrim(ltrim(d.[INN])),
          @vcKpp     = rtrim(ltrim(d.[KPP])),
          @vcOkpo    = d.[OKPO],
          @vcOkato   = d.[OKATO],
          @iUchr_Link    = d.[UCHR_LINK]
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iLINK_ORG
 SELECT   @vcInn_Uchr     = isnull(d.[INN],''),
          @vcKpp_Uchr     = isnull(d.[KPP],''),
          @vcOkpo_Uchr    = isnull(d.[OKPO],''),
          @vcOrgName_Uchr = isnull(dbo.[RA_XML_MASK](d.[FULL_NAME]),'')
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iUchr_Link
 SELECT @vcKOD_ORGAN = [SONO],
        @vcPPP       = [VED]
 FROM PrintDoc_GetDepData2(@iLINK_ORG)   
 SELECT @vcSurname=ch.[FM],
        @vcFirstName=ch.[IM],
        @vcMiddleName=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Руководитель') ch
 WHERE ch.link_dep = @iLINK_ORG
 SELECT @vcSurname_GB=ch.[FM],
        @vcFirstName_GB=ch.[IM],
        @vcMiddleName_GB=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Главный бухгалтер') ch
 WHERE ch.link_dep = @iLINK_ORG
 IF (@vcSurname='' OR @vcSurname IS NULL OR LEN(@vcSurname)=0) SELECT @vcSurname='A'
 IF (@vcFirstName='' OR @vcFirstName IS NULL OR LEN(@vcFirstName)=0) SELECT @vcFirstName='A'
 IF @vcInn IS NULL SELECT @vcInn='9999999999'
 IF @vcKpp IS NULL SELECT @vcKpp='999999999'
 IF @vcKOD_ORGAN IS NULL SELECT @vcKOD_ORGAN=''
--Дата начала   
SELECT @dBEGIN_DATE = A.[Begin_Date],
       @sYear = CAST(YEAR(@dBEGIN_DATE) AS VARCHAR(4)),  
       @vcDateRegl = convert(varchar(12), @dBEGIN_DATE+1, 104) 
  FROM dbo.[report_saved_forms] A
  WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM
--Дата документа
 SELECT @dFORM_DATE=GETDATE()
  
SET @vcCRC = RTRIM(CONVERT(VARCHAR(100), NEWID()))  
  
--Имя файла
SELECT @vcExec =  'NO_BOUCHR4.' + @vcFO + '_' +  @vcKOD_ORGAN+ '_' +  
                  @vcKOD_ORGAN+ '_' + rtrim(ltrim(@vcINN)) + rtrim(ltrim(@vcKPP)) + '_' +  
                  CAST(YEAR(@dFORM_DATE) AS VARCHAR(4)) + 
                  RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '_' + @vcCRC,
       @vcFILE_NAME =  @vcExec + '.xml',
       @vcFILE_NAME_XSD = @vcExec + '.xsd'  
--Вставка XML
INSERT #tabXML([TXT]) VALUES ('<?xml  version ="1.0"  encoding ="windows-1251"?>')
INSERT #tabXML([TXT]) VALUES ('<Файл ИдФайл="'+@vcExec+'" '+'ВерсПрог="'+@vcProgramName+'" '+'ВерсФорм="'+@vcVersion+'">')
INSERT #tabXML([TXT]) VALUES ('  <Документ КНД="' + @vcFORM_CODE + '" ДатаДок="'+RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '.' +  
                               RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ '.' + CAST(YEAR(@dFORM_DATE) AS VARCHAR(4))+
                               '" Период="34" ОтчетГод="'+CAST(@sYear AS VARCHAR(4))+'" НомКорр="0">')
INSERT #tabXML([TXT]) VALUES ('    <СвНП')
IF @vcOkpo<>'' AND LEN(@vcOkpo) BETWEEN 8 AND 10 
INSERT #tabXML([TXT]) VALUES (' ОКПО="'+LTRIM(RTRIM(@vcOkpo))+'"') 
IF @vcOkato<>'' AND LEN(@vcOkato)=11
INSERT #tabXML([TXT]) VALUES (' ОКАТО="'+@vcOkato+'"')
IF @vcOkpo_Uchr<>'' AND LEN(@vcOkpo_Uchr) BETWEEN 8 AND 10 
INSERT #tabXML([TXT]) VALUES (' ОКПО_Учр="'+LTRIM(RTRIM(@vcOkpo_Uchr))+'"') 
INSERT #tabXML([TXT]) VALUES (' ВидФО="' + @vcFO + '"')
IF @vcPPP<>'' AND LEN(@vcPPP)<4
INSERT #tabXML([TXT]) VALUES (' ГлаваБК="' + @vcPPP + '"')
INSERT #tabXML([TXT]) VALUES ('>')
INSERT #tabXML([TXT]) VALUES ('      <НПЮЛ НаимОрг="'+@vcOrgname+'" ИННЮЛ="'+@vcInn+'" КПП="'+@vcKpp+'"')
IF @vcOrgName_Uchr<>'' 
INSERT #tabXML([TXT]) VALUES (' Учредит="'+@vcOrgName_Uchr+'"')
IF @vcInn_Uchr<>''
INSERT #tabXML([TXT]) VALUES (' ИННЮЛ_Учр="'+@vcInn_Uchr+'"')
IF @vcKpp_Uchr<>''
INSERT #tabXML([TXT]) VALUES (' КПП_Учр="'+@vcKpp_Uchr+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('    </СвНП>')
INSERT #tabXML([TXT]) VALUES ('<Подписант ПрПодп="3">')
INSERT #tabXML([TXT]) VALUES ('<ФИО Фамилия="'+@vcSurname+'" Имя="'+@vcFirstName+'"')
IF @vcMiddleName<>''
INSERT #tabXML([TXT]) VALUES ('           Отчество="'+@vcMiddleName+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('</Подписант>')
INSERT #tabXML([TXT]) VALUES ('	   <ОтчетОбяз ДатаОтч="' + @vcDateRegl + '" ОКЕИ="383" ' + 'ГодПланНазн="' + CAST(@sYear AS VARCHAR(4)) + '">')
--------------------------------------------------
SELECT @val='',@val2='',@str='',@str1=''
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=960
if @val<>'' begin set @str = @str + ' УтвПланНазн="'   + @val + '"' END
SELECT @val=[COL5] FROM #tabAttr WHERE  [CODE]=960
if @val<>'' begin set @str = @str + ' ОбязПринВс="'    + @val + '"' END
SELECT @val=[COL6] FROM #tabAttr WHERE  [CODE]=960
if @val<>'' begin set @str = @str + ' ОбязПринСв="'    + @val + '"' END
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=960
if @val<>'' begin set @str = @str + ' ДенОбязПринВс="' + @val + '"' END
SELECT @val=[COL8] FROM #tabAttr WHERE  [CODE]=960
if @val<>'' begin set @str = @str + ' ДенОбязПринСв="' + @val + '"' END
SELECT @val=[COL9] FROM #tabAttr WHERE  [CODE]=960
if @val<>'' begin set @str = @str + ' ДенОбязИсп="'    + @val + '"' END
SELECT @val=[COL10] FROM #tabAttr WHERE  [CODE]=960
if @val<>'' begin set @str = @str + ' ОбязНеИсп="'     + @val + '"' END
SELECT @val=[COL11] FROM #tabAttr WHERE  [CODE]=960
if @val<>'' begin set @str = @str + ' ДенОбязНеИсп="'  + @val + '"' END
INSERT #tabXML([TXT]) SELECT '<ОбязРасхВс КодСтрок="200" '+@str+'/>' 
--------------------------------------------------
DECLARE T_CURSOR CURSOR FOR      
 SELECT [CODE] FROM #tabAttr ORDER BY [CODE]
 OPEN T_CURSOR      
 FETCH NEXT FROM T_CURSOR INTO @CODE      
 WHILE @@FETCH_STATUS = 0
 BEGIN  
 SELECT @val='',@val2='',@str='',@str1=''
 SELECT @str1=dbo.[RA_XML_MASK]([COL1]) FROM  #tabAttr WHERE [CODE]=@CODE
 SELECT @str= CASE WHEN @CODE<>960 
              THEN '<ОбязВидРасх НаимРасх="' + @str1 + '" КодСтрок="200" КодРасх="' + @CODE + '" '
              ELSE '<Итого '
              END
 SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=@CODE
 set @str = @str + ' УтвПланНазн="'   + @val + '"'
 SELECT @val=[COL5] FROM #tabAttr WHERE  [CODE]=@CODE
 set @str = @str + ' ОбязПринВс="'    + @val + '"'
 SELECT @val=[COL6] FROM #tabAttr WHERE  [CODE]=@CODE
 set @str = @str + ' ОбязПринСв="'    + @val + '"'
 SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=@CODE
 set @str = @str + ' ДенОбязПринВс="' + @val + '"'
 SELECT @val=[COL8] FROM #tabAttr WHERE  [CODE]=@CODE
 set @str = @str + ' ДенОбязПринСв="' + @val + '"'
 SELECT @val=[COL9] FROM #tabAttr WHERE  [CODE]=@CODE
 set @str = @str + ' ДенОбязИсп="'    + @val + '"'
 SELECT @val=[COL10] FROM #tabAttr WHERE  [CODE]=@CODE
 set @str = @str + ' ОбязНеИсп="'     + @val + '"'
 SELECT @val=[COL11] FROM #tabAttr WHERE  [CODE]=@CODE
 set @str = @str + ' ДенОбязНеИсп="'  + @val + '"'
 INSERT #tabXML([TXT]) SELECT @STR + '/>'
 FETCH NEXT FROM T_CURSOR INTO @CODE      
 END      
 CLOSE T_CURSOR      
DEALLOCATE T_CURSOR   
--------------------------------------------------
INSERT #tabXML([TXT]) VALUES ('</ОтчетОбяз>')
INSERT #tabXML([TXT]) VALUES ('</Документ>')
INSERT #tabXML([TXT]) VALUES ('</Файл>')
----------------------------------------
insert #Files ([TXT], [NAMEFILE],  [NAMEFILE_ARH], [OrderFile],[LINK_SAVED_FORM])
SELECT [TXT],@vcFILE_NAME,@vcFILE_NAME_XSD,[ORDERS],@iLINK_SAVED_FORM
FROM #tabXML
DROP TABLE #tabXML  


GO
GRANT ALL ON dbo.[RA_EXPORT_FORM_FNS_738] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
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', 74578 , 0, 41964
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
		into #TMP
		from 
			dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up
			
			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
		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]
		order by
			S.pachka

			SELECT
				CODE = CONVERT(VARCHAR(10), [NGROUP]),
				COL1 = CONVERT(VARCHAR(10),[NGROUP]),
				COL2 = CONVERT(VARCHAR(10),''),
				COL3 = isnull((isnull(b_bef_m1,0) + isnull(b_bef_m2,0) + isnull(b_bef_m3,0)),0.00),
				COL4 = isnull(insur,0.00),
				COL5 = 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
			ORDER BY
				NGROUP

		drop table #TMP		
	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
		into #TMP1
		from 
			dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up
			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]
	
	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 = ISNULL((case when per_edt >= 2014 then sd_str else 0 end),0),
			COL6 = ISNULL((case when per_edt < 2014 then sd_str else 0 end),0),
			COL7 = ISNULL((case when per_edt < 2014 then sd_nak else 0 end),0),
			COL8 = 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((isnull(b_bef_m1,0) + isnull(b_bef_m2,0) + isnull(b_bef_m3,0)),0.00),
			COL15 = ISNULL([INSUR],0),
			COL16 = [LINK_DOC]
		FROM
			#TMP1
		ORDER BY
			NGROUP
		
		drop table #TMP1

	END 
	
		drop table #docs_kor_otm
		drop table #docs

END









GO


GRANT EXECUTE ON dbo.[RSA_RSV_1_PERS_UCH] 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.[RA_EXPORT_FORM_FNS_760]') AND 
                 OBJECTPROPERTY(ID, N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_EXPORT_FORM_FNS_760]
END
GO
----------------------
CREATE PROCEDURE [dbo].[RA_EXPORT_FORM_FNS_760]
@iLINK_SAVED_FORM INT,                    -- Линк выгружаемой формы  
 @vcFILE_NAME     VARCHAR(100)='' OUTPUT, -- Имя текстового файла  
 @iMODE           INT=1                   -- Формат: 2-внутренний, 1-минфиновский  
AS  
  
SET NOCOUNT ON  
SET DATEFORMAT dmy  

DECLARE @iLINK_FORM		 INT,
        @iLINK_TABLE	 INT,
        @iLINK_ORG      INT,
      	@dBEGIN_DATE     DATETIME,
        @dFORM_DATE      DATETIME,
        @sYear           SMALLINT, 
        @vcOrgname       VARCHAR(1000),
        @vcKOD_ORGAN     VARCHAR(8000),
        @vcVersion       VARCHAR(8000),
        @vcProgramName   VARCHAR(100),
        @vcCRC           VARCHAR(8000),  
        @vcInn           VARCHAR(10),
        @vcKpp           VARCHAR(9),
        @vcOkpo          VARCHAR(10),
        @vcOkato         VARCHAR(11),
        @vcPPP           VARCHAR(50),
        @iUchr_Link      INT,
        @vcOrgname_Uchr  VARCHAR(1000),
        @vcInn_Uchr      VARCHAR(10),
        @vcKpp_Uchr      VARCHAR(9),
        @vcOkpo_Uchr     VARCHAR(10),
        @vcSurname       VARCHAR(60),
        @vcFirstName     VARCHAR(60),
        @vcMiddleName    VARCHAR(60),
        @vcSurname_GB    VARCHAR(60),
        @vcFirstName_GB  VARCHAR(60),
        @vcMiddleName_GB VARCHAR(60),
        @vcSurname_FES   VARCHAR(60),
        @vcFirstName_FES VARCHAR(60),
        @vcMiddleName_FES VARCHAR(60),
        @vcDateRegl      VARCHAR(10),
        @vcExec          VARCHAR(8000),  
        @vcAttr          VARCHAR(100), 
        @bCancel         BIT,
        @iReturn         INT,
        @vcNAME          VARCHAR(8000),
        @vcFORM_CODE     VARCHAR(8000),  
        @vcFILE_NAME_XSD VARCHAR(100),    
        @vcTableName     VARCHAR(8000), 
        @LINK_SAVED_FORM VARCHAR(100),
        @CODE            VARCHAR(100),
        @LINK_TABLE      VARCHAR(100),
        @COL1            VARCHAR(100)
DECLARE @val             VARCHAR(8000), 
        @val2            VARCHAR(8000), 
        @str             VARCHAR(8000),
        @strbin          VARbinary(max),        
        @strmax          VARCHAR(MAX),
        @valmax          VARCHAR(MAX)

          
CREATE TABLE #tabXML ([TXT]	  VARCHAR(8000),
							 [ORDERS] INT IDENTITY(1,1))

IF OBJECT_ID('tempdb..#tabExportOutput') IS NOT NULL  
BEGIN  
   SELECT @vcVersion = [VERSION]  
   FROM #tabExportOutput   
END  
  
SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_ORG  = [Link_Organization]         
FROM dbo.[report_saved_forms] A  
WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM   

SET @vcNAME = 'Пояснительная записка'
SET @vcFORM_CODE = '0503760'  
SET @vcVersion='5.01'  
SELECT @vcProgramName = CASE WHEN CODE_TASK = 'SMETA'   THEN 'СМЕТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'KADRY'   THEN 'КАДРЫ-КС'
                             WHEN CODE_TASK = 'SALARY'  THEN 'ЗАРПЛАТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'DELO'    THEN 'ДЕЛО-КС'
                             WHEN CODE_TASK = 'ADMIN'   THEN 'АДМИНИСТРАТОР'
                             ELSE ''
                        END       
FROM [dbo].USER_INFO                                  

--Сопроводительные отчеты
CREATE TABLE #tab (LINK_SAVED_FORM INT,
                   CODE            VARCHAR(100),
                   LINK_TABLE      INT)
INSERT #tab                   

SELECT MAX(C.LINK_SAVED_FORM),E.CODE,T.LINK_TABLE
FROM dbo.[report_saved_forms] B 
INNER JOIN dbo.[report_saved_forms] C ON B.PERIOD_TYPE = C.PERIOD_TYPE AND B.PERIOD_NUMBER = C.PERIOD_NUMBER
                                     AND B.LINK_ORGANIZATION = C.LINK_ORGANIZATION
INNER JOIN dbo.[report_forms] E ON C.[LINK_FORM] = E.[LINK_FORM]             
INNER JOIN dbo.[report_tables] T ON T.[LINK_FORM] = E.[LINK_FORM]
WHERE B.LINK_SAVED_FORM = @iLINK_SAVED_FORM
  AND E.CODE LIKE ('0503760G%')
GROUP BY E.Code,T.Link_Table

CREATE TABLE #tabAttr ([CHECKED] INT, 
                       [UPD]     INT, 
                       [DEL]     INT, 
                       [LINK_SAVED_FORM] INT, 
                       [LINK_ROW] INT, 
                       [ORDERS]   INT, 
                       [CALC_ORDERS] INT, 
                       [PRINT_NULL] INT, 
                       [CODE] VARCHAR(50), COL1 VARCHAR(8000), COL2 VARCHAR(8000))
  CREATE TABLE #tabAttr1 ([CHECKED] INT, 
                          [UPD]     INT, 
                          [DEL]     INT, 
                          [LINK_SAVED_FORM] INT, 
                          [LINK_ROW] INT, 
                          [ORDERS]   INT, 
                          [CALC_ORDERS] INT, 
                          [PRINT_NULL] INT, 
                          [CODE] VARCHAR(50), COL1 VARCHAR(8000), COL2 VARCHAR(8000),
                          COL3 VARCHAR(8000), COL4 VARCHAR(8000))
  CREATE TABLE #tabAttr4 ([CHECKED] INT, 
                          [UPD]     INT, 
                          [DEL]     INT, 
                          [LINK_SAVED_FORM] INT, 
                          [LINK_ROW] INT, 
                          [ORDERS]   INT, 
                          [CALC_ORDERS] INT, 
                          [PRINT_NULL] INT, 
                          [CODE] VARCHAR(50), COL1 VARCHAR(8000), COL2 VARCHAR(8000),
                          COL3 VARCHAR(8000), COL4 VARCHAR(8000))
  CREATE TABLE #tabAttr5 ([CHECKED] INT, 
                          [UPD]     INT, 
                          [DEL]     INT, 
                          [LINK_SAVED_FORM] INT, 
                          [LINK_ROW] INT, 
                          [ORDERS]   INT, 
                          [CALC_ORDERS] INT, 
                          [PRINT_NULL] INT, 
                          [CODE] VARCHAR(50), COL1 VARCHAR(8000), COL2 VARCHAR(8000),
                          COL3 VARCHAR(8000), COL4 VARCHAR(8000), COL5 VARCHAR(8000), COL6 VARCHAR(8000), COL7 VARCHAR(8000))
  CREATE TABLE #tabAttr6 ([CHECKED] INT, 
                          [UPD]     INT, 
                          [DEL]     INT, 
                          [LINK_SAVED_FORM] INT, 
                          [LINK_ROW] INT, 
                          [ORDERS]   INT, 
                          [CALC_ORDERS] INT, 
                          [PRINT_NULL] INT, 
                          [CODE] VARCHAR(50), COL1 VARCHAR(8000), COL2 VARCHAR(8000),
                          COL3 VARCHAR(8000), COL4 VARCHAR(8000), COL5 VARCHAR(8000), COL6 VARCHAR(8000), COL7 VARCHAR(8000), COL8 VARCHAR(8000))
  CREATE TABLE #tabAttr7 ([CHECKED] INT, 
                          [UPD]     INT, 
                          [DEL]     INT, 
                          [LINK_SAVED_FORM] INT, 
                          [LINK_ROW] INT, 
                          [ORDERS]   INT, 
                          [CALC_ORDERS] INT, 
                          [PRINT_NULL] INT, 
                          [CODE] VARCHAR(50), COL1 VARCHAR(8000), COL2 VARCHAR(8000),
                          COL3 VARCHAR(8000), COL4 VARCHAR(8000), COL5 VARCHAR(8000), COL6 VARCHAR(8000))
DECLARE T_CURSOR CURSOR FOR      
SELECT LINK_SAVED_FORM, CODE, LINK_TABLE FROM #tab 
OPEN T_CURSOR      
FETCH NEXT FROM T_CURSOR INTO @LINK_SAVED_FORM,@CODE,@LINK_TABLE
WHILE @@FETCH_STATUS = 0         
BEGIN  
IF @CODE='0503760G'
BEGIN        
  SET @vcExec = 'INSERT #tabAttr
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@LINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@LINK_SAVED_FORM)) 
  EXEC(@vcExec)
END  
ELSE IF @CODE='0503760G_т1'
BEGIN        
  SET @vcExec = 'INSERT #tabAttr1
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@LINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@LINK_SAVED_FORM)) 
  EXEC(@vcExec)
END  
ELSE IF @CODE='0503760G_т4'
BEGIN        
  SET @vcExec = 'INSERT #tabAttr4
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@LINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@LINK_SAVED_FORM)) 
  EXEC(@vcExec)
END  
ELSE IF @CODE='0503760G_т5'
BEGIN        
  SET @vcExec = 'INSERT #tabAttr5
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@LINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@LINK_SAVED_FORM)) 
  EXEC(@vcExec)
END  
ELSE IF @CODE='0503760G_т6'
BEGIN        
  SET @vcExec = 'INSERT #tabAttr6
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@LINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@LINK_SAVED_FORM)) 
  EXEC(@vcExec)
END  
ELSE IF @CODE='0503760G_т7'
BEGIN        
  SET @vcExec = 'INSERT #tabAttr7
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@LINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@LINK_SAVED_FORM)) 
  EXEC(@vcExec)
END  
FETCH NEXT FROM T_CURSOR INTO @LINK_SAVED_FORM,@CODE,@LINK_TABLE
END      
CLOSE T_CURSOR      
DEALLOCATE T_CURSOR   
-- Выгрузка подписей.
 SELECT   @vcOrgname = substring(dbo.[RA_XML_MASK](d.[FULL_NAME]),1,1000),
          @vcInn     = rtrim(ltrim(d.[INN])),
          @vcKpp     = rtrim(ltrim(d.[KPP])),
          @vcOkpo    = d.[OKPO],
          @vcOkato   = d.[OKATO],
          @iUchr_Link    = d.[UCHR_LINK]
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iLINK_ORG
 SELECT   @vcInn_Uchr     = isnull(d.[INN],''),
          @vcKpp_Uchr     = isnull(d.[KPP],''),
          @vcOkpo_Uchr    = isnull(d.[OKPO],''),
          @vcOrgName_Uchr = isnull(dbo.[RA_XML_MASK](d.[FULL_NAME]),'')
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iUchr_Link
 SELECT @vcKOD_ORGAN = [SONO],
        @vcPPP       = [VED]
 FROM PrintDoc_GetDepData2(@iLINK_ORG)   
 SELECT @vcSurname=ch.[FM],
        @vcFirstName=ch.[IM],
        @vcMiddleName=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Руководитель') ch
 WHERE ch.link_dep = @iLINK_ORG
 SELECT @vcSurname_GB=ch.[FM],
        @vcFirstName_GB=ch.[IM],
        @vcMiddleName_GB=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Главный бухгалтер') ch
 WHERE ch.link_dep = @iLINK_ORG
 IF (@vcSurname='' OR @vcSurname IS NULL OR LEN(@vcSurname)=0) SELECT @vcSurname='A'
 IF (@vcFirstName='' OR @vcFirstName IS NULL OR LEN(@vcFirstName)=0) SELECT @vcFirstName='A'
 IF (@vcinn='' OR @vcInn IS NULL) SELECT @vcInn='9999999999'
 IF (@vcKpp='' OR @vcKpp IS NULL) SELECT @vcKpp='999999999'
 IF @vcKOD_ORGAN IS NULL SELECT @vcKOD_ORGAN=''
--Дата начала   
SELECT @dBEGIN_DATE = A.[Begin_Date],
       @sYear = CAST(YEAR(@dBEGIN_DATE) AS VARCHAR(4)),  
       @vcDateRegl = convert(varchar(12), @dBEGIN_DATE+1, 104) 
  FROM dbo.[report_saved_forms] A
  WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM
--Дата документа
 SELECT @dFORM_DATE=GETDATE()
  
SET @vcCRC = RTRIM(CONVERT(VARCHAR(100), NEWID()))  
--Имя файла
SELECT @vcExec =  'NO_BOUCHR5' + '_' +  @vcKOD_ORGAN+ '_' +  
                  @vcKOD_ORGAN+ '_' + @vcINN + @vcKPP + '_' +  
                  CAST(YEAR(@dFORM_DATE) AS VARCHAR(4)) +   
                  RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '_' + @vcCRC,
       @vcFILE_NAME =  @vcExec + '.xml',
       @vcFILE_NAME_XSD = @vcExec + '.xsd'  
--Вставка XML
INSERT #tabXML([TXT]) VALUES ('<?xml version ="1.0" encoding ="windows-1251"?>')
INSERT #tabXML([TXT]) VALUES ('<Файл ИдФайл="'+@vcExec+'" '+'ВерсПрог="'+@vcProgramName+'" '+'ВерсФорм="'+@vcVersion+'">')
INSERT #tabXML([TXT]) VALUES ('  <Документ КНД="' + @vcFORM_CODE + '" ДатаДок="'+RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '.' +  
                               RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ '.' + CAST(YEAR(@dFORM_DATE) AS VARCHAR(4))+
                               '" Период="34" ОтчетГод="'+CAST(@sYear AS VARCHAR(4))+'" НомКорр="0">')
INSERT #tabXML([TXT]) VALUES ('    <СвНП')
IF @vcOkpo<>'' AND LEN(@vcOkpo) BETWEEN 8 AND 10 
INSERT #tabXML([TXT]) VALUES (' ОКПО="'+LTRIM(RTRIM(@vcOkpo))+'"') 
IF @vcOkato<>'' AND LEN(@vcOkato)=11
INSERT #tabXML([TXT]) VALUES (' ОКАТО="'+@vcOkato+'"')
IF @vcOkpo_Uchr<>'' AND LEN(@vcOkpo_Uchr) BETWEEN 8 AND 10 
INSERT #tabXML([TXT]) VALUES (' ОКПО_Учр="'+LTRIM(RTRIM(@vcOkpo_Uchr))+'"') 
IF @vcPPP<>'' AND LEN(@vcPPP)<4
INSERT #tabXML([TXT]) VALUES (' ГлаваБК="' + @vcPPP + '"')
INSERT #tabXML([TXT]) VALUES ('>')
INSERT #tabXML([TXT]) VALUES ('      <НПЮЛ НаимОрг="'+@vcOrgname+'" ИННЮЛ="'+LTRIM(RTRIM(@vcInn))+'" КПП="'+@vcKpp+'"')
IF @vcOrgName_Uchr<>'' 
INSERT #tabXML([TXT]) VALUES (' Учредит="'+@vcOrgName_Uchr+'"')
IF @vcInn_Uchr<>''
INSERT #tabXML([TXT]) VALUES (' ИННЮЛ_Учр="'+@vcInn_Uchr+'"')
IF @vcKpp_Uchr<>''
INSERT #tabXML([TXT]) VALUES (' КПП_Учр="'+@vcKpp_Uchr+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('</СвНП>')
INSERT #tabXML([TXT]) VALUES ('<Подписант ПрПодп="3">')
INSERT #tabXML([TXT]) VALUES ('<ФИО Фамилия="'+@vcSurname+'" Имя="'+@vcFirstName+'"')
IF @vcMiddleName<>''
INSERT #tabXML([TXT]) VALUES ('Отчество="'+@vcMiddleName+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('</Подписант>')
IF @vcSurname_GB<>'' AND @vcFirstName_GB<>''
begin
INSERT #tabXML([TXT]) VALUES ('<Подписант ПрПодп="4">')
INSERT #tabXML([TXT]) VALUES ('<ФИО Фамилия="'+@vcSurname_GB+'" Имя="'+@vcFirstName_GB+'"')
IF @vcMiddleName_GB<>''
INSERT #tabXML([TXT]) VALUES ('Отчество="'+@vcMiddleName_GB+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('</Подписант>')
end
INSERT #tabXML([TXT]) VALUES ('	   <ПЗБаланс ДатаОтч="' + @vcDateRegl + '" ОКЕИ="383">')
--------------------------------------------------
IF EXISTS (SELECT * FROM #tabAttr)
BEGIN
SELECT @strmax=''
INSERT #tabXML([TXT]) VALUES ('<ТекстПЗ>')
DECLARE B_CURSOR CURSOR FOR      
SELECT CODE FROM #tabAttr
OPEN B_CURSOR      
FETCH NEXT FROM B_CURSOR INTO @CODE
WHILE @@FETCH_STATUS = 0         
BEGIN
 SELECT @str=COL2 FROM #tabAttr WHERE [CODE]=@CODE
 SELECT @strmax=@strmax+@str
FETCH NEXT FROM B_CURSOR INTO @CODE
END
CLOSE B_CURSOR      
DEALLOCATE B_CURSOR   
SELECT @strbin = CAST(@strmax as VARBINARY(MAX))
SELECT @valmax = CAST(N'' as xml).value('xs:base64Binary(sql:variable("@strbin"))', 'varchar(max)')
INSERT #tabXML([TXT]) VALUES ('<![CDATA['+@valmax+']]>')
INSERT #tabXML([TXT]) VALUES ('</ТекстПЗ>')
END      
--------------------------------------------------
IF EXISTS (SELECT * FROM #tabAttr1)
BEGIN
INSERT #tabXML([TXT]) VALUES ('<ОснНапр>')
DECLARE B_CURSOR CURSOR FOR      
SELECT CODE FROM #tabAttr1
OPEN B_CURSOR      
FETCH NEXT FROM B_CURSOR INTO @CODE
WHILE @@FETCH_STATUS = 0         
BEGIN
 INSERT #tabXML([TXT]) SELECT '<ОснНапрДеят НаимЦелДеят="'+COL2+'">' FROM #tabAttr1 WHERE CODE=@CODE
 SELECT @str=COL3 FROM #tabAttr1 WHERE CODE=@CODE
 IF @str<>''
 begin
 SELECT @strbin = CAST(COL3 as VARBINARY(MAX)) FROM #tabAttr1 WHERE CODE=@CODE
 SELECT @val    = CAST(N'' as xml).value('xs:base64Binary(sql:variable("@strbin"))', 'varchar(max)')
 INSERT #tabXML([TXT]) VALUES ('<КратХаракт><![CDATA['+@val+']]></КратХаракт>')
 end
 SELECT @str=COL4 FROM #tabAttr1 WHERE CODE=@CODE
 IF @str<>''
 begin
 SELECT @strbin = CAST(COL4 as VARBINARY(MAX)) FROM #tabAttr1 WHERE CODE=@CODE
 SELECT @val    = CAST(N'' as xml).value('xs:base64Binary(sql:variable("@strbin"))', 'varchar(max)')
 INSERT #tabXML([TXT]) VALUES ('<ПравОбоснов><![CDATA['+@val+']]></ПравОбоснов>')
 END
 INSERT #tabXML([TXT]) SELECT '</ОснНапрДеят>'
FETCH NEXT FROM B_CURSOR INTO @CODE
END
CLOSE B_CURSOR      
DEALLOCATE B_CURSOR   
INSERT #tabXML([TXT]) VALUES ('</ОснНапр>')
END      
--------------------------------------------------
IF EXISTS (SELECT * FROM #tabAttr4)
BEGIN
INSERT #tabXML([TXT]) VALUES ('<ОсобБУ>')
DECLARE B_CURSOR CURSOR FOR      
SELECT CODE FROM #tabAttr4
OPEN B_CURSOR      
FETCH NEXT FROM B_CURSOR INTO @CODE
WHILE @@FETCH_STATUS = 0         
BEGIN
 INSERT #tabXML([TXT]) SELECT '<ОсобБУОбУч НаимОбУч="'+COL1+'" КодСчетБУч="'+COL2+'">' FROM #tabAttr4 WHERE CODE=@CODE
 SELECT @str=COL3 FROM #tabAttr4 WHERE CODE=@CODE
 IF @str<>''
 begin
 SELECT @strbin = CAST(COL3 as VARBINARY(MAX)) FROM #tabAttr4 WHERE CODE=@CODE
 SELECT @val    = CAST(N'' as xml).value('xs:base64Binary(sql:variable("@strbin"))', 'varchar(max)')
 INSERT #tabXML([TXT]) VALUES ('<Характер><![CDATA['+@val+']]></Характер>')
 end
 SELECT @str=COL4 FROM #tabAttr4 WHERE CODE=@CODE
 IF @str<>''
 begin
 SELECT @strbin = CAST(COL4 as VARBINARY(MAX)) FROM #tabAttr4 WHERE CODE=@CODE
 SELECT @val    = CAST(N'' as xml).value('xs:base64Binary(sql:variable("@strbin"))', 'varchar(max)')
 INSERT #tabXML([TXT]) VALUES ('<ПравОбоснов><![CDATA['+@val+']]></ПравОбоснов>')
 END
 INSERT #tabXML([TXT]) SELECT '</ОсобБУОбУч>'
FETCH NEXT FROM B_CURSOR INTO @CODE
END
CLOSE B_CURSOR      
DEALLOCATE B_CURSOR   
INSERT #tabXML([TXT]) VALUES ('</ОсобБУ>')
END      
--------------------------------------------------
IF EXISTS (SELECT * FROM #tabAttr5)
BEGIN
INSERT #tabXML([TXT]) VALUES ('<РезВнутр>')
DECLARE B_CURSOR CURSOR FOR      
SELECT CODE FROM #tabAttr5
OPEN B_CURSOR      
FETCH NEXT FROM B_CURSOR INTO @CODE
WHILE @@FETCH_STATUS = 0         
BEGIN
 INSERT #tabXML([TXT]) SELECT '<РезВнутрМер ТипКонтрМер="'+COL2+'" НаимМер="'+COL4+'">' FROM #tabAttr5 WHERE CODE=@CODE
 SELECT @str=COL5 FROM #tabAttr5 WHERE CODE=@CODE
 IF @str<>''
 begin
 SELECT @strbin = CAST(COL5 as VARBINARY(MAX)) FROM #tabAttr5 WHERE CODE=@CODE
 SELECT @val    = CAST(N'' as xml).value('xs:base64Binary(sql:variable("@strbin"))', 'varchar(max)')
 INSERT #tabXML([TXT]) VALUES ('<ВыявНаруш><![CDATA['+@val+']]></ВыявНаруш>')
 end
 SELECT @str=COL6 FROM #tabAttr5 WHERE CODE=@CODE
 IF @str<>''
 begin
 SELECT @strbin = CAST(COL6 as VARBINARY(MAX)) FROM #tabAttr5 WHERE CODE=@CODE
 SELECT @val    = CAST(N'' as xml).value('xs:base64Binary(sql:variable("@strbin"))', 'varchar(max)')
 INSERT #tabXML([TXT]) VALUES ('<МерУстран><![CDATA['+@val+']]></МерУстран>')
 END
 INSERT #tabXML([TXT]) SELECT '</РезВнутрМер>'
FETCH NEXT FROM B_CURSOR INTO @CODE
END
CLOSE B_CURSOR      
DEALLOCATE B_CURSOR   
INSERT #tabXML([TXT]) VALUES ('</РезВнутр>')
END      
--------------------------------------------------
IF EXISTS (SELECT * FROM #tabAttr6)
BEGIN
INSERT #tabXML([TXT]) VALUES ('<Инвентар>')
DECLARE B_CURSOR CURSOR FOR      
SELECT CODE FROM #tabAttr6
OPEN B_CURSOR      
FETCH NEXT FROM B_CURSOR INTO @CODE
WHILE @@FETCH_STATUS = 0         
BEGIN
 INSERT #tabXML([TXT]) VALUES ('<ИнвентарДата')  
 SELECT @str=COL2 FROM #tabAttr6 WHERE CODE=@CODE
 IF @str<>''
 INSERT #tabXML([TXT]) SELECT ' ПричИнвентар="'+COL2+'"' FROM #tabAttr6 WHERE CODE=@CODE
 INSERT #tabXML([TXT]) SELECT ' ДатаИнвентар="'+COL3+'"' FROM #tabAttr6 WHERE CODE=@CODE
 SELECT @str=COL4 FROM #tabAttr6 WHERE CODE=@CODE
 IF @str<>''
 INSERT #tabXML([TXT]) SELECT ' НомПриказ="'+COL4+'"' FROM #tabAttr6 WHERE CODE=@CODE
 SELECT @str=COL5 FROM #tabAttr6 WHERE CODE=@CODE
 IF @str<>''
 INSERT #tabXML([TXT]) SELECT ' ДатаПриказ="'+COL5+'"' FROM #tabAttr6 WHERE CODE=@CODE
 INSERT #tabXML([TXT]) VALUES ('>') 
 SELECT @str=COL7 FROM #tabAttr6 WHERE CODE=@CODE
 IF @str<>''
 INSERT #tabXML([TXT]) SELECT '<РезИнвентар КодСчетБУч="'+COL6+'" Сумма="'+COL7+'"/>' FROM #tabAttr6 WHERE CODE=@CODE
 SELECT @str=COL8 FROM #tabAttr6 WHERE CODE=@CODE
 IF @str<>''
 begin
 SELECT @strbin = CAST(COL8 as VARBINARY(MAX)) FROM #tabAttr6 WHERE CODE=@CODE
 SELECT @val    = CAST(N'' as xml).value('xs:base64Binary(sql:variable("@strbin"))', 'varchar(max)')
 INSERT #tabXML([TXT]) VALUES ('<МерУстрРасх><![CDATA['+@val+']]></МерУстрРасх>')
 end
 INSERT #tabXML([TXT]) SELECT '</ИнвентарДата>'
FETCH NEXT FROM B_CURSOR INTO @CODE
END
CLOSE B_CURSOR      
DEALLOCATE B_CURSOR   
INSERT #tabXML([TXT]) VALUES ('</Инвентар>')
END      
--------------------------------------------------
IF EXISTS (SELECT * FROM #tabAttr7)
BEGIN
INSERT #tabXML([TXT]) VALUES ('<РезВнешн>')
DECLARE B_CURSOR CURSOR FOR      
SELECT CODE FROM #tabAttr7
OPEN B_CURSOR      
FETCH NEXT FROM B_CURSOR INTO @CODE
WHILE @@FETCH_STATUS = 0         
BEGIN
 INSERT #tabXML([TXT]) SELECT '<РезВнешнДат ДатаПровер="'+COL2+'"' FROM #tabAttr7 WHERE CODE=@CODE
 SELECT @str=COL3 FROM #tabAttr7 WHERE CODE=@CODE
 IF @str<>''
 INSERT #tabXML([TXT]) SELECT ' НаимОрган="'+COL3+'"' FROM #tabAttr7 WHERE CODE=@CODE
 INSERT #tabXML([TXT]) SELECT '>'
 SELECT @str=COL4 FROM #tabAttr7 WHERE CODE=@CODE
 IF @str<>''
 begin
 SELECT @strbin = CAST(COL4 as VARBINARY(MAX)) FROM #tabAttr7 WHERE CODE=@CODE
 SELECT @val    = CAST(N'' as xml).value('xs:base64Binary(sql:variable("@strbin"))', 'varchar(max)')
 INSERT #tabXML([TXT]) VALUES ('<ТемаПровер><![CDATA['+@val+']]></ТемаПровер>')
 end
 SELECT @str=COL5 FROM #tabAttr7 WHERE CODE=@CODE
 IF @str<>''
 begin
 SELECT @strbin = CAST(COL5 as VARBINARY(MAX)) FROM #tabAttr7 WHERE CODE=@CODE
 SELECT @val    = CAST(N'' as xml).value('xs:base64Binary(sql:variable("@strbin"))', 'varchar(max)')
 INSERT #tabXML([TXT]) VALUES ('<РезПровер><![CDATA['+@val+']]></РезПровер>')
 END
 SELECT @str=COL6 FROM #tabAttr7 WHERE CODE=@CODE
 IF @str<>''
 begin
 SELECT @strbin = CAST(COL6 as VARBINARY(MAX)) FROM #tabAttr7 WHERE CODE=@CODE
 SELECT @val    = CAST(N'' as xml).value('xs:base64Binary(sql:variable("@strbin"))', 'varchar(max)')
 INSERT #tabXML([TXT]) VALUES ('<МерПровер><![CDATA['+@val+']]></МерПровер>')
 END
 INSERT #tabXML([TXT]) SELECT '</РезВнешнДат>'
FETCH NEXT FROM B_CURSOR INTO @CODE
END
CLOSE B_CURSOR      
DEALLOCATE B_CURSOR   
INSERT #tabXML([TXT]) VALUES ('</РезВнешн>')
END      
--------------------------------------------------
INSERT #tabXML([TXT]) VALUES ('</ПЗБаланс>')
INSERT #tabXML([TXT]) VALUES ('</Документ>')
INSERT #tabXML([TXT]) VALUES ('</Файл>')
----------------------------------------
INSERT #Files ([TXT], [NAMEFILE],  [NAMEFILE_ARH],  [OrderFile],[LINK_SAVED_FORM])
SELECT         [TXT], @vcFILE_NAME,@vcFILE_NAME_XSD,[ORDERS],   @iLINK_SAVED_FORM
FROM #tabXML
DROP TABLE #tabXML  


GO
GRANT ALL ON dbo.[RA_EXPORT_FORM_FNS_760] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
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_REPORT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FB_REPORT]
GO











CREATE          PROCEDURE FB_REPORT
	@varKSiFyear	int,
	@varKSdDate	datetime,
	@varKSiDocType	tinyint,
	@varKSiIFType	INT,
	@varKSiNItog	INT,
	@varKScVal1 char(1), 
	@varKSnOtborLink1 int,
	@varKScVal2 char(1) = '', 
	@varKSnOtborLink2 int,
	@varKScVal3 char(1) = '', 
	@varKSnOtborLink3 int
		

AS
DECLARE	@varKSdDateEndY	 datetime,
	@varKSintTypePer tinyint, 
	@varKSFinObjCode char(100),
	@varKSintSummaType tinyint,
	@cCROSS_TABLE 	char(100),
	@intCOUNTER		INT,
	@cSQL_STR		VARCHAR (1000),
	@cCOUNTER		VARCHAR (10),
	@intMAX_REC		INT,
	@intCOUNT_COLROW	INT,
	@varKScIF		char(1),
	@varKSintPerNum 	INT,
	@varKSintResult		INT

if @varKSiDocType = 2
	select @varKScIF = (case @varKSiIFType when 1 then '1' when 2 then '2' else 1 end)  
else 
	select @varKScIF = (case @varKSiIFType when 2 then '2' else '1' end)  
set @varKSintPerNum = 0

-- Выбираем счета из фильтра
DECLARE @DEP_ACC  TABLE (LINK_ACC [INT])	
IF LEN (@varKScVal1) > 0
	INSERT INTO @DEP_ACC
	SELECT RECORD
	FROM OBJECT_VAR_DEPARTMENT_ACCOUNTS
	WHERE LINK_UP = @varKSnOtborLink1
ELSE
	INSERT INTO @DEP_ACC
	SELECT LINK
	FROM dbo.DICTIONARY_DEP_ACCOUNTS_ZB
	WHERE NOT @varKSiDocType = 3 UNION
	SELECT LINK
	FROM dbo.DICTIONARY_ACCOUNTS
	WHERE @varKSiDocType = 3 AND 
		TYPE = 2
-- Выбираем КБК из фильтров по Подразделам и ЦС
DECLARE @varKStVKR  TABLE (LINK [INT])	
IF LEN (@varKScVal2) > 0 AND LEN (@varKScVal3) > 0
	INSERT INTO @varKStVKR
	SELECT LINK
	FROM dbo.KL_KBK KBK
	INNER JOIN dbo.KL_VKR VKR ON KBK.LINK = VKR.LINK_KBK 
	INNER JOIN dbo.OBJECT_VAR_DIVISION OVD ON OVD.LINK_UP = @varKSnOtborLink2 AND OVD.RECORD = VKR.LINK_DIV
	INNER JOIN dbo.OBJECT_VAR_TARGET_ITEM OVI ON OVI.LINK_UP = @varKSnOtborLink3 AND OVI.RECORD = VKR.LINK_CSR

IF LEN (@varKScVal2) > 0 AND NOT LEN (@varKScVal3) > 0
	INSERT INTO @varKStVKR
	SELECT LINK
	FROM dbo.KL_KBK KBK
	INNER JOIN dbo.KL_VKR VKR ON KBK.LINK = VKR.LINK_KBK
	INNER JOIN dbo.OBJECT_VAR_DIVISION OVD ON OVD.LINK_UP = @varKSnOtborLink2 AND OVD.RECORD = VKR.LINK_DIV 

IF NOT LEN (@varKScVal2) > 0 AND LEN (@varKScVal3) > 0
	INSERT INTO @varKStVKR
	SELECT LINK
	FROM dbo.KL_KBK KBK
	INNER JOIN dbo.KL_VKR VKR ON KBK.LINK = VKR.LINK_KBK
	INNER JOIN dbo.OBJECT_VAR_TARGET_ITEM OVI ON OVI.LINK_UP = @varKSnOtborLink3 AND OVI.RECORD = VKR.LINK_CSR

IF LEN (@varKScVal2) = 0 AND NOT LEN (@varKScVal3) > 0
	INSERT INTO @varKStVKR
	SELECT LINK
	FROM dbo.KL_KBK
	WHERE TYPE = 1


SET @intMAX_REC = 9

CREATE TABLE #TAB_TEMP (
	PER_NUM 	int,
	PERIOD 		VARchar(20),
	VKR		int, 
	EKR		INT, 
	DOP_CL		INT, 
	DEP_ACC 	int,
	DEP_NAME 	VARCHAR(254),
	ACC_CODE 	VARCHAR(25),
	EKRCODE 	VARCHAR(3),
	VKR_CODE	VARCHAR(25), 
	VKR_NAME 	VARCHAR(254), 
	DOP_CODE 	VARCHAR(100),
	SUMMA	[numeric](28, 2) NULL)

SELECT @varKSFinObjCode = (CASE @varKSiDocType 	WHEN 1 	THEN  'FINANS_LIMIT'
						WHEN 2 	THEN  'FINANS_ASSIGN'
						WHEN 3 	THEN  'FB_RESULT_FINANS'
						WHEN 11 THEN  'FINANS_LIMIT_SVOD'
						WHEN 12 THEN  'FINANS_ASSIGN_SVOD' END)

IF @varKSFinObjCode like '%_ASSIGN%'
BEGIN
	SELECT @varKSintTypePer = max(FIN_SMETA_PER) FROM WorkMode
	SELECT @varKSintSummaType = ISNULL(UM,1) FROM FINANS_ASSIGN_OPTIONS
	SET @varKSiNItog = 0 + (@varKSiNItog & 2)
END
IF @varKSFinObjCode like '%_LIMIT%'
BEGIN
	SELECT	@varKSintTypePer = max(FIN_LIM_PER) /* * 10 + max(FIN_LIM_PER))*/ FROM WorkMode
	SELECT @varKSintSummaType = ISNULL(UM,1) FROM FINANS_LIMIT_OPTIONS
	SET @varKSiNItog = 0 + (@varKSiNItog & 2)
END
IF @varKSFinObjCode = 'FB_RESULT_FINANS'
	IF (@varKSiNItog & 1) = 1
		SELECT @varKSintTypePer = 1, @varKSintSummaType = ISNULL(UM,1),@varKSintPerNum = 0  FROM FB_RESULT_FINANS_OPTIONS
	ELSE
		SELECT @varKSintTypePer = 13, @varKSintSummaType = ISNULL(UM,1),@varKSintPerNum = month(@varKSdDate)  FROM FB_RESULT_FINANS_OPTIONS
	
IF (@varKSiNItog & 2) = 2
BEGIN
	if @varKSiFyear is null
		SELECT F.VKR, 
			F.DEP_ACC, 
			D.NAME  AS DEP_NAME, 
			DA.CODE AS ACC_CODE,
			rtrim(KBK.CODE) + '.' + EKR.CODE AS VKR_CODE, 
			KBK.NAME AS VKR_NAME,
			[SUMMA] = F.ITOGS
		FROM (SELECT FS.VKR, FS.EKR, 
			FH.ACCOUNT as DEP_ACC, 
			sum(FS.P1) as P1,
			sum(FS.P2) as P2,
			sum(FS.P3) as P3,
			sum(FS.P4) as P4,
			sum(FS.P5) as P5,
			sum(FS.P6) as P6,
			sum(FS.P7) as P7,
			sum(FS.P8) as P8,
			sum(FS.P9) as P9,
			sum(FS.P10) as P10,
			sum(FS.P11) as P11,
			sum(FS.P12) as P12,
			[ITOGS] = sum(FS.P1 + FS.P2 + FS.P3 + FS.P4 + FS.P5 + FS.P6 + FS.P7 + FS.P8 + FS.P9 + FS.P10 + FS.P11 + FS.P12)
			from dbo.FINANSE FS
			inner join dbo.FINANSE_HEAD FH on FH.LINK = FS.LINK_UP
			inner join dbo.BufferGetTableByID('REESTR_RESULT') B on FH.LINK = B.LINK
			GROUP BY FS.VKR, FS.EKR, FH.ACCOUNT) F
		INNER JOIN DEPARTMENT_ACCOUNTS DA ON F.DEP_ACC = DA.LINK AND DA.LINK in (select LINK_ACC from @DEP_ACC)
		LEFT JOIN DEPARTMENTS D ON DA.LINK_UP = D.LINK
		LEFT JOIN KL_KBK KBK ON F.VKR = KBK.LINK
		LEFT JOIN KOSGU EKR ON F.EKR = EKR.LINK
		WHERE F.VKR in (select LINK from @varKStVKR) AND
			NOT F.ITOGS = 0
		ORDER BY DEP_NAME, ACC_CODE, VKR_CODE	
	else
	begin
		SELECT F.VKR, 
			F.DEP_ACC, 
			D.NAME  AS DEP_NAME, 
			DA.CODE AS ACC_CODE,
			KBK.CODE AS VKR_CODE, 
			KBK.NAME AS VKR_NAME,
			[SUMMA] = F.ITOGS
		FROM (SELECT FS.VKR, 
			FS.DEP_ACC, 
			sum(FS.P1) as P1,
			sum(FS.P2) as P2,
			sum(FS.P3) as P3,
			sum(FS.P4) as P4,
			sum(FS.P5) as P5,
			sum(FS.P6) as P6,
			sum(FS.P7) as P7,
			sum(FS.P8) as P8,
			sum(FS.P9) as P9,
			sum(FS.P10) as P10,
			sum(FS.P11) as P11,
			sum(FS.P12) as P12,
			[ITOGS] = sum(FS.P1 + FS.P2 + FS.P3 + FS.P4 + FS.P5 + FS.P6 + FS.P7 + FS.P8 + FS.P9 + FS.P10 + FS.P11 + FS.P12)
			FROM dbo.FB_REST_FINANS(@varKSiFyear, @varKSdDate, @varKSintPerNum, @varKSintSummaType,0, @varKSFinObjCode, @varKSintTypePer, @varKScIF,DEFAULT) FS
			GROUP BY FS.VKR, FS.DEP_ACC) F
		INNER JOIN DEPARTMENT_ACCOUNTS DA ON F.DEP_ACC = DA.LINK AND DA.LINK in (select LINK_ACC from @DEP_ACC)
		LEFT JOIN DEPARTMENTS D ON DA.LINK_UP = D.LINK
		LEFT JOIN KL_KBK KBK ON F.VKR = KBK.LINK
		WHERE F.VKR in (select LINK from @varKStVKR) AND
			NOT F.ITOGS = 0
		ORDER BY DEP_NAME, ACC_CODE, VKR_CODE	
		
		IF @@ROWCOUNT <> 0
			SELECT TOP 1 
				NUMBER 	 = '',
				[DATE1]	 = dbo.DateBeginOfYear(@varKSdDate),
				[DATE2]	 = @varKSdDate,
				DEP_CODE = D.CODE,
				DEP_NAME = D.NAME,
				ACC_CODE = DA.CODE,
				RBS_NAME = D.VED_NAME,
				BUDG	 = '',
				D.TOFK,
				D.TOFK_NAME
			FROM dbo.DICTIONARY_DEPARTMENT D
			LEFT JOIN dbo.DICTIONARY_ACCOUNTS DA ON D.LINK = DA.REF_LINK_D AND DA.TYPE = 3 
			WHERE D.LINK = ISNULL(dbo.BK_GetDepZB (), dbo.GetOwnDepLink())  
	end 
END
ELSE
BEGIN
	INSERT INTO #TAB_TEMP (PER_NUM, PERIOD, VKR, EKR, DOP_CL, DEP_ACC, DEP_NAME, ACC_CODE, EKRCODE, VKR_CODE, VKR_NAME, DOP_CODE, SUMMA)
	SELECT * FROM (SELECT P.ORD,(CASE @varKSintTypePer when 1 then 'год' else P.PERIOD end) as PERIOD, F.VKR, F.EKR, F.DOP_CL, F.DEP_ACC, 
		D.NAME  AS DEP_NAME, DA.CODE AS ACC_CODE,ISNULL(EKR.CODE,'000') AS EKRCODE, KBK.CODE AS VKR_CODE, KBK.NAME AS VKR_NAME,  DCL.CODE AS DOP_CODE,
		[SUMMA] = (CASE P.ORD WHEN 1 THEN F.P1
				  WHEN 2 THEN F.P2
				  WHEN 3 THEN F.P3
				  WHEN 4 THEN F.P4
				  WHEN 5 THEN F.P5
				  WHEN 6 THEN F.P6
				  WHEN 7 THEN F.P7
				  WHEN 8 THEN F.P8
				  WHEN 9 THEN F.P9
				  WHEN 10 THEN F.P10
				  WHEN 11 THEN F.P11
				  WHEN 12 THEN F.P12
				  WHEN 13 THEN F.P1 + F.P2 + F.P3
				  WHEN 14 THEN F.P4 + F.P5 + F.P6
				  WHEN 15 THEN F.P7 + F.P8 + F.P9
				  WHEN 16 THEN F.P10 + F.P11 + F.P12
				  ELSE F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11 + F.P12 END)
	FROM PERIODS P 
	INNER JOIN (SELECT FS.VKR, FS.EKR, FS.DOP_CL, FS.DEP_ACC, 
		convert(numeric(18,2),sum(FS.P1)) as P1,
		sum(FS.P2) as P2,
		sum(FS.P3) as P3,
		sum(FS.P4) as P4,
		sum(FS.P5) as P5,
		sum(FS.P6) as P6,
		sum(FS.P7) as P7,
		sum(FS.P8) as P8,
		sum(FS.P9) as P9,
		sum(FS.P10) as P10,
		sum(FS.P11) as P11,
		sum(FS.P12) as P12,
		[ITOGS] = sum(FS.P1 + FS.P2 + FS.P3 + FS.P4 + FS.P5 + FS.P6 + FS.P7 + FS.P8 + FS.P9 + FS.P10 + FS.P11 + FS.P12)
		FROM dbo.FB_REST_FINANS(@varKSiFyear, @varKSdDate, @varKSintPerNum, @varKSintSummaType,0, @varKSFinObjCode, @varKSintTypePer, @varKScIF,DEFAULT) FS
		GROUP BY FS.VKR, FS.EKR, DOP_CL, FS.DEP_ACC) F ON F.EKR is not null AND F.VKR in (select LINK from @varKStVKR)--AND NOT SUMMA = 0
	INNER JOIN DEPARTMENT_ACCOUNTS DA ON F.DEP_ACC = DA.LINK AND DA.LINK in (select LINK_ACC from @DEP_ACC)
	LEFT JOIN DEPARTMENTS D ON DA.LINK_UP = D.LINK
	LEFT JOIN KL_KBK KBK ON F.VKR = KBK.LINK
	
	LEFT JOIN DICTIONARY_ITEM EKR ON F.EKR = EKR.LINK 
	left outer JOIN dbo.DOP_CLASSIF DCL ON DCL.LINK = F.DOP_CL
		WHERE 	(P.ORD < 13 AND (@varKSintTypePer = 3 or @varKSintTypePer = 13)) OR
			(P.ORD > 12 AND P.ORD < 17 AND @varKSintTypePer = 2) OR 
			(P.ORD = 20 AND @varKSintTypePer = 1)) FS WHERE NOT FS.SUMMA = 0 
	ORDER BY FS.DEP_ACC,FS.ORD, FS.VKR, FS.EKR
	IF @@ROWCOUNT = 0
		select * from #TAB_TEMP where 1>2
	ELSE 
	BEGIN
		SET @varKSintResult = 1
		create table #TAB_TEMP1(PER_NUM	int, 
					VKR	int, 
					DOP_CL	int, 
					DEP_ACC	int, 
					SUMMA	NUMERIC(19,2))
		insert into #TAB_TEMP1(PER_NUM, VKR, DOP_CL, DEP_ACC, SUMMA)
		select PER_NUM, VKR, DOP_CL, DEP_ACC, SUM(SUMMA)
		from #TAB_TEMP
		group by PER_NUM, VKR, DOP_CL, DEP_ACC    		
			
		-- Разворачиваем таблицу по ЭКР
		EXEC X_GET_TABLE_NAME @cCROSS_TABLE OUTPUT
		EXEC M_CROSS_TABLE 'PER_NUM, PERIOD, VKR, DOP_CL, DEP_ACC, DEP_NAME, ACC_CODE, VKR_CODE, VKR_NAME, DOP_CODE', 'EKRCODE', 'VARCHAR (60)', 'SUMMA', 'NUMERIC (28,4)', 'SUM (SUMMA) AS SUMMA', '#TAB_TEMP', @cCROSS_TABLE
		
		-- добавляем пустые столбцы до конца страницы
		SELECT @intCOUNTER = COUNT (DISTINCT EKR) FROM #TAB_TEMP 
			SET @intCOUNTER = ISNULL (@intCOUNTER, 0)
			SET @intCOUNT_COLROW = @intCOUNTER
			WHILE @intCOUNTER < @intMAX_REC
			BEGIN
				SET @intCOUNTER = @intCOUNTER + 1
				SET @cCOUNTER = LTRIM (STR (@intCOUNTER))
				SET @cSQL_STR = 'ALTER TABLE ' + @cCROSS_TABLE
					+ ' ADD EKRCODE_' + @cCOUNTER + ' VARCHAR (60) '
					+ ', SUMMA_' + @cCOUNTER + ' [NUMERIC] (28,4)'
				EXECUTE (@cSQL_STR)
			END 
		
			IF @intCOUNT_COLROW = 0
				EXEC ('INSERT INTO ' + @cCROSS_TABLE + ' (vkr_code) VALUES ('''') ')
		
		
		EXEC ('select T.*, TI.SUMMA as SUMMAI from ' + @cCROSS_TABLE + ' T
			left join #TAB_TEMP1 TI on T.PER_NUM = TI.PER_NUM and T.VKR = TI.VKR AND (T.DOP_CL = TI.DOP_CL or T.DOP_CL is null and TI.DOP_CL is null) AND T.DEP_ACC = TI.DEP_ACC
			ORDER BY T.DEP_ACC, T.PER_NUM, T.VKR_CODE,T.DOP_CODE')
		
		
		DROP TABLE #TAB_TEMP
		DROP TABLE #TAB_TEMP1
		EXEC ('DROP TABLE ' + @cCROSS_TABLE)
		
		select 	[um] 	= @varKSintSummaType, 
			[title]	= (case @varKSiDocType 	WHEN 1 	THEN  'ЛИМИТЫ БЮДЖЕТНЫХ ОБЯЗАТЕЛЬСТВ'
							WHEN 2 	THEN  'БЮДЖЕТНЫЕ АССИГНОВАНИЯ'
							WHEN 11 THEN  'СВОДНЫЕ ЛИМИТЫ БЮДЖЕТНЫХ ОБЯЗАТЕЛЬСТВ' 
							WHEN 12 THEN  'СВОДНЫЕ БЮДЖЕТНЫЕ АССИГНОВАНИЯ' END),
			[Month] = PERIOD,
			[DATE2]	 = @varKSdDate,
			[DATE1]	 = dbo.DateBeginOfYear(@varKSdDate)
		FROM PERIODS where ord = month(@varKSdDate)  
	END
END	

RETURN @varKSintResult



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
IF EXISTS (SELECT * 
           FROM dbo.[SYSOBJECTS]
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_EXPORT_FORM_FNS_830]') AND 
                 OBJECTPROPERTY(ID, N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_EXPORT_FORM_FNS_830]
END
GO
----------------------

CREATE PROCEDURE [dbo].[RA_EXPORT_FORM_FNS_830]
@iLINK_SAVED_FORM INT,                    -- Линк выгружаемой формы  
 @vcFILE_NAME    VARCHAR(100)='' OUTPUT, -- Имя текстового файла  
 @iMODE          INT=1                   -- Формат: 2-внутренний, 1-минфиновский  
AS  
  
SET NOCOUNT ON  
SET DATEFORMAT dmy  

DECLARE @iLINK_FORM		 INT,
      	@iLINK_TABLE	 INT,
        @iLINK_ORG       INT, 
        @dBEGIN_DATE     DATETIME,
        @dFORM_DATE      DATETIME,
        @sYear           SMALLINT, 
        @vcOrgname       VARCHAR(1000),
        @vcKOD_ORGAN     VARCHAR(8000),
        @vcVersion       VARCHAR(8000),
        @vcProgramName   VARCHAR(100),
        @vcPeriod        VARCHAR(2),
        @vcCRC           VARCHAR(8000),  
        @vcInn           VARCHAR(50),
        @vcKpp           VARCHAR(9),
        @vcOkpo          VARCHAR(20),
        @vcOkato         VARCHAR(11),
        @vcPPP           VARCHAR(50), 
        @iUchr_Link      INT,
        @vcOrgname_Uchr  VARCHAR(1000),
        @vcInn_Uchr      VARCHAR(50),
        @vcKpp_Uchr      VARCHAR(9),
        @vcOkpo_Uchr     VARCHAR(20),
        @vcSurname       VARCHAR(60),
        @vcFirstName     VARCHAR(60),
        @vcMiddleName    VARCHAR(60),
        @vcSurname_GB    VARCHAR(60),
        @vcFirstName_GB  VARCHAR(60),
        @vcMiddleName_GB VARCHAR(60),
        @vcDateRegl      VARCHAR(10),
        @vcExec          VARCHAR(8000),  
        @bCancel         BIT,
        @iReturn         INT,
        @vcNAME          VARCHAR(8000),
        @vcFORM_CODE     VARCHAR(8000),  
        @vcFILE_NAME_XSD VARCHAR(100),    
        @CODE            VARCHAR(10),
        @v_code          VARCHAR(10),
        @C_CODE          VARCHAR(10),
        @vc_code         VARCHAR(10),
        @vcAcc           VARCHAR(2)
DECLARE @val             VARCHAR(8000), 
        @str             VARCHAR(8000), 
        @str1            VARCHAR(8000)
          
CREATE TABLE #tabXML ([TXT]	  VARCHAR(8000),
							 [ORDERS] INT IDENTITY(1,1))

IF OBJECT_ID('tempdb..#tabExportOutput') IS NOT NULL  
BEGIN  
   SELECT @vcVersion = [VERSION]  
   FROM #tabExportOutput   
END  
  
--IF @iMODE = 2  
--BEGIN  
-- EXEC @iReturn = dbo.[RN_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,  
--                 @vcFILE_NAME OUTPUT,  
--                 @iMODE  
-- RETURN @iReturn  
--END  
  
IF @bCancel = 1  
BEGIN  
   RETURN 0  
END  
  
SET @bCancel = 0         
SET @vcNAME = 'Разделительный (ликвидационный) баланс государственного (муниципального) учреждения'
SET  @vcFORM_CODE = '0503830'
SET @vcVersion = '5.02'
SET @vcPeriod = '90'  
SELECT @vcProgramName = CASE WHEN CODE_TASK = 'SMETA'   THEN 'СМЕТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'KADRY'   THEN 'КАДРЫ-КС'
                             WHEN CODE_TASK = 'SALARY'  THEN 'ЗАРПЛАТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'DELO'    THEN 'ДЕЛО-КС'
                             WHEN CODE_TASK = 'ADMIN'   THEN 'АДМИНИСТРАТОР'
                             ELSE ''
                        END       
FROM [dbo].USER_INFO                                  

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_ORG  = [Link_Organization]         
FROM dbo.[report_saved_forms] A  
WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM   

--Таблица
SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 1

CREATE TABLE #tabAttr ([CHECKED] INT, 
                       [UPD]     INT, 
                       [DEL]     INT, 
                       [LINK_SAVED_FORM] INT, 
                       [LINK_ROW] INT, 
                       [ORDERS]   INT, 
                       [CALC_ORDERS] INT, 
                       [PRINT_NULL] INT, 
                       [CODE] VARCHAR(50), COL1 VARCHAR(8000), 
                       COL2 VARCHAR(8000), COL3 VARCHAR(8000), COL4 VARCHAR(8000), 
                       COL5 VARCHAR(8000), COL6 VARCHAR(8000), COL7 VARCHAR(8000), 
                       COL8 VARCHAR(8000), COL9 VARCHAR(8000), COL10 VARCHAR(8000), 
                       COL11 VARCHAR(8000), itog VARCHAR(8000))
  SET @vcExec = 'INSERT #tabAttr
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  EXEC(@vcExec)

--Справка
SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 2

CREATE TABLE #tabAttr1 ([CHECKED] INT, 
                       [UPD]     INT, 
                       [DEL]     INT, 
                       [LINK_SAVED_FORM] INT, 
                       [LINK_ROW] INT, 
                       [ORDERS]   INT, 
                       [CALC_ORDERS] INT, 
                       [PRINT_NULL] INT, 
                       [CODE] VARCHAR(50), COL1 VARCHAR(8000), 
                       COL2 VARCHAR(8000), COL3 VARCHAR(8000), COL4 VARCHAR(8000), 
                       COL5 VARCHAR(8000), COL6 VARCHAR(8000), COL7 VARCHAR(8000), 
                       COL8 VARCHAR(8000), COL9 VARCHAR(8000), itog VARCHAR(8000))
  SET @vcExec = 'INSERT #tabAttr1
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  EXEC(@vcExec)

-- Выгрузка подписей.
 SELECT   @vcOrgname = substring(dbo.[RA_XML_MASK](d.[FULL_NAME]),1,1000),
          @vcInn     = rtrim(ltrim(d.[INN])),
          @vcKpp     = rtrim(ltrim(d.[KPP])),
          @vcOkpo    = d.[OKPO],
          @vcOkato   = d.[OKATO],
          @iUchr_Link    = d.[UCHR_LINK]
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iLINK_ORG
 SELECT   @vcInn_Uchr     = isnull(d.[INN],''),
          @vcKpp_Uchr     = isnull(d.[KPP],''),
          @vcOkpo_Uchr    = isnull(d.[OKPO],''),
          @vcOrgName_Uchr = isnull(dbo.[RA_XML_MASK](d.[FULL_NAME]),'')
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iUchr_Link
 SELECT @vcKOD_ORGAN = [SONO],
        @vcPPP       = [VED]
 FROM PrintDoc_GetDepData2(@iLINK_ORG)   
 SELECT @vcSurname=ch.[FM],
        @vcFirstName=ch.[IM],
        @vcMiddleName=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Руководитель') ch
 WHERE ch.link_dep = @iLINK_ORG
 SELECT @vcSurname_GB=ch.[FM],
        @vcFirstName_GB=ch.[IM],
        @vcMiddleName_GB=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Главный бухгалтер') ch
 WHERE ch.link_dep = @iLINK_ORG
 IF (@vcSurname='' OR @vcSurname IS NULL OR LEN(@vcSurname)=0) SELECT @vcSurname='A'
 IF (@vcFirstName='' OR @vcFirstName IS NULL OR LEN(@vcFirstName)=0) SELECT @vcFirstName='A'
 IF @vcInn = '' SELECT @vcInn='9999999999'
 IF @vcKpp = '' SELECT @vcKpp='999999999'
 IF @vcKOD_ORGAN IS NULL SELECT @vcKOD_ORGAN=''
--Дата начала   
SELECT @dBEGIN_DATE = A.[Begin_Date],
       @sYear = CAST(YEAR(@dBEGIN_DATE) AS VARCHAR(4)),  
       @vcDateRegl = convert(varchar(12), @dBEGIN_DATE+1, 104) 
  FROM dbo.[report_saved_forms] A
  WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM
--Дата документа
 SELECT @dFORM_DATE=GETDATE()
  
SET @vcCRC = RTRIM(CONVERT(VARCHAR(100), NEWID()))  
--Имя файла
SELECT @vcExec =  'NO_BOUCHR8_' +  @vcKOD_ORGAN+ '_' +  
                  @vcKOD_ORGAN+ '_' + @vcINN + @vcKPP + '_' +  
                  CAST(YEAR(@dFORM_DATE) AS VARCHAR(4)) + 
                  RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '_' + @vcCRC,
       @vcFILE_NAME =  @vcExec + '.xml',
       @vcFILE_NAME_XSD =  @vcExec + '.xsd'
--Вставка XML
INSERT #tabXML([TXT]) VALUES ('<?xml  version ="1.0"  encoding ="windows-1251"?>')
INSERT #tabXML([TXT]) VALUES ('<Файл ИдФайл="'+@vcExec+'" '+'ВерсПрог="'+@vcProgramName+'" '+'ВерсФорм="'+@vcVersion+'">')
INSERT #tabXML([TXT]) VALUES ('  <Документ КНД="' + @vcFORM_CODE + '" ДатаДок="'+RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '.' +  
                               RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ '.' + CAST(YEAR(@dFORM_DATE) AS VARCHAR(4))+
                               '" Период="' + @vcPeriod + '" ОтчетГод="'+CAST(@sYear AS VARCHAR(4))+'" НомКорр="0" ОКЕИ="383">')
INSERT #tabXML([TXT]) VALUES ('    <СвНП')
IF @vcOkpo<>'' AND LEN(@vcOkpo) BETWEEN 8 AND 10 
begin INSERT #tabXML([TXT]) VALUES (' ОКПО="'+LTRIM(RTRIM(@vcOkpo))+'"') end
IF @vcOkato<>'' AND LEN(@vcOkato)=11
begin INSERT #tabXML([TXT]) VALUES (' ОКАТО="'+@vcOkato+'"') end
IF @vcOkpo_Uchr<>'' AND LEN(@vcOkpo_Uchr) BETWEEN 8 AND 10 
INSERT #tabXML([TXT]) VALUES (' ОКПО_Учр="'+LTRIM(RTRIM(@vcOkpo_Uchr))+'"') 
IF @vcPPP<>'' AND LEN(@vcPPP)<4
INSERT #tabXML([TXT]) VALUES (' ГлаваБК="' + @vcPPP + '"')
INSERT #tabXML([TXT]) VALUES ('>')
INSERT #tabXML([TXT]) VALUES ('      <НПЮЛ НаимОрг="'+@vcOrgname+'" ИННЮЛ="'+LTRIM(RTRIM(@vcInn))+'" КПП="'+@vcKpp+'"')
IF @vcOrgName_Uchr<>'' 
begin INSERT #tabXML([TXT]) VALUES (' Учредит="'+@vcOrgName_Uchr+'"') end
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('</СвНП>')
INSERT #tabXML([TXT]) VALUES ('<Подписант ПрПодп="1">')
INSERT #tabXML([TXT]) VALUES ('<ФИО Фамилия="'+@vcSurname+'" Имя="'+@vcFirstName+'"')
IF @vcMiddleName<>''
INSERT #tabXML([TXT]) VALUES ('Отчество="'+@vcMiddleName+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
IF @vcSurname_GB<>'' AND @vcFirstName_GB<>''
begin
INSERT #tabXML([TXT]) VALUES ('<ФИОГлБух Фамилия="'+@vcSurname_GB+'" Имя="'+@vcFirstName_GB+'"')
IF @vcMiddleName_GB<>''
INSERT #tabXML([TXT]) VALUES ('Отчество="'+@vcMiddleName_GB+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
end
INSERT #tabXML([TXT]) VALUES ('</Подписант>')
INSERT #tabXML([TXT]) VALUES ('<Баланс ДатаОтч="'+@vcDateRegl+'" >')
INSERT #tabXML([TXT]) VALUES ('<Актив>')
INSERT #tabXML([TXT]) VALUES ('<НефинАктив>')
-----------------------------------------------
DECLARE B_CURSOR CURSOR FOR      
SELECT CODE FROM #tabAttr 
  WHERE CODE LIKE '__0' AND CODE<=150
OPEN B_CURSOR      
FETCH NEXT FROM B_CURSOR INTO @CODE      
WHILE @@FETCH_STATUS = 0         
BEGIN  
  SELECT @str1='',@v_code=''
  IF      @CODE='010' SELECT @str1='<БалансОС>'    ,@v_code=@CODE
  ELSE IF @CODE='020' SELECT @str1='<АмортОС>'     ,@v_code=@CODE
  ELSE IF @CODE='030' SELECT @str1='<ОстатОС>'     ,@v_code=@CODE
  ELSE IF @code='040' SELECT @str1='<НеМатАктБС>'  ,@v_code=@CODE
  ELSE IF @code='050' SELECT @str1='<АмортНмА>'    ,@v_code=@CODE
  ELSE IF @code='060' SELECT @str1='<НеМатАктОС>'  ,@v_code=@CODE
  ELSE IF @code='070' SELECT @str1='<НеПроизвАкт>' ,@v_code=@CODE
  ELSE IF @code='080' SELECT @str1='<МатЗапас>'    ,@v_code=@CODE
  ELSE IF @code='090' SELECT @str1='<ВложНеФинАкт>',@v_code=@CODE
  ELSE IF @code='100' SELECT @str1='<НеФинАктП>'   ,@v_code=@CODE
  ELSE IF @code='140' SELECT @str1='<ИзгГотовПрод>',@v_code=@CODE
  ELSE IF @code='150' SELECT @str1='<Итого>'       ,@v_code=@CODE
  ELSE                SELECT @str1=''              ,@v_code=''
  INSERT #tabXML([TXT]) SELECT @str1
 DECLARE C_CURSOR CURSOR FOR      
 SELECT [CODE] FROM #tabAttr WHERE [CODE] LIKE SUBSTRING(@v_code,1,2)+'_'
 OPEN C_CURSOR      
 FETCH NEXT FROM C_CURSOR INTO @C_CODE      
 WHILE @@FETCH_STATUS = 0         
 BEGIN
SELECT @str1=''      
IF      @code IN ('070','140','150')         SELECT @vc_code=@C_CODE
ELSE IF @c_code in ('010','020','030','040','050','060','080','090','100')                   
                                             SELECT @str1='<Всего>'      ,@vc_code=@C_CODE
ELSE IF @c_code in ('011','021','031')       SELECT @str1='<НедИмущУчр>' ,@vc_code=@C_CODE
ELSE IF @c_code in ('012','022','032','092') SELECT @str1='<ОЦДИмущУчр>' ,@vc_code=@C_CODE
ELSE IF @c_code in ('013','023','033','093') SELECT @str1='<ИнДИмущУчр>' ,@vc_code=@C_CODE
ELSE IF @c_code in ('014','024','034','094') SELECT @str1='<ПрЛизинг>'   ,@vc_code=@C_CODE
ELSE IF @c_code in ('041','051','081')       SELECT @str1='<ОЦДИмущУчр>' ,@vc_code=@C_CODE
ELSE IF @c_code in ('042','052','062')       SELECT @str1='<ИнДИмущУчр>' ,@vc_code=@C_CODE
ELSE IF @c_code in ('043','053','063')       SELECT @str1='<ПрЛизинг>'   ,@vc_code=@C_CODE
ELSE IF @c_code='061'                        SELECT @str1='<ОЦИмущУчр>'  ,@vc_code=@C_CODE
ELSE IF @c_code='091'                        SELECT @str1='<НеДИмущУчр>' ,@vc_code=@C_CODE
ELSE IF @c_code='101'                        SELECT @str1='<НеДИмущУчрП>',@vc_code=@C_CODE
ELSE IF @c_code='102'                        SELECT @str1='<ОЦДИмущУчрП>',@vc_code=@C_CODE
ELSE IF @c_code='103'                        SELECT @str1='<ИнДИмущУчрП>',@vc_code=@C_CODE
ELSE IF @c_code='104'                        SELECT @str1='<ПрЛизингП>'  ,@vc_code=@C_CODE
ELSE                                         SELECT @str1=''             ,@vc_code=''  
INSERT #tabXML([TXT]) SELECT @str1
SELECT @val='', @str=''
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=@vc_CODE
if @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val  + '"'END
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=@vc_CODE
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val  + '"'END
SELECT @val=[COL5] FROM #tabAttr WHERE  [CODE]=@vc_CODE
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val  + '"'END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL6]+'"/>' FROM #tabAttr WHERE [CODE]	=@vc_CODE
end
SELECT @val='', @str=''
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=@vc_CODE
if @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val  + '"'END
SELECT @val=[COL8] FROM #tabAttr WHERE  [CODE]=@vc_CODE
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val  + '"'END
SELECT @val=[COL9] FROM #tabAttr WHERE  [CODE]=@vc_CODE
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val  + '"'END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL10]+'"/>' FROM #tabAttr WHERE [CODE]=@vc_CODE
SELECT @str1=''
IF @c_code in ('010','020','030','040','050','060','080','090','100')                   
                                             SELECT @str1='</Всего>'
ELSE IF @c_code in ('011','021','031')       SELECT @str1='</НедИмущУчр>'
ELSE IF @c_code in ('012','022','032','092') SELECT @str1='</ОЦДИмущУчр>'
ELSE IF @c_code in ('013','023','033','093') SELECT @str1='</ИнДИмущУчр>' 
ELSE IF @c_code in ('014','024','034','094') SELECT @str1='</ПрЛизинг>' 
ELSE IF @c_code in ('041','051','081')       SELECT @str1='</ОЦДИмущУчр>'
ELSE IF @c_code in ('042','052','062')       SELECT @str1='</ИнДИмущУчр>'
ELSE IF @c_code in ('043','053','063')       SELECT @str1='</ПрЛизинг>' 
ELSE IF @c_code='061'                        SELECT @str1='</ОЦИмущУчр>'
ELSE IF @c_code='091'                        SELECT @str1='</НеДИмущУчр>'
ELSE IF @c_code='101'                        SELECT @str1='</НеДИмущУчрП>'
ELSE IF @c_code='102'                        SELECT @str1='</ОЦДИмущУчрП>'
ELSE IF @c_code='103'                        SELECT @str1='</ИнДИмущУчрП>'
ELSE IF @c_code='104'                        SELECT @str1='</ПрЛизингП>'
ELSE SELECT @str1='' 
INSERT #tabXML([TXT]) SELECT @str1

FETCH NEXT FROM C_CURSOR INTO @C_CODE      
END      
CLOSE C_CURSOR      
DEALLOCATE C_CURSOR   
  SELECT @str1=''
  IF      @CODE='010' SELECT @str1='</БалансОС>'    
  ELSE IF @CODE='020' SELECT @str1='</АмортОС>'     
  ELSE IF @CODE='030' SELECT @str1='</ОстатОС>'     
  ELSE IF @code='040' SELECT @str1='</НеМатАктБС>'  
  ELSE IF @code='050' SELECT @str1='</АмортНмА>'    
  ELSE IF @code='060' SELECT @str1='</НеМатАктОС>'  
  ELSE IF @code='070' SELECT @str1='</НеПроизвАкт>' 
  ELSE IF @code='080' SELECT @str1='</МатЗапас>'    
  ELSE IF @code='090' SELECT @str1='</ВложНеФинАкт>'
  ELSE IF @code='100' SELECT @str1='</НеФинАктП>'   
  ELSE IF @code='140' SELECT @str1='</ИзгГотовПрод>'
  ELSE IF @code='150' SELECT @str1='</Итого>'       
  ELSE                SELECT @str1=''
  INSERT #tabXML([TXT]) SELECT @str1

FETCH NEXT FROM B_CURSOR INTO @CODE      
END      
CLOSE B_CURSOR      
DEALLOCATE B_CURSOR
------------------------------------------------
INSERT #tabXML([TXT]) VALUES('</НефинАктив>')
INSERT #tabXML([TXT]) VALUES('<ФинАктив>')
------------------------------------------------
DECLARE B_CURSOR CURSOR FOR      
SELECT CODE FROM #tabAttr WHERE CODE LIKE '__0' AND CODE BETWEEN 170 AND 400
OPEN B_CURSOR      
FETCH NEXT FROM B_CURSOR INTO @CODE      
WHILE @@FETCH_STATUS = 0         
BEGIN  
  SELECT @str1='',@v_code=''
  IF      @code='170' SELECT @str1='<ДенСрУчр>'     ,@v_code=@CODE
  ELSE IF @CODE='210' SELECT @str1='<ФинВлож>'      ,@v_code=@CODE
  ELSE IF @CODE='230' SELECT @str1='<РасчДоход>'    ,@v_code=@CODE
  ELSE IF @code='260' SELECT @str1='<РасчВыдАванс>' ,@v_code=@CODE
  ELSE IF @code='290' SELECT @str1='<РасчКредит>'   ,@v_code=@CODE
  ELSE IF @code='310' SELECT @str1='<РасчПОтчЛиц>'  ,@v_code=@CODE
  ELSE IF @code='320' SELECT @str1='<РасчУщербИмущ>',@v_code=@CODE
  ELSE IF @code='330' SELECT @str1='<ПрочРасчДеб>'  ,@v_code=@CODE
  ELSE IF @code='370' SELECT @str1='<ВложФинАкт>'   ,@v_code=@CODE
  ELSE IF @code='400' SELECT @str1='<Итого>'        ,@v_code=@CODE
  ELSE                SELECT @str1=''               ,@v_code=''
  INSERT #tabXML([TXT]) SELECT @str1

DECLARE C_CURSOR CURSOR FOR      
SELECT [CODE] FROM #tabAttr WHERE [CODE] LIKE SUBSTRING(@v_code,1,2)+'_'
OPEN C_CURSOR      
FETCH NEXT FROM C_CURSOR INTO @C_CODE      
WHILE @@FETCH_STATUS = 0         
BEGIN  
  SELECT @str1='',@vc_code=''
  IF      @c_code IN ('230','260','310','320','400') SELECT @vc_code=@C_CODE
  ELSE IF @c_code in ('170','210','290','330','370') SELECT @str1='<Всего>',@vc_code=@C_CODE
  ELSE IF @c_code='171'      SELECT @str1='<ЛицСчОргКазн>',@vc_code=@C_CODE
  ELSE IF @c_code='172'      SELECT @str1='<ОргКазнПут>',@vc_code=@C_CODE
  ELSE IF @c_code='173'      SELECT @str1='<СчетКО>',@vc_code=@C_CODE
  ELSE IF @c_code='174'      SELECT @str1='<КОПут>',@vc_code=@C_CODE
  ELSE IF @c_code='175'      SELECT @str1='<АккрСчетКО>',@vc_code=@C_CODE
  ELSE IF @c_code='176'      SELECT @str1='<ИнВалСчКО>' ,@vc_code=@C_CODE
  ELSE IF @c_code='177'      SELECT @str1='<Касса>',@vc_code=@C_CODE
  ELSE IF @c_code='178'      SELECT @str1='<ДенДокум>',@vc_code=@C_CODE
  ELSE IF @c_code='179'      SELECT @str1='<РазмДепКО>',@vc_code=@C_CODE
  ELSE IF @c_code IN ('211','371') SELECT @str1='<ЦенБумКрАкц>',@vc_code=@C_CODE
  ELSE IF @c_code IN ('212','372') SELECT @str1='<АкцИнКапит>',@vc_code=@C_CODE
  ELSE IF @c_code IN ('213','373') SELECT @str1='<ИнФинАктив>',@vc_code=@C_CODE
  ELSE IF @c_code='291'      SELECT @str1='<ПредстКредит>',@vc_code=@C_CODE
  ELSE IF @c_code='292'      SELECT @str1='<ЦелИнКредит>',@vc_code=@C_CODE
  ELSE IF @c_code='331'      SELECT @str1='<РасчНДС>',@vc_code=@C_CODE
  ELSE IF @c_code='333'      SELECT @str1='<РасчФОДен>',@vc_code=@C_CODE
  ELSE IF @c_code='335'      SELECT @str1='<РасчПрДеб>',@vc_code=@C_CODE
  ELSE IF @c_code='336'      SELECT @str1='<РасчУчред>',@vc_code=@C_CODE
  ELSE IF @c_code='337'      SELECT @str1='<УмБалСтОЦИ>',@vc_code=@C_CODE
  ELSE IF @c_code='338'      SELECT @str1='<ЧистСтОЦИ>',@vc_code=@C_CODE
  ELSE SELECT @str1='' ,@vc_code='' 
  INSERT #tabXML([TXT]) SELECT @str1
SELECT @val='', @str=''
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=@vc_CODE
if @val<>'0.00' AND @vc_code NOT IN ('336','337','338') begin set @str = @str + ' ДеятЦелСр = "' + @val  + '"'END
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=@vc_CODE
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val  + '"'END
SELECT @val=[COL5] FROM #tabAttr WHERE  [CODE]=@vc_CODE
if @val<>'0.00' AND @vc_code NOT IN ('336','337','338') begin set @str = @str + ' СрВремРасп = "' + @val  + '"'END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL6]+'"/>' FROM #tabAttr WHERE [CODE]	=@vc_CODE
end
SELECT @val='', @str=''
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=@vc_CODE
if @val<>'0.00' AND @vc_code NOT IN ('336','337','338') begin set @str = @str + ' ДеятЦелСр = "' + @val  + '"'END
SELECT @val=[COL8] FROM #tabAttr WHERE  [CODE]=@vc_CODE
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val  + '"'END
SELECT @val=[COL9] FROM #tabAttr WHERE  [CODE]=@vc_CODE
if @val<>'0.00' AND @vc_code NOT IN ('336','337','338') begin set @str = @str + ' СрВремРасп = "' + @val  + '"'END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL10]+'"/>' FROM #tabAttr WHERE [CODE]=@vc_CODE

  SELECT @str1=''
  IF @c_code in ('170','210','290','330','370') 
                             SELECT @str1='</Всего>'
  ELSE IF @c_code='171'      SELECT @str1='</ЛицСчОргКазн>'
  ELSE IF @c_code='172'      SELECT @str1='</ОргКазнПут>'
  ELSE IF @c_code='173'      SELECT @str1='</СчетКО>'
  ELSE IF @c_code='174'      SELECT @str1='</КОПут>'
  ELSE IF @c_code='175'      SELECT @str1='</АккрСчетКО>'
  ELSE IF @c_code='176'      SELECT @str1='</ИнВалСчКО>' 
  ELSE IF @c_code='177'      SELECT @str1='</Касса>'
  ELSE IF @c_code='178'      SELECT @str1='</ДенДокум>'
  ELSE IF @c_code='179'      SELECT @str1='</РазмДепКО>'
  ELSE IF @c_code IN ('211','371') SELECT @str1='</ЦенБумКрАкц>'
  ELSE IF @c_code IN ('212','372') SELECT @str1='</АкцИнКапит>'
  ELSE IF @c_code IN ('213','373') SELECT @str1='</ИнФинАктив>'
  ELSE IF @c_code='291'      SELECT @str1='</ПредстКредит>'
  ELSE IF @c_code='292'      SELECT @str1='</ЦелИнКредит>'
  ELSE IF @c_code='331'      SELECT @str1='</РасчНДС>'
  ELSE IF @c_code='333'      SELECT @str1='</РасчФОДен>'
  ELSE IF @c_code='335'      SELECT @str1='</РасчПрДеб>'
  ELSE IF @c_code='336'      SELECT @str1='</РасчУчред>'
  ELSE IF @c_code='337'      SELECT @str1='</УмБалСтОЦИ>'
  ELSE IF @c_code='338'      SELECT @str1='</ЧистСтОЦИ>'
  ELSE SELECT @str1='' 
  INSERT #tabXML([TXT]) SELECT @str1

FETCH NEXT FROM C_CURSOR INTO @C_CODE      
END      
CLOSE C_CURSOR      
DEALLOCATE C_CURSOR   
SELECT @str1=''
IF      @CODE='170' SELECT @str1='</ДенСрУчр>'
ELSE IF @CODE='210' SELECT @str1='</ФинВлож>'
ELSE IF @CODE='230' SELECT @str1='</РасчДоход>'
ELSE IF @code='260' SELECT @str1='</РасчВыдАванс>'
ELSE IF @code='290' SELECT @str1='</РасчКредит>'
ELSE IF @code='310' SELECT @str1='</РасчПОтчЛиц>'
ELSE IF @code='320' SELECT @str1='</РасчУщербИмущ>'
ELSE IF @code='330' SELECT @str1='</ПрочРасчДеб>'
ELSE IF @code='370' SELECT @str1='</ВложФинАкт>'
ELSE IF @code='400' SELECT @str1='</Итого>'
ELSE SELECT @str1=''
INSERT #tabXML([TXT]) SELECT @str1

FETCH NEXT FROM B_CURSOR INTO @CODE      
END      
CLOSE B_CURSOR      
DEALLOCATE B_CURSOR
---------------------------------------------
INSERT #tabXML([TXT]) VALUES('</ФинАктив>')
INSERT INTO #tabXML([TXT]) VALUES('<Баланс>')
SELECT @val='', @str='',@str1=''
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=410
if @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val + '"' END
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=410
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val + '"' END
SELECT @val=[COL5] FROM #tabAttr WHERE  [CODE]=410
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val + '"' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL6]+'"/>' FROM #tabAttr WHERE [CODE]	=410
end
SELECT @val='', @str=''
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=410
if @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val + '"' END
SELECT @val=[COL8] FROM #tabAttr WHERE  [CODE]=410
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val + '"' END
SELECT @val=[COL9] FROM #tabAttr WHERE  [CODE]=410
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val + '"' END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL10]+'"/>' FROM #tabAttr WHERE [CODE]	=410
INSERT INTO #tabXML([TXT]) VALUES('</Баланс>')
----------------------------------------------
INSERT #tabXML([TXT]) VALUES ('</Актив>')
INSERT #tabXML([TXT]) VALUES ('<Пассив>')
INSERT #tabXML([TXT]) VALUES ('<Обязат>')
----------------------------------------------
DECLARE B_CURSOR CURSOR FOR      
SELECT CODE FROM #tabAttr WHERE CODE LIKE '__0' AND CODE BETWEEN 470 AND 600 
OPEN B_CURSOR      
FETCH NEXT FROM B_CURSOR INTO @CODE      
WHILE @@FETCH_STATUS = 0         
BEGIN  
  SELECT @str1='',@v_code=''
  IF      @CODE='470' SELECT @str1='<РасчКДолгОбяз>',@v_code=@code
  ELSE IF @CODE='490' SELECT @str1='<РасчПрОбяз>',@v_code=@code
  ELSE IF @CODE='510' SELECT @str1='<РасчПлатБюдж>',@v_code=@code
  ELSE IF @code='530' SELECT @str1='<ПрРасчКредит>',@v_code=@code
  ELSE IF @code='600' SELECT @str1='<Итого>',@v_code=@code
  ELSE SELECT @str1='',@v_code='' 
  INSERT #tabXML([TXT]) SELECT @str1

DECLARE C_CURSOR CURSOR FOR      
SELECT [CODE] FROM #tabAttr WHERE [CODE] LIKE SUBSTRING(@V_code,1,2)+'_'
OPEN C_CURSOR      
FETCH NEXT FROM C_CURSOR INTO @C_CODE      
WHILE @@FETCH_STATUS = 0         
BEGIN
  SELECT @str1=''
  IF @c_code IN ('490','600') SELECT @vc_code=@c_code
  ELSE IF @c_code in ('470','510','530') 
                        SELECT @str1='<Всего>',@vc_code=@c_code
  ELSE IF @c_code='471' SELECT @str1='<ДолгОбязРуб>',@vc_code=@c_code
  ELSE IF @c_code='472' SELECT @str1='<ДолгОбязИнКр>',@vc_code=@c_code
  ELSE IF @c_code='474' SELECT @str1='<ДолгОбязВал>',@vc_code=@c_code
  ELSE IF @c_code='511' SELECT @str1='<РасчНДФЛ>',@vc_code=@c_code
  ELSE IF @c_code='512' SELECT @str1='<РасчВзнОСС>',@vc_code=@c_code
  ELSE IF @c_code='513' SELECT @str1='<РасчПриб>',@vc_code=@c_code
  ELSE IF @c_code='514' SELECT @str1='<РасчНДС>',@vc_code=@c_code
  ELSE IF @c_code='515' SELECT @str1='<РасчИнПлат>',@vc_code=@c_code
  ELSE IF @c_code='516' SELECT @str1='<РасчВзнМПС>',@vc_code=@c_code
  ELSE IF @c_code='531' SELECT @str1='<РасчВремСр>',@vc_code=@c_code
  ELSE IF @c_code='532' SELECT @str1='<РасчДепонент>',@vc_code=@c_code
  ELSE IF @c_code='533' SELECT @str1='<РасчУдержОТ>',@vc_code=@c_code
  ELSE IF @c_code='534' SELECT @str1='<РасчВнВедоств>',@vc_code=@c_code
  ELSE IF @c_code='536' SELECT @str1='<РасчПрочКред>',@vc_code=@c_code
  ELSE SELECT @str1='' ,@vc_code='' 
  INSERT #tabXML([TXT]) SELECT @str1
SELECT @val='', @str=''
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=@vc_CODE
if @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val  + '"'END
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=@vc_CODE
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val  + '"'END
SELECT @val=[COL5] FROM #tabAttr WHERE  [CODE]=@vc_CODE
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val  + '"'END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL6]+'"/>' FROM #tabAttr WHERE [CODE]	= @vc_CODE
end
SELECT @val='', @str=''
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=@vc_CODE
if @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val  + '"'END
SELECT @val=[COL8] FROM #tabAttr WHERE  [CODE]=@vc_CODE
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val  + '"'END
SELECT @val=[COL9] FROM #tabAttr WHERE  [CODE]=@vc_CODE
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val  + '"'END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL10]+'"/>' FROM #tabAttr WHERE [CODE] = @vc_CODE

  SELECT @str1=''
  IF      @c_code in ('470','510','530') SELECT @str1='</Всего>'
  ELSE IF @c_code='471' SELECT @str1='</ДолгОбязРуб>'
  ELSE IF @c_code='472' SELECT @str1='</ДолгОбязИнКр>'
  ELSE IF @c_code='474' SELECT @str1='</ДолгОбязВал>'
  ELSE IF @c_code='511' SELECT @str1='</РасчНДФЛ>'
  ELSE IF @c_code='512' SELECT @str1='</РасчВзнОСС>'
  ELSE IF @c_code='513' SELECT @str1='</РасчПриб>'
  ELSE IF @c_code='514' SELECT @str1='</РасчНДС>'
  ELSE IF @c_code='515' SELECT @str1='</РасчИнПлат>'
  ELSE IF @c_code='516' SELECT @str1='</РасчВзнМПС>'
  ELSE IF @c_code='531' SELECT @str1='</РасчВремСр>'
  ELSE IF @c_code='532' SELECT @str1='</РасчДепонент>'
  ELSE IF @c_code='533' SELECT @str1='</РасчУдержОТ>'
  ELSE IF @c_code='534' SELECT @str1='</РасчВнВедоств>'
  ELSE IF @c_code='536' SELECT @str1='</РасчПрочКред>'
  ELSE SELECT @str1='' 
  INSERT #tabXML([TXT]) SELECT @str1
  
FETCH NEXT FROM C_CURSOR INTO @C_CODE      
END      
CLOSE C_CURSOR      
DEALLOCATE C_CURSOR   
  SELECT @str1=''
  IF @code='470' SELECT @str1='</РасчКДолгОбяз>'
  else IF @CODE='490' SELECT @str1='</РасчПрОбяз>'
  else IF @CODE='510' SELECT @str1='</РасчПлатБюдж>'
  else IF @code='530' SELECT @str1='</ПрРасчКредит>'
  else IF @code='600' SELECT @str1='</Итого>'
  ELSE SELECT @str1='' 
  INSERT #tabXML([TXT]) SELECT @str1

FETCH NEXT FROM B_CURSOR INTO @CODE      
END      
CLOSE B_CURSOR      
DEALLOCATE B_CURSOR
---------------------------------------------  
INSERT #tabXML([TXT]) VALUES ('</Обязат>')
INSERT #tabXML([TXT]) VALUES ('<ФинРезул>')
-----------------------------------------
INSERT INTO #tabXML([TXT]) VALUES('<ФинРезХозСуб>')
DECLARE FA_CURSOR CURSOR FOR      
 SELECT CODE      
 FROM #tabAttr      WHERE [CODE] LIKE '62%'
 OPEN FA_CURSOR      
 FETCH NEXT FROM FA_CURSOR INTO @CODE      
 WHILE @@FETCH_STATUS = 0         
 BEGIN  
SELECT @val=[COL10] FROM #tabAttr WHERE  [CODE]=@CODE
 
begin 
SELECT @str1='',@v_code=''
IF      @code='620'  SELECT @str1='<Всего>',@v_code=@code
else IF @code='621'  SELECT @str1='<ДохТекФинГод>',@v_code=@code
else IF @code='622'  SELECT @str1='<РасхТекФинГод>',@v_code=@code
else IF @code='623'  SELECT @str1='<ФинРезПрОПер>',@v_code=@code
else IF @code='6231' SELECT @str1='<ФинРезНАмОЦИ>',@v_code=@code
else IF @code='624'  SELECT @str1='<ДохБудПер>',@v_code=@code
else IF @code='625'  SELECT @str1='<РасхБудПер>',@v_code=@code
ELSE SELECT @str1='',@v_code=''  
INSERT INTO #tabXML([TXT]) SELECT @str1
end
SELECT @val='', @str=''
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=@v_CODE
if @val<>'0.00' AND @v_code NOT IN ('6231') begin set @str = @str + ' ДеятЦелСр = "' + @val + '"' END
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=@v_CODE
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val + '"' END
SELECT @val=[COL5] FROM #tabAttr WHERE  [CODE]=@v_CODE
if @val<>'0.00' AND @v_code NOT IN ('6231') begin set @str = @str + ' СрВремРасп = "' + @val + '"' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL6]+'"/>' FROM #tabAttr WHERE [CODE]	=@v_CODE
end
SELECT @val='', @str=''
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=@v_CODE
if @val<>'0.00' AND @v_code NOT IN ('6231') begin set @str = @str + ' ДеятЦелСр = "' + @val + '"' END
SELECT @val=[COL8] FROM #tabAttr WHERE  [CODE]=@v_CODE
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val + '"' END
SELECT @val=[COL9] FROM #tabAttr WHERE  [CODE]=@v_CODE
if @val<>'0.00' AND @v_code NOT IN ('6231') begin set @str = @str + ' СрВремРасп = "' + @val + '"' END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL10]+'"/>' FROM #tabAttr WHERE [CODE]	=@v_CODE

SELECT @val='', @str=''
SELECT @val=[COL10] FROM #tabAttr WHERE  [CODE]=@v_CODE
 
begin 
SELECT @str1=''   
IF      @code='620'  SELECT @str1='</Всего>'
ELSE IF @code='621'  SELECT @str1='</ДохТекФинГод>'
ELSE IF @code='622'  SELECT @str1='</РасхТекФинГод>'
ELSE IF @code='623'  SELECT @str1='</ФинРезПрОПер>'
ELSE IF @code='6231' SELECT @str1='</ФинРезНАмОЦИ>'
ELSE IF @code='624'  SELECT @str1='</ДохБудПер>'
ELSE IF @code='625'  SELECT @str1='</РасхБудПер>'
ELSE SELECT @str1='' 
INSERT INTO #tabXML([TXT]) SELECT @str1
end

FETCH NEXT FROM FA_CURSOR INTO @CODE      
END      
CLOSE FA_CURSOR      
DEALLOCATE FA_CURSOR   

INSERT INTO #tabXML([TXT]) VALUES('</ФинРезХозСуб>')
-------------------------------------------------
INSERT #tabXML([TXT]) VALUES ('</ФинРезул>')
INSERT INTO #tabXML([TXT]) VALUES('<Баланс>')
SELECT @val='', @str='',@str1=''
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=900
if @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val + '"' END
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=900
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val + '"' END
SELECT @val=[COL5] FROM #tabAttr WHERE  [CODE]=900
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val + '"' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL6]+'"/>' FROM #tabAttr WHERE [CODE]	=900
end
SELECT @val='', @str=''
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=900
if @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val + '"' END
SELECT @val=[COL8] FROM #tabAttr WHERE  [CODE]=900
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val + '"' END
SELECT @val=[COL9] FROM #tabAttr WHERE  [CODE]=900
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val + '"' END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL10]+'"/>' FROM #tabAttr WHERE [CODE]	=900
INSERT INTO #tabXML([TXT]) VALUES('</Баланс>')
---------------------------------------------------
INSERT #tabXML([TXT]) VALUES ('</Пассив>')
INSERT #tabXML([TXT]) VALUES ('<СпрИмущОбЗС>')
----------------------------------------------------
DECLARE B_CURSOR CURSOR FOR      
 SELECT CODE      
 FROM #tabAttr1 WHERE [CODE] LIKE '__0'
 OPEN B_CURSOR      
 FETCH NEXT FROM B_CURSOR INTO @CODE      
 WHILE @@FETCH_STATUS = 0         
 BEGIN
SELECT @vcAcc = COL1 FROM #tabAttr1 WHERE [CODE]=@CODE
SELECT @str1='',@v_code=''
IF      @code='010' SELECT @str1='<ИмущПолПольз НомСчет = "'      + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='020' SELECT @str1= '<МатЦенХран НомСчет = "'        + @vcAcc + '">', @v_code=@CODE
ELSE IF @code='030' SELECT @str1='<БланкСтрОтч НомСчет = "'       + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='040' SELECT @str1='<ДолгНД НомСчетЗаб = "'         + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='050' SELECT @str1='<МатЦенОплЦС НомСчет = "'       + @vcAcc + '">',  @v_code=@CODE                 
ELSE IF @code='060' SELECT @str1='<ДолгНеМатЦен НомСчетЗаб = "'   + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='070' SELECT @str1='<НагрПриз НомСчетЗаб = "'       + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='080' SELECT @str1='<ПутевНеОпл НомСчетЗаб = "'     + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='090' SELECT @str1='<ЗапЧастТС НомСчетЗаб = "'      + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='100' SELECT @str1='<ИспОбяз НомСчет = "'           + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='120' SELECT @str1='<СпецНИРДог НомСчет = "'        + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='130' SELECT @str1='<ЭксперУстр НомСчетЗаб = "'     + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='150' SELECT @str1='<РасчДокНеОпл НомСчетЗаб = "'   + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='160' SELECT @str1='<ПерепПенсНеЗак НомСчетЗаб = "' + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='170' SELECT @str1='<ПостДССчетУчр НомСчет = "'     + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='180' SELECT @str1='<ВыбДССчетУчр НомСчет = "'      + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='200' SELECT @str1='<ДолгНеКред НомСчетЗаб = "'     + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='210' SELECT @str1='<ОснСр3000Экспл НомСчет = "'    + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='220' SELECT @str1='<МатЦенЦСнаб НомСчет = "'       + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='230' SELECT @str1='<ПериодИзд НомСчет = "'         + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='240' SELECT @str1='<ИмущДовУпр НомСчет = "'        + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='250' SELECT @str1='<ИмущВозмПольз НомСчет = "'     + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='260' SELECT @str1='<ИмущБВозмПольз НомСчет = "'    + @vcAcc + '">',  @v_code=@CODE
ELSE                SELECT @str1='', @v_code=''
                
INSERT INTO #tabXML([TXT]) VALUES(@str1)

 DECLARE C_CURSOR CURSOR FOR      
 SELECT [CODE] FROM #tabAttr1 WHERE [CODE] LIKE SUBSTRING(@v_code,1,2)+'_'
 OPEN C_CURSOR      
 FETCH NEXT FROM C_CURSOR INTO @C_CODE      
 WHILE @@FETCH_STATUS = 0         
 BEGIN  
 SELECT @str1=''    
IF      @c_code IN ('060','080','090','130','150','160') 
                           SELECT @vc_code=@c_code 
ELSE IF @c_code in ('010','020','030','040','050','070','100','120','170','180','200','210','220','230','240','250','260') 
                           SELECT @str1='<Всего>',@vc_code=@c_code
ELSE IF @c_code='011'      SELECT @str1='<Недвиж>',@vc_code=@c_code
ELSE IF @c_code='012'      SELECT @str1='<НедвижНепр>',@vc_code=@c_code
ELSE IF @c_code='015'      SELECT @str1='<Движ>',@vc_code=@c_code
ELSE IF @c_code='052'      SELECT @str1='<ЦенДвИмущОС>',@vc_code=@c_code
ELSE IF @c_code='054'      SELECT @str1='<МатЗапас>',@vc_code=@c_code
ELSE IF @c_code='055'      SELECT @str1='<ЦенДвИмущМЗ>',@vc_code=@c_code
ELSE IF @c_code='071'      SELECT @str1='<УсловОцен>',@vc_code=@c_code
ELSE IF @c_code='072'      SELECT @str1='<СтоимПриобр>',@vc_code=@c_code
ELSE IF @c_code='101'      SELECT @str1='<Задаток>',@vc_code=@c_code
ELSE IF @c_code='102'      SELECT @str1='<Залог>',@vc_code=@c_code
ELSE IF @c_code='103'      SELECT @str1='<БанкГарант>',@vc_code=@c_code
ELSE IF @c_code='104'      SELECT @str1='<Поручит>',@vc_code=@c_code
ELSE IF @c_code='105'      SELECT @str1='<ИнОбеспеч>',@vc_code=@c_code
ELSE IF @c_code='171'      SELECT @str1='<Доходы>',@vc_code=@c_code
ELSE IF @c_code IN ('172','181')      SELECT @str1='<Расходы>',@vc_code=@c_code
ELSE IF @c_code IN ('173','182')      SELECT @str1='<ИстФинДефСр>',@vc_code=@c_code
ELSE IF @c_code='211'      SELECT @str1='<ОсЦенДИмущ>',@vc_code=@c_code
ELSE IF @c_code='212'      SELECT @str1='<ИнДИмущ>',@vc_code=@c_code
ELSE IF @c_code IN ('051','221','241','251','261') SELECT @str1='<ОснСредств>',@vc_code=@c_code
ELSE IF @c_code IN (            '242','252','262') SELECT @str1='<НедвижИмущОС>',@vc_code=@c_code
ELSE IF @c_code IN (      '222','243','253','263') SELECT @str1='<ОсЦенДИмущОС>',@vc_code=@c_code
ELSE IF @c_code IN (            '244','254','264') SELECT @str1='<НематАктив>',@vc_code=@c_code
ELSE IF @c_code IN (            '245','255','265') SELECT @str1='<ОсЦенДИмущНА>',@vc_code=@c_code
ELSE IF @c_code IN (      '224','246','256','266') SELECT @str1='<МатЗапас>',@vc_code=@c_code
ELSE IF @c_code IN (      '225','247','257','267') SELECT @str1='<ОсЦенДИмущМЗ>',@vc_code=@c_code
ELSE SELECT @str1='', @vc_code='' 
INSERT INTO #tabXML([TXT]) SELECT @str1
SELECT @val='', @str=''
SELECT @val=[COL4] FROM #tabAttr1 WHERE  [CODE] = @vc_code
IF @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val + '"' END
SELECT @val=[COL5] FROM #tabAttr1 WHERE  [CODE] = @vc_code
IF @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val + '"' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL6]+'"/>' FROM #tabAttr1 WHERE [CODE] = @vc_code
end
SELECT @val='', @str=''
SELECT @val=[COL7] FROM #tabAttr1 WHERE  [CODE] = @vc_code
IF @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val + '"' END
SELECT @val=[COL8] FROM #tabAttr1 WHERE  [CODE] = @vc_code
IF @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val + '"' END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL9]+'"/>' FROM #tabAttr1 WHERE [CODE] = @vc_code
SELECT @str1=''
IF      @c_code in ('010','020','030','040','050','070','100','120','170','180','200','210','220','230','240','250','260') 
                           SELECT @str1='</Всего>'
ELSE IF @c_code='011'      SELECT @str1='</Недвиж>'
ELSE IF @c_code='012'      SELECT @str1='</НедвижНепр>'
ELSE IF @c_code='015'      SELECT @str1='</Движ>'
ELSE IF @c_code='052'      SELECT @str1='</ЦенДвИмущОС>'
ELSE IF @c_code='054'      SELECT @str1='</МатЗапас>'
ELSE IF @c_code='055'      SELECT @str1='</ЦенДвИмущМЗ>'
ELSE IF @c_code='071'      SELECT @str1='</УсловОцен>'
ELSE IF @c_code='072'      SELECT @str1='</СтоимПриобр>'
ELSE IF @c_code='101'      SELECT @str1='</Задаток>'
ELSE IF @c_code='102'      SELECT @str1='</Залог>'
ELSE IF @c_code='103'      SELECT @str1='</БанкГарант>'
ELSE IF @c_code='104'      SELECT @str1='</Поручит>'
ELSE IF @c_code='105'      SELECT @str1='</ИнОбеспеч>'
ELSE IF @c_code='171'      SELECT @str1='</Доходы>'
ELSE IF @c_code IN ('172','181')      SELECT @str1='</Расходы>'
ELSE IF @c_code IN ('173','182')      SELECT @str1='</ИстФинДефСр>'
ELSE IF @c_code='211'      SELECT @str1='</ОсЦенДИмущ>'
ELSE IF @c_code='212'      SELECT @str1='</ИнДИмущ>'
ELSE IF @c_code IN ('051','221','241','251','261') SELECT @str1='</ОснСредств>'
ELSE IF @c_code IN (            '242','252','262') SELECT @str1='</НедвижИмущОС>'
ELSE IF @c_code IN (      '222','243','253','263') SELECT @str1='</ОсЦенДИмущОС>'
ELSE IF @c_code IN (            '244','254','264') SELECT @str1='</НематАктив>'
ELSE IF @c_code IN (            '245','255','265') SELECT @str1='</ОсЦенДИмущНА>'
ELSE IF @c_code IN (      '224','246','256','266') SELECT @str1='</МатЗапас>'
ELSE IF @c_code IN (      '225','247','257','267') SELECT @str1='</ОсЦенДИмущМЗ>'
ELSE SELECT @str1='' 
INSERT INTO #tabXML([TXT]) SELECT @str1

FETCH NEXT FROM C_CURSOR INTO @C_CODE      
END      
CLOSE C_CURSOR      
DEALLOCATE C_CURSOR   
SELECT @str1='',@v_code=''
IF      @code='010' SELECT @str1='</ИмущПолПольз>'
ELSE IF @code='020' SELECT @str1='</МатЦенХран>'
ELSE IF @code='030' SELECT @str1='</БланкСтрОтч>'
ELSE IF @code='040' SELECT @str1='</ДолгНД>'
ELSE IF @code='050' SELECT @str1='</МатЦенОплЦС>'                 
ELSE IF @code='060' SELECT @str1='</ДолгНеМатЦен>'
ELSE IF @code='070' SELECT @str1='</НагрПриз>'
ELSE IF @code='080' SELECT @str1='</ПутевНеОпл>'
ELSE IF @code='090' SELECT @str1='</ЗапЧастТС>'
ELSE IF @code='100' SELECT @str1='</ИспОбяз>'
ELSE IF @code='120' SELECT @str1='</СпецНИРДог>'
ELSE IF @code='130' SELECT @str1='</ЭксперУстр>'
ELSE IF @code='150' SELECT @str1='</РасчДокНеОпл>'
ELSE IF @code='160' SELECT @str1='</ПерепПенсНеЗак>'
ELSE IF @code='170' SELECT @str1='</ПостДССчетУчр>'
ELSE IF @code='180' SELECT @str1='</ВыбДССчетУчр>'
ELSE IF @code='200' SELECT @str1='</ДолгНеКред>'
ELSE IF @code='210' SELECT @str1='</ОснСр3000Экспл>'
ELSE IF @code='220' SELECT @str1='</МатЦенЦСнаб>'
ELSE IF @code='230' SELECT @str1='</ПериодИзд>'
ELSE IF @code='240' SELECT @str1='</ИмущДовУпр>'
ELSE IF @code='250' SELECT @str1='</ИмущВозмПольз>'
ELSE IF @code='260' SELECT @str1='</ИмущБВозмПольз>'
ELSE                SELECT @str1=''
                
INSERT INTO #tabXML([TXT]) VALUES(@str1)

FETCH NEXT FROM B_CURSOR INTO @CODE      
END      
CLOSE B_CURSOR      
DEALLOCATE B_CURSOR
-----------------------------------------------------
INSERT #tabXML([TXT]) VALUES ('</СпрИмущОбЗС>')
INSERT #tabXML([TXT]) VALUES ('</Баланс>')
INSERT #tabXML([TXT]) VALUES ('</Документ>')
INSERT #tabXML([TXT]) VALUES ('</Файл>')
-----------------------------------------------------
INSERT #Files ([TXT], [NAMEFILE],  [NAMEFILE_ARH],  [OrderFile],[LINK_SAVED_FORM])
SELECT         [TXT], @vcFILE_NAME,@vcFILE_NAME_XSD,[ORDERS],   @iLINK_SAVED_FORM
FROM #tabXML
DROP TABLE #tabXML  

GO
GRANT ALL ON dbo.[RA_EXPORT_FORM_FNS_830] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
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))
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)
SELECT D.LINK,left(D.NAME,100),ER.REG_NUM, D.[SODER]
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
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
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.[XA_CRT_FN_LINK_OBJ]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[XA_CRT_FN_LINK_OBJ]

GO
CREATE PROCEDURE [dbo].XA_CRT_FN_LINK_OBJ (@OBJ_CODE VARCHAR(25))
AS

DECLARE @SCRIPT VARCHAR(4000), @NAME VARCHAR(30), @EXECUTE VARCHAR(254)
SET @OBJ_CODE = LTRIM(RTRIM(@OBJ_CODE))
SET @NAME = 'link_' + @OBJ_CODE
SET @EXECUTE = 'EXECUTE XA_CRT_FN_LINK_OBJ ''' + @OBJ_CODE + ''''

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

EXEC (@SCRIPT)

SET @SCRIPT = '
CREATE FUNCTION [dbo].' + @NAME + '()
---Сгенерирована скриптом ' + @EXECUTE + '
RETURNS INT
AS
BEGIN
	RETURN ' + CONVERT(VARCHAR(20), (SELECT TOP 1 LINK FROM dbo.S_OBJECTS WHERE CODE = @OBJ_CODE))	 + '
END
'

EXEC (@SCRIPT)

SET @SCRIPT = '
GRANT EXECUTE ON dbo.[' + @NAME + '] TO PUBLIC
'

EXEC (@SCRIPT)

EXEC dbo.U_UPDATE_SCRIPT_PROPERTY @NAME, @EXECUTE

RETURN 0

GO

GRANT EXECUTE ON dbo.[XA_CRT_FN_LINK_OBJ] TO PUBLIC

GO

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

GO

CREATE   procedure [dbo].SALARY_REP_AVG @varKSLINK int
AS 

select * into #CurDoc from  DOCUMENTS_CALC_AVG   where link = @varKSLINK
----
declare @ref_empl int
set @ref_empl = (select top 1 ref_empl from DOCUMENTS_CALC_AVG   where link = @varKSLINK)

---
CREATE TABLE #NUMERATOR (NUM INT IDENTITY(1,1), Y INT, M INT)
INSERT INTO #NUMERATOR (Y,M)
select DISTINCT YEAR(SD.PERIOD),MONTH(SD.PERIOD)
from dbo.SDOC_AVAC_TABLE2 SD where SD.LINK_UP = @varKSLINK order by YEAR(SD.PERIOD),MONTH(SD.PERIOD)

---
select *  into #Temp from DOCUMENTS_ADD_FUR_TABLE T INNER JOIN #NUMERATOR N ON T.[MONTH] = N.M AND T.[YEAR] = N.Y 
where link = @varKSLINK order by N.NUM

--- Начало периода, за который предоставляется отпуск
declare @dDateBegin datetime
exec KU_GET_DATE_BEGIN_WORK @ref_empl, @dDateBegin output

---
select 	d.num_arhe as doc_num, 
		[date1] = d.PER_ARHE, 
		[subdiv] = EP.SUBDIV_NAME,
		[sub_code] = EP.subdiv_code,
		[FIO] = RTRIM(EP.FM)+' '+RTRIM(EP.IM)+' '+RTRIM(EP.OT),
		[TN] = EP.TAB,
		[TYPE] = D.NAME_TYP_ARHE,
		[TYPE_CODE] =(SELECT CODE FROM dbo.VACATION_VID WHERE LINK =D.REF_TYP_ARHE),
		[DATE_PER1] = (CASE WHEN YEAR(@dDateBegin) = YEAR(D.[Date]) then dbo.ConvertDMY2Date(DAY(@dDateBegin), month(@dDateBegin), year(D.[Date]))
					else dbo.ConvertDMY2Date(DAY(@dDateBegin), month(@dDateBegin), year(D.[Date])-1) end),
		[DATE_PER2] = DATEADD(m,12, (CASE WHEN YEAR(@dDateBegin) = YEAR(D.[Date]) then dbo.ConvertDMY2Date(DAY(@dDateBegin), month(@dDateBegin), year(D.[Date]))
						else dbo.ConvertDMY2Date(DAY(@dDateBegin), month(@dDateBegin), year(D.[Date])-1) end)
					) - 1,
		[DATE_V1] = D.[DATE1],
		[DATE_V2] = D.[DATE2],
		[DAYS1] = (Case when D.[DATE1] =  D.[DATE2]
					then DBO.W_DAYS(7, D.[DATE1], D.[DATE2])
				else NULL end),
		[DAYS2] = (Case when D.[DATE1] <>  D.[DATE2]
					then DBO.W_DAYS(7, D.[DATE1], D.[DATE2])
				else NULL end),

		[DAYS3] = DBO.W_DAYS(7, D.[DATE1], D.[DATE2]),
	  
		[year1] 	= isnull((select top 1 Y from #NUMERATOR where NUM = 1),0),
		[month1]	= isnull((select top 1 M from #NUMERATOR where NUM = 1),0),
		[DAY1]		= isnull((select top 1 [day] from #Temp where NUM = 1),0),
		[sm1] 		= isnull((select SUM(coalesce(summa,0)+coalesce(summa_prem,0)+ coalesce(mater,0)) from #Temp where NUM = 1),0),

		[year2] 	= isnull((select top 1 Y from #NUMERATOR where NUM = 2),0),
		[month2]	= isnull((select top 1 M from #NUMERATOR where NUM = 2),0),
		[DAY2]		= isnull((select top 1 [day] from #Temp T where NUM = 2),0),
		[sm2] 		= isnull((select SUM(coalesce(summa,0)+coalesce(summa_prem,0)+ coalesce(mater,0)) from #Temp where NUM = 2),0),

		[year3] 	= isnull((select top 1 Y from #NUMERATOR where NUM = 3),0),
		[month3]	= isnull((select top 1 M from #NUMERATOR where NUM = 3),0),
		[DAY3]		= isnull((select top 1 [day] from #Temp where NUM = 3),0),
		[sm3] 		= isnull((select SUM(coalesce(summa,0)+coalesce(summa_prem,0)+ coalesce(mater,0)) from #Temp where NUM = 3),0),

		[year4] 	= isnull((select top 1 Y from #NUMERATOR where NUM = 4),0),
		[month4]	= isnull((select top 1 M from #NUMERATOR where NUM = 4),0),
		[DAY4]		= isnull((select top 1 [day] from #Temp where NUM = 4),0),
		[sm4] 		= isnull((select SUM(coalesce(summa,0)+coalesce(summa_prem,0)+ coalesce(mater,0)) from #Temp where NUM = 4),0),

		[year5] 	= isnull((select top 1 Y from #NUMERATOR where NUM = 5),0),
		[month5]	= isnull((select top 1 M from #NUMERATOR where NUM = 5),0),
		[DAY5]		= isnull((select top 1 [day] from #Temp where NUM = 5),0),
		[sm5] 		= isnull((select SUM(coalesce(summa,0)+coalesce(summa_prem,0)+ coalesce(mater,0)) from #Temp where NUM = 5),0),

		[year6] 	= isnull((select top 1 Y from #NUMERATOR where NUM = 6),0),
		[month6]	= isnull((select top 1 M from #NUMERATOR where NUM = 6),0),
		[DAY6]		= isnull((select top 1 [day] from #Temp where NUM = 6),0),
		[sm6] 		= isnull((select SUM(coalesce(summa,0)+coalesce(summa_prem,0)+ coalesce(mater,0)) from #Temp where NUM = 6),0),

		[year7] 	= isnull((select top 1 Y from #NUMERATOR where NUM = 7),0),
		[month7]	= isnull((select top 1 M from #NUMERATOR where NUM = 7),0),
		[DAY7]		= isnull((select top 1 [day] from #Temp where NUM = 7),0),
		[sm7] 		= isnull((select SUM(coalesce(summa,0)+coalesce(summa_prem,0)+ coalesce(mater,0)) from #Temp where NUM = 7),0),

		[year8] 	= isnull((select top 1 Y from #NUMERATOR where NUM = 8),0),
		[month8]	= isnull((select top 1 M from #NUMERATOR where NUM = 8),0),
		[DAY8]		= isnull((select top 1 [day] from #Temp where NUM = 8),0),
		[sm8] 		= isnull((select SUM(coalesce(summa,0)+coalesce(summa_prem,0)+ coalesce(mater,0)) from #Temp where NUM = 8),0),

		[year9] 	= isnull((select top 1 Y from #NUMERATOR where NUM = 9),0),
		[month9]	= isnull((select top 1 M from #NUMERATOR where NUM = 9),0),
		[DAY9]		= isnull((select top 1 [day] from #Temp where NUM = 9),0),
		[sm9] 		= isnull((select SUM(coalesce(summa,0)+coalesce(summa_prem,0)+ coalesce(mater,0)) from #Temp where NUM = 9),0),

		[year10] 	= isnull((select top 1 Y from #NUMERATOR where NUM = 10),0),
		[month10]	= isnull((select top 1 M from #NUMERATOR where NUM = 10),0),
		[DAY10]		= isnull((select top 1 [day] from #Temp where NUM = 10),0),
		[sm10] 		= isnull((select SUM(coalesce(summa,0)+coalesce(summa_prem,0)+ coalesce(mater,0)) from #Temp where NUM = 10),0),

		[year11] 	= isnull((select top 1 Y from #NUMERATOR where NUM = 11),0),
		[month11]	= isnull((select top 1 M from #NUMERATOR where NUM = 11),0),
		[DAY11]		= isnull((select top 1 [day] from #Temp where NUM = 11),0),
		[sm11] 		= isnull((select SUM(coalesce(summa,0)+coalesce(summa_prem,0)+ coalesce(mater,0)) from #Temp where NUM = 11),0),

		[year12] 	= isnull((select top 1 Y from #NUMERATOR where NUM = 12),0),
		[month12]	= isnull((select top 1 M from #NUMERATOR where NUM = 12),0),
		[DAY12]		= isnull((select top 1 [day] from #Temp where NUM = 12),0),
		[sm12] 		= isnull((select SUM(coalesce(summa,0)+coalesce(summa_prem,0)+ coalesce(mater,0)) from #Temp where NUM = 12),0),

		[sm_all]	= isnull((select SUM(coalesce(summa,0)+coalesce(summa_prem,0)+ coalesce(mater,0)) from #Temp where NUM between 1 and 12),0),
		[DAY_all]	= isnull(RP_DAYS,0),
		D.[NUMBER],
		D.[DATE]
into #V1
FROM DOCUMENTS_CALC_AVG   D, KU_EMPL_PLACING EP
where D.LINK =@varKSLINK AND D.REF_EMPL = EP.LINK

----
select * from #V1

----
select 	ORDERS = IDENTITY(int, 1,1), SUMMA = SUM(SUMMA), SUMMA_PREM = SUM(SUMMA_PREM), [MONTH], [YEAR], [DAY], [HOUR], 
	DAY01, HOUR01, KOEF, NUM, Y, M
into 	#Tem 
from 	#Temp 
where 	link = @varKSLINK --AND NUM BETWEEN 1 AND 12
GROUP BY	[MONTH], [YEAR], [DAY], [HOUR], DAY01, HOUR01, KOEF, NUM, Y, M
ORDER BY 	Y, M

----
select  
	ref_pay as ref, 
	[acc_code] = (select rtrim(code) from s_accounts where link = 
			(select top 1 account  from g_prov_ap 
			where  db_kr=1 and  link_up in (select link from G_PROV2 where link_up in (select  link from g_prov1 where oper in (select link_oper from pays where link = ref_pay))))),
	[CODE] = CASE WHEN COALESCE(T2.ORDERS,0) <> COALESCE(T2.NUM,0) then 13 - COALESCE(T2.NUM,0) else COALESCE(T2.NUM,0) end,
	[SUMMA] = (CASE WHEN T2.NUM = 1 THEN KSUMMA1 WHEN T2.NUM = 2 THEN KSUMMA2 WHEN T2.NUM = 3 THEN KSUMMA3 
		WHEN T2.NUM = 4 THEN KSUMMA4 WHEN T2.NUM = 5 THEN KSUMMA5 WHEN T2.NUM = 6 THEN KSUMMA6 
		WHEN T2.NUM = 7 THEN KSUMMA7 WHEN T2.NUM = 8 THEN KSUMMA8 WHEN T2.NUM = 9 THEN KSUMMA9 
		WHEN T2.NUM = 10 THEN KSUMMA10 WHEN T2.NUM = 11 THEN KSUMMA11 WHEN T2.NUM = 12 THEN KSUMMA12 
		END)
into #Temp1  
from documents_add_fur_table1 t1, #Tem T2
where t1.LINK = @varKSLINK


--Для расчета по постановлению 522
declare @LINK_EMPL int, @DATE_BEGIN datetime, @LINK_PAYS int, @INSTR tinyint
select @LINK_EMPL = LINK_EMPL, @DATE_BEGIN = DATE1, @LINK_PAYS = LINK_PAY, @INSTR = coalesce(instr,1) from dbo.SDOC_AVAC where LINK_UP = @varKSLINK

declare @M tinyint
Set @M = 12

IF @INSTR = 2 BEGIN

	Set @M = 13

	INSERT INTO #Temp1 (ref, ACC_CODE, CODE, SUMMA)	
	SELECT 
		LINK_PAYS, 
		[acc_code] = (select rtrim(code) from dbo.s_accounts where link = 
				(select top 1 account  from dbo.g_prov_ap 
				where  db_kr=1 and  link_up in (select link from G_PROV2 where link_up in (select  link from dbo.g_prov1 where oper in (select link_oper from dbo.pays where link = LINK_PAYS))))),
		code = convert(varchar(2),@M),
		summa
	FROM dbo.sa_all_pays_all(@LINK_EMPL, @DATE_BEGIN, NULL, DEFAULT, DEFAULT) P INNER JOIN dbo.group_pays(@LINK_PAYS) T ON P.link_PAYS=T.PAY_LINK
	where
		WAY_CALC not in (6, 7, 12)
END

----
select acc_code, code, sum(summa) as summa into #T1 from #Temp1 where acc_code like '%.302.%' or acc_code like '%.302.%' or acc_code like '%.302.%'
group by acc_code, code

--Список счетов
create table #ACC_CODE (id int identity(1,1), acc_c varchar(6))
insert into #ACC_CODE (acc_c)
SELECT DISTINCT LEFT(acc_code,6) FROM #T1 ORDER BY LEFT(acc_code,6)

----
declare @CurYM int, @norm_days numeric(18,2)
--Set @CurYM = (select min(Year(DATE1) * 100 + month(DATE1)) from DOCUMENTS_ADD_FUR_TABLE0 where link= @varKSLINK )
Set @CurYM = (select min(Year(DATE) * 100 + month(DATE)) from #CurDoc where link= @varKSLINK )

----
set @norm_days = (Select case when Coalesce((Select top 1 payment from #CurDoc),0) = 1
				then dbo.norm_days(REF_EMPL,month(DATE1),YEAR(DATE1))
				else Day(dbo.dateEndOfMonth(Date1)) 
			end
		from #CurDoc)

----
CREATE TABLE #v2 (CAPTION VARCHAR(254), CODE varchar(2), d1 numeric(18,2), d2 numeric(18,2), d3 numeric(18,2), 
sm1 numeric(18,2), sm2 numeric(18,2), sm3 numeric(18,2), acct1 varchar(18), acct2 varchar(10), acct3 varchar(10), 
sr_mes numeric(18,2), sr_d numeric(18,2), sm_m1 numeric(18,2), sm_m2 numeric(18,2), 
sm_d1 numeric(18,2), sm_d2 numeric(18,2), sm_all0 numeric(18,2))

INSERT INTO #v2
select
CAPTION = RTRIM(LTRIM(M.MON)) + ',' + CONVERT(VARCHAR(30),T.Y),
CASE WHEN T.NUM <= 9 THEN '0' + CAST(T.NUM AS CHAR(1)) ELSE CAST(T.NUM AS CHAR(2)) END as [CODE],
[d1] = T.[day],
[d2] = T.[day],
[d3] = T.[day],
[sm1] = isnull((select SUM(summa) from #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 1 and code =T.NUM),0), 
[sm2] = isnull((select SUM(summa) from #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 2 and code =T.NUM),0), 
[sm3] = isnull((select SUM(summa) from #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 3 and code =T.NUM),0),
[acct1] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 1),
[acct2] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 2),
[acct3] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 3),
[sr_mes] =isnull((select TOP 1 (summa_base * @norm_days) from #CurDoc),0),
[sr_d]= isnull((select TOP 1 summa_base  from #CurDoc),0),
[sm_m1] =(select sum(summa) from DOCUMENTS_ADD_FUR_TABLE0 where link = @varKSLINK and Year(DATE1) * 100 + month(DATE1) = @CurYM ) ,
[sm_m2] = (select sum(summa) from DOCUMENTS_ADD_FUR_TABLE0 where link = @varKSLINK and Year(DATE1) * 100 + month(DATE1) <> @CurYM),
[sm_d1] = (select top 1 [DAY] from DOCUMENTS_ADD_FUR_TABLE0 where link = @varKSLINK and Year(DATE1) * 100 + month(DATE1) = @CurYM ) ,
[sm_d2] = (select top 1 [DAY]from DOCUMENTS_ADD_FUR_TABLE0 where link = @varKSLINK and Year(DATE1) * 100 + month(DATE1) <> @CurYM),
[sm_all0] = isnull((select SUM(summa) from #T1  where code =T.NUM),0)
from #Tem T inner join dbo.Months M on T.M = M.NUM
order by t.num


----
declare @varKSsm_all numeric(20,2), @varKSsr_mes numeric(20,4), @varKSsr_d numeric(20,4), @varKSsm_m1 numeric(20,2), @varKSsm_m2 numeric(20,2)
declare @sum_d1 numeric(18,2), @sum_d2 numeric(18,2)
--select top 1 @varKSsr_mes = isnull(sr_mes, 0), @varKSsr_d = isnull(sr_d, 0), @varKSsm_m1 = isnull(sm_m1, 0), @varKSsm_m2 = isnull(sm_m2, 0) from #v2 set @varKSsr_mes = coalesce((select top 1 sr_mes from #v2),0)
--Вычисление среднемесячного заработка. Для 922 постановления Итого за расчетные мес / 12, по 562 не надо делить
set @varKSsr_mes = coalesce((select SUM(coalesce(summa,0)+coalesce(summa_prem,0) + coalesce(mater,0)) from #Temp),0)
IF COALESCE((select COALESCE(instr,1) from dbo.SDOC_AVAC where LINK_UP = @varKSLINK),1) = 1 BEGIN
	IF (select COUNT(ORDERS) from #Temp) > 0
		set @varKSsr_mes = COALESCE(@varKSsr_mes,0) / (select COUNT(ORDERS) from #Temp)
END
---
set @varKSsr_d = coalesce((select top 1 sr_d from #v2),0)
set @varKSsm_m1 = coalesce((select top 1 sm_m1 from #v2),0)
set @varKSsm_m2 = coalesce((select top 1 sm_m2 from #v2),0)
set @sum_d1 = coalesce((select top 1 sm_d1 from #v2),0)
set @sum_d2 = coalesce((select top 1 sm_d2 from #v2),0)

--select @varKSsm_all = sum(sm1+sm2+sm3) from #v2
Set @varKSsm_all = coalesce( (select sum(sm1+sm2+sm3) from #v2),0)

insert into #v2(CAPTION, code,d1, d2, d3, sm1, sm2, sm3, acct1, acct2, acct3, sr_mes, sr_d, sm_m1, sm_m2, sm_all0)
select  'Средний заработок: месячный',
	convert(varchar(2),@M+2), 0,0,0,
	CASE WHEN @varKSsm_all = 0 THEN 0.00 ELSE @varKSsr_mes * sum(sm1)/@varKSsm_all END,
	CASE WHEN @varKSsm_all = 0 THEN 0.00 ELSE @varKSsr_mes * sum(sm2)/@varKSsm_all END,
	CASE WHEN @varKSsm_all = 0 THEN 0.00 ELSE @varKSsr_mes * sum(sm3)/@varKSsm_all END,
	[acct1] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 1),
	[acct2] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 2),
	[acct3] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 3),
	@varKSsr_mes, @varKSsr_d, @varKSsm_m1, @varKSsm_m2,
	@varKSsr_mes
from #v2

insert into #v2(CAPTION, code, d1, d2, d3, sm1, sm2, sm3, acct1, acct2, acct3, sr_mes, sr_d, sm_m1, sm_m2, sm_all0)
select  'Дневной',
	convert(varchar(2),@M+3), 0,0,0,
	CASE WHEN @varKSsm_all = 0 THEN 0.00 ELSE @varKSsr_d * sum(sm1)/@varKSsm_all END,
	CASE WHEN @varKSsm_all = 0 THEN 0.00 ELSE @varKSsr_d * sum(sm2)/@varKSsm_all END,
	CASE WHEN @varKSsm_all = 0 THEN 0.00 ELSE @varKSsr_d * sum(sm3)/@varKSsm_all END,
	[acct1] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 1),
	[acct2] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 2),
	[acct3] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 3),
	@varKSsr_d, @varKSsr_d, @varKSsm_m1, @varKSsm_m2,
	@varKSsr_d
from #v2
where code <= @M

insert into #v2(CAPTION, code, d1, d2, d3, sm1, sm2, sm3, acct1, acct2, acct3, sr_mes, sr_d, sm_m1, sm_m2, sm_all0)
select  'Сумма за отпуск за текущий месяц',
	convert(varchar(2),@M+4), @sum_d1,0,0,
	CASE WHEN @varKSsm_all = 0 THEN 0.00 ELSE @varKSsm_m1 * sum(sm1)/@varKSsm_all END,
	CASE WHEN @varKSsm_all = 0 THEN 0.00 ELSE @varKSsm_m1 * sum(sm2)/@varKSsm_all END,
	CASE WHEN @varKSsm_all = 0 THEN 0.00 ELSE @varKSsm_m1 * sum(sm3)/@varKSsm_all END,
	[acct1] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 1),
	[acct2] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 2),
	[acct3] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 3),
	@varKSsr_d, @varKSsr_d, @varKSsm_m1, @varKSsm_m2,
	@varKSsm_m1
from #v2
where code <= @M

insert into #v2(CAPTION, code,d1, d2, d3, sm1, sm2, sm3, acct1, acct2, acct3, sr_mes, sr_d, sm_m1, sm_m2, sm_all0)
select 'Сумма за отпуск за будущий месяц',
	convert(varchar(2),@M+5), @sum_d2,0,0,
	CASE WHEN @varKSsm_all = 0 THEN 0.00 ELSE @varKSsm_m2 * sum(sm1)/@varKSsm_all END,
	CASE WHEN @varKSsm_all = 0 THEN 0.00 ELSE @varKSsm_m2 * sum(sm2)/@varKSsm_all END,
	CASE WHEN @varKSsm_all = 0 THEN 0.00 ELSE @varKSsm_m2 * sum(sm3)/@varKSsm_all END,
	[acct1] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 1),
	[acct2] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 2),
	[acct3] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 3),
	@varKSsr_d, @varKSsr_d, @varKSsm_m1, @varKSsm_m2, 
	@varKSsm_m2
from #v2
where code <= @M

insert into #v2(CAPTION, code,d1, d2, d3,  sm1, sm2, sm3, acct1, acct2, acct3, sr_mes, sr_d, sm_m1, sm_m2, sm_all0)
select  'Итого за отпуск',
	convert(varchar(2),@M+6), @sum_d1 + @sum_d2,0,0,
	sum(sm1),
	sum(sm2),
	sum(sm3),
	[acct1] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 1),
	[acct2] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 2),
	[acct3] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 3),
	@varKSsr_d, @varKSsr_d, @varKSsm_m1, @varKSsm_m2,
	@varKSsm_m1 + @varKSsm_m2
from #v2
where code >= convert(varchar(2),@M+4)

insert into #v2(CAPTION, code,d1, d2, d3,  sm1, sm2, sm3, acct1, acct2, acct3, sr_mes, sr_d, sm_m1, sm_m2, sm_all0)
select  'Зарплата за текущий месяц',
	convert(varchar(2),@M+7), dbo.WORKDAYS(@ref_empl, @CurYM%100, @CurYM/100, DEFAULT),0,0,
	SUM(CASE WHEN c.id = 1 then summa else 0 end),
	SUM(CASE WHEN c.id = 2 then summa else 0 end),
	SUM(CASE WHEN c.id = 3 then summa else 0 end),
	[acct1] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 1),
	[acct2] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 2),
	[acct3] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 3),
	0, 0, 0, 0,
	SUM(summa)
from s_j_c j left join
	(select distinct P.link, A.code
	from pays P inner join g_prov1 g1 on P.link_oper = G1.link AND P.OBJECT = 1
		inner join G_PROV2 G2 on G2.LINK_UP = G1.link 
		inner join g_prov_ap G on G.link_up = G2.link and G.db_kr = 1
		inner join s_accounts A on A.link = G.account) PA on j.LINK_PAYS = PA.link
	INNER JOIN #ACC_CODE c ON c.acc_c = LEFT(PA.CODE,6)	
where link_empl = @ref_empl and month_begin = @CurYM%100 and year_begin = @CurYM/100 and typ_oper = 1
	and LINK_DOC <> @varKSLINK

----
insert into #v2(CAPTION, code, d1, d2, d3,  sm1, sm2, sm3, acct1, acct2, acct3, sr_mes, sr_d, sm_m1, sm_m2, sm_all0)
select  'Всего начислено',
	convert(varchar(2),@M+8), sum(d1), sum(d2), sum(d3),
	sum(sm1), sum(sm2), sum(sm3),
	[acct1] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 1),
	[acct2] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 2),
	[acct3] = (SELECT TOP 1 acc_code FROM #T1 A INNER JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 3),
	0,0,0,0,
	sum(sm_all0)
from #v2
where code = convert(varchar(2),@M+6) OR code = convert(varchar(2),@M+7)

----
select V2.CODE,
[month]=(CASE WHEN V2.CODE = 1 THEN v1.month1 WHEN V2.CODE = 2 THEN v1.month2 WHEN V2.CODE = 3 THEN v1.month3 
	WHEN V2.CODE = 4 THEN v1.month4 WHEN V2.CODE = 5 THEN v1.month5 WHEN V2.CODE = 6 THEN v1.month6 
	WHEN V2.CODE = 7 THEN v1.month7 WHEN V2.CODE = 8 THEN v1.month8 WHEN V2.CODE = 9 THEN v1.month9 
	WHEN V2.CODE = 10 THEN v1.month10 WHEN V2.CODE = 11 THEN v1.month11 WHEN V2.CODE = 12 THEN v1.month12 
	END),
[year] = (CASE WHEN V2.CODE = 1 THEN v1.year1 WHEN V2.CODE = 2 THEN v1.year2 WHEN V2.CODE = 3 THEN v1.year3 
		WHEN V2.CODE = 4 THEN v1.year4 WHEN V2.CODE = 5 THEN v1.year5 WHEN V2.CODE = 6 THEN v1.year6 
		WHEN V2.CODE = 7 THEN v1.year7 WHEN V2.CODE = 8 THEN v1.year8 WHEN V2.CODE = 9 THEN v1.year9 
		WHEN V2.CODE = 10 THEN v1.year10 WHEN V2.CODE = 11 THEN v1.year11 WHEN V2.CODE = 12 THEN v1.year12 
	END)
into #D1
from #V1 V1, #V2 V2

UPDATE #D1
	SET [month] = month(@DATE_BEGIN), [year] = YEAR(@DATE_BEGIN) 
WHERE
	@INSTR = 2 AND CODE = 13
----
select 	D1.code AS CODE1, sum(summa) as sm1, link_pays, name_pays AS NP, code_pays AS CP, [month], [year]
into #t10
from s_j_c, #D1 D1 
where link_empl = @ref_empl and month_begin = d1.[month] and year_begin = [year] and typ_oper = 2
group by D1.code,link_pays,name_pays,code_pays, [month], [year]

---- Удержания за текущий
insert into #t10
select 	convert(varchar(2),@M+7) AS CODE1, sum(summa) as sm1, link_pays, name_pays AS NP, code_pays AS CP, @CurYM%100 as [month], @CurYM/100 as [year]
from s_j_c j 
where link_empl = @ref_empl and month_begin = @CurYM%100 and year_begin = @CurYM/100 and typ_oper = 2
group by link_pays,name_pays,code_pays

------ Итого удержено
insert into #t10
Select convert(varchar(2),@M+8) as code1, sm1, link_pays, np, cp, [month], [year] 
from #t10 where code1 = convert(varchar(2),@M+7)

----
select code1 as code2, sum(sm1) as sm_all into #t11 from #t10 group by code1
DECLARE @varKSTable_Name VARCHAR(100), @varKStable1 VARCHAR(100)
EXEC X_GET_TABLE_NAME @varKSTable_Name OUTPUT
EXEC X_GET_TABLE_NAME @varKStable1 OUTPUT
EXEC M_CROSS_TABLE 
	'CODE1, MONTH, YEAR',
	'CP, NP',
	'VARCHAR(10)#VARCHAR(254)',
	'SM1', 'NUMERIC(20,2)', 'SUM(SM1) AS SM1',
	#t10,
	@varKSTable_Name

EXEC('SELECT * INTO ' + @varKStable1 + ' FROM #V2 V 
LEFT JOIN #T11 T1 ON V.CODE = T1.CODE2 
LEFT OUTER JOIN ' + @varKSTable_Name + ' T ON V.CODE = T.CODE1' )

DECLARE @varKSCODE_CNT INT, @varKSDELTA INT, @varKSI INT, @varKSSQL_STR VARCHAR(8000)
SET @varKSCODE_CNT = (SELECT COUNT(DISTINCT CP) FROM #t10 )
SET @varKSDELTA = CASE WHEN @varKSCODE_CNT = 0 THEN 8 WHEN @varKSCODE_CNT BETWEEN 1 AND 8 THEN 8 - @varKSCODE_CNT ELSE 0 END

IF @varKSDELTA > 0 BEGIN
	SET @varKSI=1
	WHILE @varKSI<=@varKSDELTA BEGIN
		SET @varKSSQL_STR= 'ALTER TABLE '  + @varKStable1 + '  ADD CP_' + LTRIM(STR(@varKSCODE_CNT+@varKSI)) + '  VARCHAR(10) DEFAULT '''', NP_' + LTRIM(STR(@varKSCODE_CNT+@varKSI)) + '_' + LTRIM(STR(@varKSCODE_CNT+@varKSI)) + ' VARCHAR(254) DEFAULT '''', SM1_'
		+  LTRIM(STR(@varKSCODE_CNT+@varKSI)) + '_' + LTRIM(STR(@varKSCODE_CNT+@varKSI)) + '  NUMERIC(20,2) DEFAULT 0'
		EXEC (@varKSSQL_STR)
		SET @varKSI=@varKSI+1
	END
END

DECLARE @varKSFIELD_NAME VARCHAR(254)
SET @varKSI = 1
SET @varKSCODE_CNT = CASE WHEN @varKSCODE_CNT < 8 THEN 8 ELSE @varKSCODE_CNT END
WHILE @varKSI <=@varKSCODE_CNT BEGIN
	SET @varKSFIELD_NAME= 'CP_' + RTRIM(LTRIM(STR(@varKSI))) 
	SET @varKSSQL_STR= ' UPDATE ' + @varKStable1 + '  SET ' + @varKSFIELD_NAME+ ' = ISNULL((SELECT TOP 1 '+@varKSFIELD_NAME+' FROM ' +@varKSTable_Name + ' WHERE '+
			@varKSFIELD_NAME+ '  IS NOT NULL ), '''') ' 

	EXEC (@varKSSQL_STR)

	SET @varKSFIELD_NAME= 'NP_' + RTRIM(LTRIM(STR(@varKSI))) + '_' + + RTRIM(LTRIM(STR(@varKSI))) 
	SET @varKSSQL_STR= ' UPDATE ' + @varKStable1 + '  SET ' + @varKSFIELD_NAME+ ' = ISNULL((SELECT TOP 1 '+@varKSFIELD_NAME+' FROM ' +@varKSTable_Name + ' WHERE '+
			@varKSFIELD_NAME+ '  IS NOT NULL ), '''') ' 

	EXEC (@varKSSQL_STR)

	SET @varKSFIELD_NAME= 'SM1_' + RTRIM(LTRIM(STR(@varKSI))) + '_' + + RTRIM(LTRIM(STR(@varKSI))) 
	SET @varKSSQL_STR= ' UPDATE ' + @varKStable1 + '  SET ' + @varKSFIELD_NAME+ ' = 0 WHERE ' + @varKSFIELD_NAME + ' IS NULL ' 

	EXEC (@varKSSQL_STR)
	SET @varKSI=@varKSI+1
END

Declare @Script varchar(254)
EXEC('UPDATE ' + @varKStable1 + ' SET SM_ALL = 0 WHERE SM_ALL IS NULL')
set @Script = 'SELECT * FROM ' + @varKStable1 + ' WHERE CODE <= ''' + convert(varchar(2),@M) + ''' ORDER BY CODE'
EXEC (@Script)
Set @Script = 'SELECT * FROM ' + @varKStable1 + ' WHERE CODE > ''' + convert(varchar(2),@M) + ''' ORDER BY CODE'
EXEC (@Script)
Set @Script = 'SELECT CASE WHEN COALESCE(sm_all0,0) > COALESCE(sm_all,0) then  COALESCE(sm_all0,0) - COALESCE(sm_all,0) else 0 end as sm_all0 FROM ' + @varKStable1 + ' WHERE CODE = ''' + convert(varchar(2),@M+8) + ''' ORDER BY CODE'
EXEC (@Script)
EXEC('DROP TABLE ' + @varKSTable_Name)
EXEC('DROP TABLE ' + @varKStable1)



GO


GRANT EXECUTE ON dbo.[SALARY_REP_AVG] TO PUBLIC

GO



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

GO

CREATE    PROCEDURE [dbo].[SA_CREATE_PP_O]
	@LINK_PP INT OUTPUT,
	@LINK_DOC INT,
	@DATE_DOC DATETIME
AS BEGIN

SET NOCOUNT ON

/*Очистить старые сообщения об ошибках*/
DELETE FROM SAL_WORNINGS WHERE SID = SUSER_SID() AND TASK ='SALARY'

Set @LINK_PP = Coalesce((SELECT TOP 1 LINK_rko FROM dbo.sdoc_vedom_rko WHERE LINK_vedom = @LINK_DOC),0)
IF @LINK_PP <> 0 BEGIN
	Select LINK_RKO, COMMENT from dbo.sdoc_vedom_rko where LINK_VEDOM = @LINK_DOC
	RETURN 0
END

DECLARE @iCreatePP INT
SELECT @iCreatePP = dbo.sa_get_option_by_code('XB_NASTR_ZAYAVKA_KR_OR_PP')

DECLARE @OBJ_SNAME VARCHAR(10)
SET @OBJ_SNAME = CASE WHEN @iCreatePP = 0 THEN 'ПП' ELSE 'ЗКР' END

--
DECLARE 
	@NUM_PP 	VARCHAR(25),
	@DATE_PP  	DATETIME,
	@DATE_PROV	DATETIME,
	@SUMMA_PP	numeric(19,2),
	@LINK_KBK  	INT,
	@Add_text 	VARCHAR(100),
	@LINK_PAY 	INT,
	@LINK_EKR 	INT,
	@Osnovanie 	VARCHAR(100),
	@Osnovanie2 	VARCHAR(100),
	@varKSpTARGETTEXT VARCHAR(1000)

CREATE TABLE #tmp (CODE VARCHAR(254), [TNAME] VARCHAR(254), LINK INT, [ANAME] VARCHAR(254), REF_LINK_B INT, REF_LINK_K INT)

--Реквизиты шаблона платежки
DECLARE
	@varKSpKIND           CHAR(50),
	@varKSpS_LINK         INT, --Ссылка на свою организацию		
	@varKSpS_ACC_LINK     INT, --Счет своей организации
	@varKSpD_LINK         INT,		
	@varKSpD_ACC_LINK     INT,
	@varKSpORDER          CHAR(1),
	@varKSpPAYKIND        CHAR(5),
	@varKSpREASON         CHAR(5),
	@varKSpSBANK_LINK     INT,	
	@varKSpDBANK_LINK     INT,
	@varKSpNDSKIND        VARCHAR(100),
	@varKSpNDS            INT,
	@varKSpBK_IN_TGT      tinyint,
	@varKSpPRINT_KPP      tinyint,
	@varKSpNDS_LINK       INT,
	@varKSpDOG_LINK       INT,
	@SROK		      Datetime,
	--
	@AVANSE TINYINT,
	@SHORT BIT,
	@BO_NUM char(10),
	@NDS_SUM NUMERIC(18,2)	

--Назначение платежа из шаблона платежки
DECLARE 
	@varKSpDOH_LINK		INT,
	@varKSpSGU_LINK		INT,
	@varKSpOKATO		VARCHAR(11),
	@varKSpP_REASON		VARCHAR(2),
	@varKSpPERIOD1		VARCHAR(2),
	@varKSpPERIOD		VARCHAR(10),
	@varKSpTREBNUM		VARCHAR(30),
	@varKSpTREBDATE		DATETIME,
	@varKSpZERODATE		BIT,
	@varKSpP_TYPE		VARCHAR(2),
	@varKSpSTATUS		VARCHAR(2),
	@DAY			INT,
	@DT_FULL_CODE_ACC VARCHAR(13),
	@KD_FULL_CODE_ACC VARCHAR(13),
	@ACC_NAME varchar(15),
	@UIN VARCHAR(20)

DECLARE @LINK_DEFAULT_EKR int
SELECT @LINK_DEFAULT_EKR = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '213'

DECLARE @LINK_211EKR int
SELECT @LINK_211EKR = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '211'

---
DECLARE @Cur CURSOR, @SUM_PROV numeric(18,2), @ORDER INT, @Account1 INT, @Account2 INT,	
		@HOZ_OPER INT, @P1 float, @P2 float, @SGU INT, @KD_CODE_ACC VARCHAR(6), @DT_CODE_ACC VARCHAR(6), @LINK_KAU INT, @Fin_Source VARCHAR(1),
		@isNALOG INT, @LINK_DOP_KL INT, @USER_ACC VARCHAR(4), @CODE_SFIN VARCHAR(20), @ACC_CODE VARCHAR(13),
		@varKStrancount INT, @varKSERROR as INT, @REG_NUM VARCHAR(30), @LINK_OBJ INT, @LINK_OBJ_DOCUMENTS_DGH INT, @LINK_ORG INT

SET @LINK_OBJ_DOCUMENTS_DGH = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS WHERE CODE = 'DOCUMENTS_DGH')

DECLARE @Cur1 CURSOR, @LINK_ACC int, @LINK_DOH int, @P_NAME varchar(254), @SHABLON_LINK INT, @LINK_SGU INT

DECLARE @LINK_DEP INT 
SET @LINK_DEP = (SELECT D.LINK_DEP FROM dbo.SDOC D WHERE D.LINK = @LINK_DOC)

DECLARE @BUH_TYPE TINYINT
SET @BUH_TYPE = ISNULL((SELECT BUH_TYPE FROM DBO.DEPARTMENTS WHERE LINK = @LINK_DEP),0)

DECLARE @WORKMODE157N INT
SET @WORKMODE157N = ISNULL((SELECT dbo.XK_GET_NASTR_INT ('XK_WORKMODE157N')),0)
--Если не выполнен переход, то считаем, что тип организации не определён!
SET @BUH_TYPE = CASE WHEN @WORKMODE157N = 0 THEN 0 ELSE @BUH_TYPE END

--IF @BUH_TYPE = 0 BEGIN
--	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
--	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление взносов',
--		'Не определён вид государственного учреждения.',
--		'В реквизитах текущей организации установите реквизит "Вид государственного учреждения".',
--		'SALARY'
--	RETURN 0		
--END

IF NOT EXISTS (SELECT * FROM DBO.SAL_NASTR_PROV WHERE TYPE_OPER = 1 AND TYPE_DEP = @BUH_TYPE) BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление взносов',
		'Не определён счет для выбытия ср-в с лиц. либо расч. счета.',
		'В настройках формирования проводок по зарплате укажите счёта в справочнике "Счета для выбытия ср-в с лиц. либо расч. счета" для данного вида гос. учреждения".',
		'SALARY'
	RETURN 0		
END

-- определим организацию и счет по умолчанию
SET @varKSpS_LINK = @LINK_DEP
INSERT INTO #tmp 
EXEC dbo.XD_DEP_ACCOUNT @varKSpS_ACC_LINK OUTPUT, @varKSpS_LINK, DEFAULT

IF NOT EXISTS (SELECT T1.LINK from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE IN (1,2,4) ) BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление взносов',
	'Не указаны счета в настройках организации.',
	'Требуется указать счета в настройках организации.',
	'SALARY'
	RETURN 0
END


DECLARE @SALARY_OPTIONS_OPT9 INT --Добавлять в назначение платежа наименование операции	
SET @SALARY_OPTIONS_OPT9 = dbo.sa_get_option_by_code('SALARY_OPTIONS_OPT9')

DECLARE @SALARY_OPTIONS_OPT11 INT --Добавлять в назначение платежа рег. номер
SET @SALARY_OPTIONS_OPT11 = dbo.sa_get_option_by_code('SALARY_OPTIONS_OPT11')

SET @Cur1 = CURSOR FORWARD_ONLY
FOR 
SELECT  
	D.[DATE],
	'Перечисление ' + RTRIM(P.SNAME) + ' за ' + coalesce((SELECT TOP 1 MON FROM months WHERE NUM = MONTH(CJ.PERIOD_END)),'') + ',' + CONVERT(VARCHAR(4),coalesce(YEAR(CJ.PERIOD_END),0))
		+ ' по вид.деят. "' + ISNULL((SELECT TOP 1 LTRIM(RTRIM(FS.CODE)) + '.' + LTRIM(RTRIM(FS.NAME)) FROM dbo.BB_FIN_SOURCE FS WHERE FS.CODE = F.SOURCE),'') +  '"',
	'Расчет №' + RTRIM(LTRIM(COALESCE(D.NUMBER,''))) + ' от ' + COALESCE(convert(VARCHAR(10),D.[DATE], 104),''),
	CJ.LINK_PAYS,
	SUM(SUMMA),
	T.LINK_ACC,
	T.LINK_DOH,
	COALESCE(CAST (F.SOURCE as CHAR(1)),''),
	P.[NAME],
	/*Определим шаблон с параметрами платежки*/ 
	CASE WHEN P.WAY_CALC <> 5 THEN 
					CASE WHEN @iCreatePP = 0 THEN dbo.sa_get_option_by_code('ESN_OPT2') ELSE dbo.sa_get_option_by_code('ESN_OPT4') END
				ELSE 
					CASE WHEN @iCreatePP = 0 THEN dbo.sa_get_option_by_code('ESNTR_OPT1') ELSE dbo.sa_get_option_by_code('ESNTR_OPT2') END
				END,
	T.LINK_SGU,
	RTRIM(LTRIM(COALESCE(T.REG_NUM,''))),
	D.OBJECT,
	T.LINK_ORG
FROM dbo.SDOC D INNER JOIN dbo.CALCULATE_JURNAL CJ ON D.LINK = CJ.LINK_DOC
	INNER JOIN dbo.PAYS P ON CJ.LINK_PAYS = P.LINK
	INNER JOIN TAX2_APP T on P.link = T.link_up
	LEFT JOIN  dbo.SAL_SFIN F ON F.LINK = CJ.LINK_VKR
	LEFT JOIN DBO.BB_FIN_SOURCE FUN ON FUN.CODE = F.[SOURCE]
WHERE 
	D.LINK = @LINK_DOC
GROUP BY 
	D.NUMBER, D.[DATE], CJ.PERIOD_END, CJ.LINK_PAYS, P.[NAME], P.SNAME, T.LINK_ACC, T.LINK_DOH, F.[SOURCE], FUN.NAME, P.WAY_CALC,T.LINK_SGU,T.REG_NUM, D.OBJECT, T.LINK_ORG
HAVING 
	SUM(SUMMA) > 0

------
OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @DATE_PP, @Osnovanie, @Add_Text, @LINK_PAY, @SUMMA_PP, @LINK_ACC, @LINK_DOH, @Fin_Source, @P_NAME, @SHABLON_LINK, @LINK_SGU, @REG_NUM, @LINK_OBJ, @LINK_ORG

WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2) 
	BEGIN

		---
		IF NOT EXISTS (SELECT * FROM G_PROV WHERE LINK = @SHABLON_LINK)
		BEGIN
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформированы ' + @OBJ_SNAME + ' на ' + @Osnovanie,
			'Не указан шаблон ' + @OBJ_SNAME + ' в настройках отчисления взносов, или платежка, указанная в качестве шаблона удалена.',
			'Укажите в настройках шаблон в настройках.',
			'SALARY'
			RETURN 0
		END
	
		IF @iCreatePP = 0
			--Реквизиты шаблона платежки
			SELECT  @varKSpKIND = PP.KIND,
				@varKSpD_LINK = PP.D_LINK,
				@varKSpD_ACC_LINK = PP.D_ACC_LINK,
				@varKSpORDER = PP.[ORDER],
				@varKSpPAYKIND = PP.PAYKIND,
				@varKSpREASON = PP.REASON,
				@varKSpSBANK_LINK = PP.SBANK_LINK,		
				@varKSpDBANK_LINK = PP.DBANK_LINK,		
				@varKSpNDSKIND = PP.NDSKIND,	
				@varKSpNDS = PP.NDS,
				@varKSpBK_IN_TGT = PP.BK_IN_TGT,
				@varKSpPRINT_KPP = PP.PRINT_KPP,
				@varKSpNDS_LINK = PP.NDS_LINK,
				@varKSpDOG_LINK = PP.DOG_LINK,
				@SROK 		= PP.SROK,
				@varKSpTARGETTEXT = RTRIM(LTRIM(PP.TARGETTEXT)),
				@BO_NUM = '',
				@AVANSE = 0,
				@SHORT = 0
			FROM dbo.DOCUMENTS_PAY  PP
			WHERE PP.LINK = @SHABLON_LINK
		ELSE
			SELECT  
				@AVANSE = ISNULL(AVANSE,0), --Авансовый платеж 
				@varKSpKIND = KIND, --Вид платежа
				@varKSpD_LINK = KOR_LINK, -- Получатель
				@varKSpD_ACC_LINK = KOR_ACC_LINK, --Номер счета получателя 
				@varKSpORDER = [ORDER], --Очередность платежа     
				@varKSpNDS = NDS, --Процент НДС  
				@varKSpNDS_LINK = NDS_LINK, --Шаблон НДС  
				@SROK 		= SROK, --Срок платежа 
				@SHORT = ISNULL(SHORT,0), -- Сокращенная форма заявки
				@varKSpTARGETTEXT = RTRIM(LTRIM(TARGETTEXT)), --Назначение платежа,
				@BO_NUM = ISNULL(BO_NUM,''),
				@UIN = ISNULL(UIN_CODE,'')
			FROM dbo.BB_ZAYAVKA_KR WHERE LINK = @SHABLON_LINK			
	
		--Назначение платежа из шаблона платежки
		SELECT
			@varKSpDOH_LINK       = DOH_LINK,
			@isNALOG	      = DOH_LINK,
			@varKSpSGU_LINK       = SGU_LINK,
			@varKSpOKATO          = OKATO,
			@varKSpP_REASON  = P_REASON,
			@varKSpPERIOD1         = LEFT(PERIOD,2),
			@varKSpTREBNUM        = '0',
			@varKSpTREBDATE       = @DATE_PP,
			@varKSpZERODATE       = ZERODATE,
			@varKSpP_TYPE         = P_TYPE,
			@varKSpSTATUS         = STATUS,
			@UIN = ISNULL(UIN_CODE,'')
		from dbo.DOCUMENTS_PAY_ADD where link = @SHABLON_LINK
	
		SET @varKSpD_ACC_LINK = COALESCE(@LINK_ACC,@varKSpD_ACC_LINK)
		SET @varKSpDOH_LINK = COALESCE(@LINK_DOH,@varKSpDOH_LINK)
		SET @varKSpTARGETTEXT = @varKSpTARGETTEXT + case when @SALARY_OPTIONS_OPT9 = 1 then CASE WHEN LEN(@varKSpTARGETTEXT) > 0 THEN ', ' else '' end + RTRIM(LTRIM(@P_NAME)) ELSE '' END	
		SET @varKSpTARGETTEXT = @varKSpTARGETTEXT + case when @SALARY_OPTIONS_OPT11 = 1 then CASE WHEN LEN(@varKSpTARGETTEXT) > 0 AND LEN(RTRIM(LTRIM(@REG_NUM))) >0 THEN ', рег.номер ' else '' end + RTRIM(LTRIM(@REG_NUM)) ELSE '' END	
		SET @varKSpSGU_LINK = COALESCE(@LINK_SGU,@varKSpSGU_LINK)
		SET @varKSpPERIOD = @varKSpPERIOD1 + RIGHT(CONVERT(VARCHAR(10),@DATE_PP,104),8)
		SET @DAY = (CASE WHEN @DAY > DAY(dbo.DateEndOfMonth(DATEADD(m,1,@DATE_PP))) THEN DAY(dbo.DateEndOfMonth(DATEADD(m,1,@DATE_PP))) ELSE DAY(@SROK) END)
		SET @SROK = dbo.ConvertDMY2Date(DAY(@SROK), MONTH(DATEADD(m,1,@DATE_PP)), YEAR(DATEADD(m,1,@DATE_PP)))
		SET @DATE_PP = CASE WHEN COALESCE(@DATE_DOC,@DATE_PP) > @DATE_PP THEN @DATE_DOC ELSE @DATE_PP END	
		SET @DATE_PROV = CASE WHEN dbo.sa_get_option_by_code('SALARY_OPTIONS_OPT12') = 1 THEN @DATE_PP ELSE NULL END

		---
		SET @varKStrancount = @@TRANCOUNT
		SET IMPLICIT_TRANSACTIONS ON
		BEGIN TRAN 
		COMMIT TRAN
	
		IF @varKSERROR <> 0
			RETURN @varKSERROR

		IF @DATE_PROV is not null and not exists(Select * from admin_info Where @DATE_PROV BETWEEN BEGINDATE AND ENDDATE) BEGIN
			ROLLBACK
			SET IMPLICIT_TRANSACTIONS OFF
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
				'Программа формирует дату проводки, равную дате платежки. Но эта дата не попадает в период редактирования!',
				'Укажите другую дату платежки, или отключите в общих настройках по зарплате опцию "В бух. документе автоматически ставить дату" проводки, или измените период редактирования.',
				'SALARY'
			GOTO DO_NEXT
		END
	
		-- определим максимальный номер 
		Set @NUM_PP = NULL
	
		IF @iCreatePP = 0
			exec dbo.X_DOCUMENT_GET_NEXT_NUMBER 'DOCUMENTS_PAY', @NUM_PP output, @LINK_DEP
		ELSE
			exec dbo.X_DOCUMENT_GET_NEXT_NUMBER 'BB_ZAYAVKA_KR', @NUM_PP output, @LINK_DEP				
	
		--
		IF @KD_CODE_ACC LIKE '%.21' BEGIN
			
			SET @ACC_NAME = 'расчётный'
			select TOP 1 @varKSpS_ACC_LINK = T1.LINK from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE = 1			
			
		END
		ELSE BEGIN
			
			IF @Fin_Source = 1 BEGIN--бюджетная деятельность
			
				SET @ACC_NAME = 'лицевой'
				select TOP 1 @varKSpS_ACC_LINK = T1.LINK from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE = 2			
			
			END
			ELSE BEGIN
			
				SET @ACC_NAME = 'внебюджетный'			
				select TOP 1 @varKSpS_ACC_LINK = T1.LINK from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE = 4
			
				IF 	COALESCE(@varKSpS_ACC_LINK,0) = 0 BEGIN
				
					SET @ACC_NAME = @ACC_NAME + ' или лицевой'
					select TOP 1 @varKSpS_ACC_LINK = T1.LINK from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE = 2			
				
				END
				
			END	
			
		END
		
		IF COALESCE(@varKSpS_ACC_LINK,0) = 0 BEGIN
			ROLLBACK
			SET IMPLICIT_TRANSACTIONS OFF
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
				'В настройках реквизитов организации на вкладке "счета" не найден ' + @ACC_NAME + ' счет.',
				'Добавьте ' + @ACC_NAME + ' счет в настройках реквизитов организации на вкладке "счета".',
				'SALARY'
			GOTO DO_NEXT
		END		

		-- Сохраняем ПП 
		Set @LINK_PP = NULL
		IF @iCreatePP = 0 BEGIN
			exec X_SAVE_DOCUMENTS_PAY @LINK_PP OUT, @NUM_PP, @DATE_PP, @DATE_PROV, @SUMMA_PP, '',
				@varKSpKIND, @varKSpS_LINK, @varKSpS_ACC_LINK, @varKSpD_LINK, @varKSpD_ACC_LINK,
				@SROK, @varKSpORDER, @varKSpPAYKIND, @varKSpREASON, --@varKSpSBANK_LINK, @varKSpDBANK_LINK,
				@varKSpTARGETTEXT, /*@varKSpNDSKIND, */@varKSpNDS, @varKSpBK_IN_TGT, @varKSpPRINT_KPP,
				@varKSpNDS_LINK, /*@varKSpDOG_LINK*/ 'DOCUMENTS_PAY'
		
			-- Сохраняем назначение платежа
			IF COALESCE(@isNALOG,0) <> 0 
				exec X_SAVE_DOCUMENTS_PAY_ADD @LINK_PP OUT, @varKSpDOH_LINK, @varKSpSGU_LINK, @varKSpOKATO, @varKSpP_REASON,
					 @varKSpPERIOD, @varKSpTREBNUM, @DATE_PP, @varKSpZERODATE, @varKSpP_TYPE, @varKSpSTATUS, @UIN
		END
		ELSE BEGIN
			EXEC dbo.X_SAVE_DOCUMENTS_PAY @LINK_PP OUT, @NUM_PP, @DATE_PP, @DATE_PROV, @SUMMA_PP, '',
				@varKSpKIND, @varKSpS_LINK, @varKSpS_ACC_LINK, @varKSpD_LINK, @varKSpD_ACC_LINK,
				@SROK, @varKSpORDER, NULL, DEFAULT, 
				@varKSpTARGETTEXT, @varKSpNDS, @varKSpBK_IN_TGT, NULL,
				@varKSpNDS_LINK, 'BB_ZAYAVKA_KR'

			SET @NDS_SUM = ISNULL(@SUMMA_PP * ISNULL(@varKSpNDS,0) / 100,0)

			EXEC dbo.X_SAVE_DOCUMENTS_PAY2 @LINK_PP, NULL, @BO_NUM, NULL, @AVANSE, @NDS_SUM, @SHORT

			EXEC dbo.X_SAVE_DOCUMENTS_PAY_ADD @LINK_PP, @varKSpDOH_LINK, @varKSpSGU_LINK, @varKSpOKATO, @varKSpP_REASON,
				 @varKSpPERIOD, @varKSpTREBNUM, @DATE_PP, @varKSpZERODATE, @varKSpP_TYPE, @varKSpSTATUS, @UIN		
					
		END					 
	
		INSERT INTO dbo.sdoc_vedom_rko (LINK_VEDOM, LINK_RKO, LINK_PAYS, COMMENT)
		SELECT @LINK_DOC, @LINK_PP, @LINK_PAY, COALESCE(@Osnovanie,'') + ' ' + @OBJ_SNAME + ' №' + CONVERT(VARCHAR(8), @NUM_PP)  + ' от ' + CONVERT(VARCHAR(10),@DATE_PP,104)
	
		Set @ORDER = 0
		SET @SUMMA_PP = 0

		SET @Cur = CURSOR FORWARD_ONLY
		FOR 
	
			SELECT  
				LINK_KBK = F.KBK,
				LINK_DOP_KL = F.DOP_KL,
				USER_ACC = F.USER_ACC,
				CODE_SFIN = F.CODE,
				(CASE WHEN ISNULL(CJ.link_ekr,@LINK_DEFAULT_EKR) = @LINK_211EKR THEN @LINK_DEFAULT_EKR ELSE ISNULL(CJ.link_ekr,@LINK_DEFAULT_EKR) END), 
				P.CODE_ACC, 
				LINK_KAU = COALESCE(LINK_KAU,F.KAU),
				SUMMA=  (CASE WHEN P.WAY_CALC <> 2 OR @LINK_OBJ_DOCUMENTS_DGH = @LINK_OBJ THEN SUM(SUMMA) 
							ELSE
				
							COALESCE((
							Select  
									SUM((CASE WHEN 
										P1.OBJECT = 3
										THEN 1 ELSE -1 END) * CJ1.SUMMA) 
							from 
								dbo.CALCULATE_JURNAL CJ1 INNER JOIN dbo.PAYS P1 ON CJ1.LINK_PAYS = P1.LINK
							where
								ISNULL(CJ1.link_ekr,@LINK_DEFAULT_EKR) = ISNULL(CJ.link_ekr,@LINK_DEFAULT_EKR)
								AND
								( 
										P1.OBJECT = 3
										OR
										P1.OBJECT = 1 AND ISNULL(CJ1.link_ekr,@LINK_DEFAULT_EKR) = @LINK_DEFAULT_EKR
								)									
								AND
								(P1.[OBJECT] = 1 OR P1.[OBJECT] = 3 AND P1.WAY_CALC = 2)
								AND
								YEAR(CJ1.PERIOD_BEGIN) = YEAR(CJ.PERIOD_BEGIN)
								AND 
								MONTH(CJ1.PERIOD_BEGIN) = MONTH(CJ.PERIOD_BEGIN)
								AND
								CJ1.LINK_VKR = CJ.LINK_VKR
								AND
								CJ1.LINK_DEP = CJ.LINK_DEP
							HAVING 
								SUM((CASE WHEN P1.OBJECT = 3 THEN 1 ELSE -1 END) * CJ1.SUMMA) > 0
							),0)
							
						END)	
			FROM 
				dbo.CALCULATE_JURNAL CJ 
				INNER JOIN dbo.PAYS P ON CJ.LINK_PAYS = P.LINK
				LEFT JOIN  dbo.SAL_SFIN F ON F.LINK = CJ.LINK_VKR
			WHERE 
				LINK_DOC = @LINK_DOC
				AND CJ.LINK_PAYS = @LINK_PAY
				AND F.SOURCE = @Fin_Source
			GROUP BY 
				F.KBK,CJ.LINK_VKR, F.DOP_KL,F.USER_ACC,F.CODE, 
				CJ.link_ekr,
				P.CODE_ACC, COALESCE(LINK_KAU,F.KAU), P.WAY_CALC, CJ.PERIOD_BEGIN, CJ.LINK_DEP
		OPEN @Cur
	
		FETCH NEXT FROM @Cur INTO @LINK_KBK, @LINK_DOP_KL, @USER_ACC, @CODE_SFIN, @LINK_EKR, @DT_CODE_ACC, @LINK_KAU, @SUM_PROV
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN
				IF COALESCE(@SUM_PROV,0) >= 0 BEGIN

					SET @P1 = NULL
					SET @Osnovanie2 = LEFT(@Osnovanie + ' ' + LTRIM(RTRIM(@CODE_SFIN)), 100)
					exec X_UPDATE_G_PROV1 @P1 output, @LINK_PP, NULL, @Osnovanie2, 1
			
					Set @ORDER = @ORDER + 1
					SET @SUMMA_PP = @SUMMA_PP + @SUM_PROV

					IF REPLACE(LTRIM(RTRIM(ISNULL(@DT_CODE_ACC,''))),'.','') = '' BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'Не указан счет кредита в настройках отчисления '+COALESCE(LTRIM(RTRIM(@P_NAME)),''),
							'Укажите в настройках отчисления '+COALESCE(LTRIM(RTRIM(@P_NAME)),'')+' счет кредита.',
							'SALARY'
						GOTO DO_NEXT			
					END

					---
					SET @Account1 = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @DT_CODE_ACC) AND cUser = RTRIM(LTRIM(COALESCE(@USER_ACC,''))))
					SET @DT_FULL_CODE_ACC = @Fin_Source + '.' + @DT_CODE_ACC + CASE WHEN RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> '' THEN '/' + RTRIM(LTRIM(COALESCE(@USER_ACC,''))) ELSE '' END
					
					IF COALESCE(@Account1,0) = 0 BEGIN 
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'В плане счетов не найден счет ' + @DT_FULL_CODE_ACC,
							'Добавьте в план счетов счет ' + @DT_FULL_CODE_ACC,
							'SALARY'
						GOTO DO_NEXT
					END
											
					---
					SET @ACC_CODE = (select top 1 A2.CODE from dbo.S_ACCOUNTS A1 inner join dbo.S_ACCOUNTS A2 on A1.link_self = A2.link
						WHERE A2.LINK = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @DT_CODE_ACC) ) and A2.cSource <> '')
		
					IF  RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) <> '' AND RTRIM(LTRIM(COALESCE(@USER_ACC,''))) = '' BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'У источника финансирования ' + RTRIM(LTRIM(@CODE_SFIN)) + ' не указан пользовательский субсчет, однако у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' есть субсчета',
							'Укажите пользовательский субсчет, либо уберите в плане счетов субсчет у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' с помощью слияния',
							'SALARY'
						GOTO DO_NEXT
					END
		
					--		
					SET @KD_CODE_ACC = (SELECT TOP 1 CODE_ACC FROM DBO.SAL_NASTR_PROV WHERE TYPE_OPER = 1 AND TYPE_DEP = @BUH_TYPE AND TYPE_FUNC = @Fin_Source)

					IF REPLACE(LTRIM(RTRIM(ISNULL(@KD_CODE_ACC,''))),'.','') = '' BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF		
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'Не задан счет для выбытия ср-в с лиц. либо расч. счета для вида организации ' 
							+ ISNULL((SELECT TOP 1 BT_NAME FROM DBO.DICTIONARY_BUH_TYPE WHERE BUH_TYPE = @BUH_TYPE),'')
							+ ' для вида деятельности ' + ISNULL((SELECT TOP 1 NAME FROM DBO.BB_FIN_SOURCE WHERE CODE = @Fin_Source),''),
							'В настройках всех режимов задачи выберите раздел "Настройка счетов для проводок по зарплате" и укажите требуемый счёт в настройке "Счет для выбытия ср-в с лиц. либо расч. счета".',
							'SALARY'
						GOTO DO_NEXT
					END	

					SET @Account2 = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @KD_CODE_ACC) AND cUser = RTRIM(LTRIM(COALESCE(@USER_ACC,''))))
					SET @KD_FULL_CODE_ACC = @Fin_Source + '.' + @KD_CODE_ACC + CASE WHEN RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> '' THEN '/' + RTRIM(LTRIM(COALESCE(@USER_ACC,''))) ELSE '' END

					IF COALESCE(@Account2,0) = 0 BEGIN 
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'В плане счетов не найден счет ' + @KD_FULL_CODE_ACC,
							'Добавьте в план счетов счет ' + @KD_FULL_CODE_ACC,
							'SALARY'
						GOTO DO_NEXT
					END

					---
					SET @ACC_CODE = (select top 1 A2.CODE from dbo.S_ACCOUNTS A1 inner join dbo.S_ACCOUNTS A2 on A1.link_self = A2.link
						WHERE A2.LINK = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @KD_CODE_ACC) ) and A2.cSource <> '')
	
					IF  RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) <> '' AND RTRIM(LTRIM(COALESCE(@USER_ACC,''))) = '' BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'У источника финансирования ' + RTRIM(LTRIM(@CODE_SFIN)) + ' не указан пользовательский субсчет, однако у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' есть субсчета',
							'Укажите пользовательский субсчет, либо уберите в плане счетов субсчет у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' с помощью слияния',
							'SALARY'
						GOTO DO_NEXT
					END

					---
					IF COALESCE(@Account1,0) > 0 AND COALESCE(@Account2,0) > 0 BEGIN
		
						SET @HOZ_OPER = (SELECT TOP 1 LINK FROM dbo.BX_BPROV_VIBOR_ECON_OPER(@Account1,@Account2))
						IF COALESCE(@HOZ_OPER,0) = 0 BEGIN
							ROLLBACK
							SET IMPLICIT_TRANSACTIONS OFF
							INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
								'Не найдено подходящей хоз. операции для проводки ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account1) + '-' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account2),
								'Вероятно в общих настройках по зарплате указан неправильно счет для выбытия бюдж. или внебюдж средств с лицевого либо расчетного счета',
								'SALARY'
							GOTO DO_NEXT
						END	
				
						set @P2 = null
						exec X_UPDATE_G_PROV2 @P2 output, @P1, NULL, @SUM_PROV, 0, 0, @Osnovanie, @HOZ_OPER, @ORDER
			
					---
					SET @SGU = (SELECT TOP 1 LINK_SGU FROM S_ACCOUNTS_SGU SGU INNER JOIN KOSGU ON SGU.LINK_SGU = KOSGU.LINK WHERE DB_KR = 0 AND ACCOUNT = @Account1)
					IF EXISTS (SELECT p_KASSA FROM dbo.s_accounts WHERE LINK = @Account1 AND p_KASSA = 1)
						SET @SGU = @LINK_EKR
	
					IF COALESCE(@SGU,0) = 0 BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'У счета ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account1) + ' не задано СГУ',
							'Укажите СГУ в настройках счета в плане счетов',
							'SALARY'
						GOTO DO_NEXT
					END	
					exec X_UPDATE_G_PROV_AP @P2, 0, @Account1, @LINK_KBK, @LINK_EKR, @LINK_ORG /*Получатель*/, NULL, NULL, NULL, NULL, @LINK_KAU, @varKSpD_ACC_LINK /*Счет получателя*/, NULL, NULL, NULL, @LINK_DOP_KL, NULL, @SGU

					---
					SET @SGU = (SELECT TOP 1 LINK_SGU FROM S_ACCOUNTS_SGU SGU INNER JOIN KOSGU ON SGU.LINK_SGU = KOSGU.LINK WHERE DB_KR = 1 AND ACCOUNT = @Account2)
					IF EXISTS (SELECT p_KASSA FROM dbo.s_accounts WHERE LINK = @Account2 AND p_KASSA = 1)
						SET @SGU = @LINK_EKR
	
					IF COALESCE(@SGU,0) = 0 BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'У счета ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account2) + ' не задано СГУ',
							'Укажите СГУ в настройках счета в плане счетов',
							'SALARY'
						GOTO DO_NEXT
					END	
					exec X_UPDATE_G_PROV_AP @P2, 1, @Account2, @LINK_KBK, @LINK_EKR, @LINK_DEP /*отправитель*/, NULL, NULL, NULL, NULL, @LINK_KAU, @varKSpS_ACC_LINK /*Счет отправителя*/, NULL, NULL, NULL, @LINK_DOP_KL, NULL, @SGU
					END

				END
			END

			IF @iCreatePP = 1
				EXEC dbo.BB_ZAYAVKA_KR_CREATE_TABLE @LINK_PP
				
			FETCH NEXT FROM @Cur INTO @LINK_KBK, @LINK_DOP_KL, @USER_ACC, @CODE_SFIN, @LINK_EKR, @DT_CODE_ACC, @LINK_KAU, @SUM_PROV
		END
		
		CLOSE @Cur
		DEALLOCATE @Cur
		
		--
		UPDATE dbo.G_PROV SET SUMMA = @SUMMA_PP WHERE LINK = @LINK_PP
		
		--
		IF @@TRANCOUNT > @varKStrancount BEGIN
			COMMIT TRAN
			SET IMPLICIT_TRANSACTIONS OFF
		END

		--Платежку с 0 суммой удалим
		IF (select sum(G2.SUMMA)
				from dbo.G_PROV G
				inner join dbo.G_PROV1 G1 on G1.LINK_UP = G.LINK
				inner join dbo.G_PROV2 G2 on G2.LINK_UP = G1.LINK
				where G.LINK = @LINK_PP) = 0
				
				DELETE FROM dbo.G_PROV WHERE LINK = @LINK_PP

		ELSE
		BEGIN			
		
			---Если надо, то сформировать БО
			DECLARE @TestBO tinyint
			exec @TestBO = dbo.XD_TEST_FORM_BO @LINK_PP 

			IF @TestBO = 0
			BEGIN
				create table #tProtocol1(txt varchar(1000), NEW_ROW tinyint, nSTATUS tinyint, nTAB tinyint, ord int identity(1,1))

				insert into #tProtocol1 (txt, NEW_ROW, nSTATUS, nTAB) 
				Exec dbo.XD_FORM_BO @LINK_PP

				IF EXISTS (SELECT * FROM #tProtocol1 WHERE nSTATUS >=1 )
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Обнаружены замечания при формирование БО:', CASE WHEN nSTATUS = 1 THEN 'Предупреждение!' ELSE 'Ошибка!' END + SPACE(1) + LEFT(txt,240), 'Устраните замечания!', 'SALARY'
					FROM #tProtocol1	WHERE nSTATUS >= 1
				
				DROP TABLE #tProtocol1
					
			END	
				
		END		

	
	END
	DO_NEXT:
	FETCH NEXT FROM @Cur1 INTO @DATE_PP, @Osnovanie, @Add_Text, @LINK_PAY, @SUMMA_PP, @LINK_ACC, @LINK_DOH, @Fin_Source, @P_NAME, @SHABLON_LINK, @LINK_SGU, @REG_NUM, @LINK_OBJ, @LINK_ORG
END

CLOSE @Cur1
DEALLOCATE @Cur1

IF @LINK_OBJ_DOCUMENTS_DGH = @LINK_OBJ BEGIN
	/*Создадим платежку на перечисление НДФЛ*/
	SET @P1 = 0
	EXEC SA_CREATE_PP @P1 OUT, @LINK_DOC, @DATE_DOC, 1
END ELSE
	Select LINK_RKO, COMMENT from dbo.sdoc_vedom_rko where LINK_VEDOM = @LINK_DOC

exec X_SALDO_CommitChanges

SET NOCOUNT OFF
Return 0
END



GO


GRANT EXECUTE ON dbo.[SA_CREATE_PP_O] TO PUBLIC

GO

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

GO

CREATE  PROCEDURE [dbo].[SA_CREATE_PP]
			@LINK_PP int OUTPUT,
			@LINK_DOC int,
			@DATE_DOC DATETIME,
			@P TINYINT = 0 -- Признак для подавления проверки на существование платежек
					-- Проверка выполняется в другом месте
AS BEGIN

SET NOCOUNT ON

Set @LINK_PP = Coalesce((SELECT TOP 1 LINK_rko FROM dbo.sdoc_vedom_rko WHERE LINK_vedom = @LINK_DOC),0)
IF (@LINK_PP <> 0 AND @P = 0) BEGIN
	Select LINK_RKO, COMMENT from dbo.sdoc_vedom_rko where LINK_VEDOM = @LINK_DOC
	RETURN 0
END

/*Очистить старые сообщения об ошибках*/
DELETE FROM SAL_WORNINGS WHERE SID = SUSER_SID() AND TASK ='SALARY'

DECLARE @iCreatePP INT
SELECT @iCreatePP = dbo.sa_get_option_by_code('XB_NASTR_ZAYAVKA_KR_OR_PP')

/*Определим шаблон с параметрами*/
DECLARE @SHABLON_LINK INT, @OBJ_SNAME VARCHAR(10)
IF @iCreatePP = 0
	SELECT	@SHABLON_LINK = dbo.sa_get_option_by_code('NDFL_OPT4'),
			@OBJ_SNAME = 'ПП'
ELSE
	SELECT	@SHABLON_LINK = dbo.sa_get_option_by_code('NDFL_OPT10'),
			@OBJ_SNAME = 'ЗКР'
	
---
IF NOT EXISTS (SELECT * FROM dbo.G_PROV WHERE LINK = @SHABLON_LINK)
BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление НДФЛ ',
	'Не указан шаблон ' + @OBJ_SNAME + ' в настройках удержания НДФЛ, или ' + @OBJ_SNAME + ', указанное(ая) в качестве шаблона удалена.',
	'Укажите в настройках шаблон ' + @OBJ_SNAME,
	'SALARY'
	RETURN 0
END
	

---
DECLARE @NUM_PP VARCHAR(25), @LINK_EKR INT, @LINK_EMPL INT, @LINK_KBK INT, @DATE_PP DATETIME 

CREATE TABLE #tmp (CODE VARCHAR(254), [TNAME] VARCHAR(254), LINK INT, [ANAME] VARCHAR(254), REF_LINK_B INT, REF_LINK_K INT)

DECLARE
	@varKSpKIND           CHAR(50),
	@varKSpS_LINK         INT,		
	@varKSpS_ACC_LINK     INT,
	@varKSpD_LINK         INT,		
	@varKSpD_ACC_LINK     INT,
	@varKSpORDER          CHAR(1),
	@varKSpPAYKIND        CHAR(5),
	@varKSpREASON         CHAR(5),
	@varKSpSBANK_LINK     INT,	
	@varKSpDBANK_LINK     INT,
	@varKSpNDSKIND        VARCHAR(100),
	@varKSpNDS            INT,
	@varKSpBK_IN_TGT      tinyint,
	@varKSpPRINT_KPP      tinyint,
	@varKSpNDS_LINK       INT,
	@varKSpDOG_LINK       INT,
	@SROK		      Datetime,
	@varKSpTARGETTEXT     VARCHAR(1000),
	--
	@AVANSE TINYINT,
	@SHORT BIT,
	@BO_NUM char(10),
	@NDS_SUM NUMERIC(18,2),
	@UIN VARCHAR(20)


DECLARE @LINK_DEP INT 
SET @LINK_DEP = (SELECT D.LINK_DEP FROM dbo.SDOC D WHERE D.LINK = @LINK_DOC)

-- определим организацию и счет по умолчанию
SET @varKSpS_LINK = @LINK_DEP
INSERT INTO #tmp 
EXEC dbo.XD_DEP_ACCOUNT @varKSpS_ACC_LINK OUTPUT, @varKSpS_LINK, DEFAULT

IF @iCreatePP = 0
	--Реквизиты ПП
	SELECT  
		@varKSpKIND = PP.KIND, --Вид платежа
		@varKSpD_LINK = PP.D_LINK, -- Получатель
		@varKSpD_ACC_LINK = PP.D_ACC_LINK, --Номер счета получателя 
		@varKSpORDER = PP.[ORDER], --Очередность платежа     
		@varKSpPAYKIND = PP.PAYKIND, --Вид оплаты   
		@varKSpREASON = PP.REASON, --Назначение  
		@varKSpSBANK_LINK = PP.SBANK_LINK, --банк плательщика		
		@varKSpDBANK_LINK = PP.DBANK_LINK,	--банк получателя	
		@varKSpNDSKIND = PP.NDSKIND, --Указание НДС 	
		@varKSpNDS = PP.NDS, --Процент НДС  
		@varKSpBK_IN_TGT = PP.BK_IN_TGT, --Показать БК в назначении платежа  
		@varKSpPRINT_KPP = PP.PRINT_KPP, --Показывать КПП   
		@varKSpNDS_LINK = PP.NDS_LINK, --Шаблон НДС  
		@varKSpDOG_LINK = PP.DOG_LINK, -- Номер договора 
		@SROK 		= PP.SROK, --Срок платежа   
		@varKSpTARGETTEXT = RTRIM(LTRIM(PP.TARGETTEXT)) --Назначение платежа 
	FROM dbo.DOCUMENTS_PAY PP
	WHERE 
		PP.LINK = @SHABLON_LINK
ELSE
	SELECT  
		@AVANSE = ISNULL(AVANSE,0), --Авансовый платеж 
		@varKSpKIND = KIND, --Вид платежа
		@varKSpD_LINK = KOR_LINK, -- Получатель
		@varKSpD_ACC_LINK = KOR_ACC_LINK, --Номер счета получателя 
		@varKSpORDER = [ORDER], --Очередность платежа     
		@varKSpNDS = NDS, --Процент НДС  
		@varKSpNDS_LINK = NDS_LINK, --Шаблон НДС  
		@SROK 		= SROK, --Срок платежа 
		@SHORT = ISNULL(SHORT,0), -- Сокращенная форма заявки
		@varKSpTARGETTEXT = RTRIM(LTRIM(TARGETTEXT)), --Назначение платежа,
		@BO_NUM = ISNULL(BO_NUM,''),
		@UIN = ISNULL(UIN_CODE,'')
	FROM dbo.BB_ZAYAVKA_KR WHERE LINK = @SHABLON_LINK		

DECLARE 
	@varKSpDOH_LINK       INT,
	@varKSpSGU_LINK       INT,
	@varKSpOKATO          VARCHAR(11),
	@varKSpP_REASON       VARCHAR(2),
	@varKSpPERIOD1         VARCHAR(2),
	@varKSpPERIOD         VARCHAR(10),
	@varKSpTREBNUM        VARCHAR(30),
	@varKSpTREBDATE       DATETIME,
	@varKSpZERODATE       BIT,
	@varKSpP_TYPE         VARCHAR(2),
	@varKSpSTATUS         VARCHAR(2),
	@DAY			INT,
	@DT_FULL_CODE_ACC VARCHAR(13),
	@KD_FULL_CODE_ACC VARCHAR(13),
	@ACC_NAME varchar(15)	

--Реквизиты назначения платежа
SELECT
	@varKSpDOH_LINK       = DOH_LINK, --Код дохода
	@varKSpSGU_LINK       = SGU_LINK, --ОСГУ
	@varKSpOKATO          = OKATO, --Код окато
	@varKSpP_REASON       = P_REASON, --Основание платежа
	@varKSpPERIOD1        = LEFT(PERIOD,2), --налоговый период
	@varKSpTREBNUM        = '0', -- Номер требования
	@varKSpTREBDATE       = @DATE_PP, --Дата документа
	@varKSpZERODATE       = ZERODATE, --Дата документа = 0
	@varKSpP_TYPE         = P_TYPE, --Тип платежа
	@varKSpSTATUS         = [STATUS], --Статус плательщика
	@UIN = ISNULL(UIN_CODE,'')
from dbo.DOCUMENTS_PAY_ADD where link = @SHABLON_LINK

DECLARE @LINK_EKR_DEFAULT int
SET @LINK_EKR_DEFAULT = (SELECT TOP 1 LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '211')

IF NOT EXISTS (SELECT T1.LINK from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE IN (1,2,4) ) BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление НДФЛ',
	'Не указаны счета в настройках организации.',
	'Требуется указать счета в настройках организации.',
	'SALARY'
	RETURN 0
END

declare @DEP_LINK int
exec dbo.xd_whats_zb @DEP_LINK output

DECLARE @BUH_TYPE TINYINT
SET @BUH_TYPE = ISNULL((SELECT BUH_TYPE FROM DBO.DEPARTMENTS WHERE LINK = @DEP_LINK),0)

DECLARE @WORKMODE157N INT
SET @WORKMODE157N = ISNULL((SELECT dbo.XK_GET_NASTR_INT ('XK_WORKMODE157N')),0)
--Если не выполнен переход, то считаем, что тип организации не определён!
SET @BUH_TYPE = CASE WHEN @WORKMODE157N = 0 THEN 0 ELSE @BUH_TYPE END

--IF @BUH_TYPE = 0 BEGIN
--	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
--	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление НДФЛ',
--		'Не определён вид государственного учреждения.',
--		'В реквизитах текущей организации установите реквизит "Вид государственного учреждения".',
--		'SALARY'
--	RETURN 0		
--END

IF NOT EXISTS (SELECT * FROM DBO.SAL_NASTR_PROV WHERE TYPE_OPER = 1 AND TYPE_DEP = @BUH_TYPE) BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление НДФЛ',
		'Не определён счет для выбытия ср-в с лиц. либо расч. счета.',
		'В настройках формирования проводок по зарплате укажите счёта в справочнике "Счета для выбытия ср-в с лиц. либо расч. счета" для данного вида гос. учреждения".',
		'SALARY'
	RETURN 0		
END

DECLARE @GROUP_BY_SUB INT
SET @GROUP_BY_SUB = dbo.sa_get_option_by_code('SALARY_PROV_OPT3')

SELECT LINK, SUBDIV_HEAD, SUBDIV_NAME INTO #EMPL_INFO FROM DBO.SD_EMPL

----
DECLARE @CURSOR_EKR CURSOR, @DATE_PROV DATETIME, @Osnovanie VARCHAR(100), @Add_text VARCHAR(100), @link_pay int, @SUMMA_PP as numeric(19,2), @Fin_Source VARCHAR(1), @KD_CODE_ACC VARCHAR(6), @DT_CODE_ACC VARCHAR(6),
	@Cur CURSOR, @SUM_PROV numeric(18,2), @order int, @Account1 INT, @Account2 INT,	@HOZ_OPER int, @P1 float, @P2 float, @SGU INT, @LINK_KAU INT, @LINK_DOP_KL INT, @PAYS_CODE VARCHAR(10),
	@USER_ACC VARCHAR(4), @CODE_SFIN VARCHAR(20), @ACC_CODE VARCHAR(13),
	@varKStrancount INT, @varKSERROR as INT, @LINK_ORG int, @LINK_ACC int, @LINK_DOH int, @SUBDIV_HEAD INT, @SUBDIV_NAME VARCHAR(254),
	@LINK_SFIN INT

SET @CURSOR_EKR = CURSOR FORWARD_ONLY
FOR 
SELECT  
	D.[DATE],
	'Перечисление НДФЛ за ' + coalesce((SELECT TOP 1 MON FROM months WHERE NUM = MONTH(CJ.PERIOD_END)),'') + ',' + CONVERT(VARCHAR(4),coalesce(YEAR(CJ.PERIOD_END),0)) + 'г.' + ' по ' + RTRIM(EKR.CODE) + ' ЭКР ' 
		+ ' по ист.фин. "' + RTRIM(LTRIM(F.CODE)) + '" с вид.деят. "' + RTRIM(LTRIM(ISNULL((SELECT TOP 1 FS.CODE + '.' + FS.NAME FROM dbo.BB_FIN_SOURCE FS WHERE FS.CODE = F.SOURCE),''))) +  '"',
	'Расчет №' + RTRIM(LTRIM(COALESCE(D.NUMBER,''))) + ' от ' + COALESCE(convert(VARCHAR(10),D.[DATE], 104),''),
	CJ.LINK_PAYS,
	SUM(SUMMA),
	@varKSpTARGETTEXT + case when dbo.sa_get_option_by_code('SALARY_OPTIONS_OPT9') = 1 then CASE WHEN LEN(@varKSpTARGETTEXT) > 0 THEN ', ' else '' end + P.[NAME]  + ' по ' + RTRIM(EKR.CODE) + ' ЭКР'  ELSE '' END,
	COALESCE(CJ.link_ekr,@LINK_EKR_DEFAULT),
	P.CODE_ACC, 
	COALESCE(CAST (F.SOURCE as CHAR(1)),''),
	T.LINK_ORG,
	T.LINK_ACC,
	T.LINK_DOH,
	CASE WHEN @GROUP_BY_SUB = 1 THEN SUBDIV_HEAD ELSE NULL END,
	CASE WHEN @GROUP_BY_SUB = 1 THEN SUBDIV_NAME ELSE NULL END,
	F.LINK -- зарплатский источник финансирования
FROM 
	dbo.SDOC D INNER JOIN dbo.CALCULATE_JURNAL CJ ON D.LINK = CJ.LINK_DOC
	INNER JOIN dbo.PAYS P ON (CJ.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC = 4)
	INNER JOIN dbo.DICTIONARY_ITEM EKR ON EKR.LINK = COALESCE(CJ.link_ekr,@LINK_EKR_DEFAULT)
	LEFT JOIN  dbo.SAL_SFIN F ON F.LINK = CJ.LINK_VKR
	LEFT JOIN DBO.BB_FIN_SOURCE FUN ON FUN.CODE = F.[SOURCE]	
	LEFT JOIN TAX2_APP T on P.link = T.link_up
	LEFT JOIN #EMPL_INFO E ON E.LINK = CJ.LINK_EMPL
WHERE 
	D.LINK = @LINK_DOC 
GROUP BY 
	D.NUMBER, D.[DATE], CJ.PERIOD_END, CJ.LINK_PAYS, P.[NAME], CJ.link_ekr, EKR.CODE, P.CODE_ACC, F.SOURCE,	F.CODE, T.LINK_ORG,	T.LINK_ACC,	T.LINK_DOH, CASE WHEN @GROUP_BY_SUB = 1 THEN SUBDIV_HEAD ELSE NULL END,
	CASE WHEN @GROUP_BY_SUB = 1 THEN SUBDIV_NAME ELSE NULL END, F.LINK
HAVING 
	SUM(SUMMA) > 0

OPEN @CURSOR_EKR
FETCH NEXT FROM @CURSOR_EKR INTO @DATE_PP, @Osnovanie, @Add_Text, @link_pay, @SUMMA_PP, @varKSpTARGETTEXT, @link_ekr, @DT_CODE_ACC, @Fin_Source, @LINK_ORG, @LINK_ACC, @LINK_DOH, @SUBDIV_HEAD, @SUBDIV_NAME, @LINK_SFIN
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN

		SET @varKSpPERIOD = @varKSpPERIOD1 + RIGHT(CONVERT(VARCHAR(10),@DATE_PP,104),8)
		SET @DAY = (CASE WHEN DAY(@SROK) > DAY(dbo.DateEndOfMonth(DATEADD(m,1,@DATE_PP))) THEN DAY(dbo.DateEndOfMonth(DATEADD(m,1,@DATE_PP))) ELSE DAY(@SROK) END)
		SET @SROK = dbo.ConvertDMY2Date(@DAY, MONTH(DATEADD(m,1,@DATE_PP)), YEAR(DATEADD(m,1,@DATE_PP)))
		SET @DATE_PP = CASE WHEN COALESCE(@DATE_DOC,@DATE_PP) > @DATE_PP THEN @DATE_DOC ELSE @DATE_PP END	
		SET @DATE_PROV = CASE WHEN dbo.sa_get_option_by_code('SALARY_OPTIONS_OPT12') = 1 THEN @DATE_PP ELSE NULL END

		SET @varKSpD_ACC_LINK = COALESCE(@LINK_ACC,@varKSpD_ACC_LINK)
		SET @varKSpDOH_LINK = COALESCE(@LINK_DOH,@varKSpDOH_LINK)
		SET @varKSpD_LINK = COALESCE(@LINK_ORG,@varKSpD_LINK)
		---

			
		IF @varKSpD_ACC_LINK is null OR @varKSpD_ACC_LINK is null OR @varKSpD_LINK is null BEGIN
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
				'Заданы не все сведения о получателе в настройках вида вида удержания для НДФЛ!',
				'Укажите получателя, номер счета получателя, код дохода в настройках вида удержания меню: \СПРАВОЧНИКИ\Операции по зарплате\Виды удержаний.',
				'SALARY'
			GOTO DO_NEXT
		END



		IF @DATE_PROV is not null and not exists(Select * from admin_info Where @DATE_PROV BETWEEN BEGINDATE AND ENDDATE) BEGIN
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
				'Программа формирует дату проводки, равную дате платежки. Но эта дата не попадает в период редактирования!',
				'Укажите другую дату платежки, или отключите в общих настройках по зарплате опцию "В бух. документе автоматически ставить дату" проводки, или измените период редактирования.',
				'SALARY'
			GOTO DO_NEXT
		END
		
		SET @varKStrancount = @@TRANCOUNT
		SET IMPLICIT_TRANSACTIONS ON
		BEGIN TRAN 
		COMMIT TRAN

		-- определим максимальный номер 
		Set @NUM_PP = NULL
		IF @iCreatePP = 0		
			exec dbo.X_DOCUMENT_GET_NEXT_NUMBER 'DOCUMENTS_PAY', @NUM_PP output, @LINK_DEP
		ELSE
			exec dbo.X_DOCUMENT_GET_NEXT_NUMBER 'BB_ZAYAVKA_KR', @NUM_PP output, @LINK_DEP	

		--
		IF @KD_CODE_ACC LIKE '%.21' BEGIN
			
			SET @ACC_NAME = 'расчётный'
			select TOP 1 @varKSpS_ACC_LINK = T1.LINK from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE = 1			
			
		END
		ELSE BEGIN
			
			IF @Fin_Source = 1 BEGIN--бюджетная деятельность
			
				SET @ACC_NAME = 'лицевой'
				select TOP 1 @varKSpS_ACC_LINK = T1.LINK from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE = 2			
			
			END
			ELSE BEGIN
			
				SET @ACC_NAME = 'внебюджетный'			
				select TOP 1 @varKSpS_ACC_LINK = T1.LINK from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE = 4
			
				IF 	COALESCE(@varKSpS_ACC_LINK,0) = 0 BEGIN
				
					SET @ACC_NAME = @ACC_NAME + ' или лицевой'
					select TOP 1 @varKSpS_ACC_LINK = T1.LINK from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE = 2			
				
				END
				
			END	
			
		END
		
		IF COALESCE(@varKSpS_ACC_LINK,0) = 0 BEGIN
			ROLLBACK
			SET IMPLICIT_TRANSACTIONS OFF
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
				'В настройках реквизитов организации на вкладке "счета" не найден ' + @ACC_NAME + ' счет.',
				'Добавьте ' + @ACC_NAME + ' счет в настройках реквизитов организации на вкладке "счета".',
				'SALARY'
			GOTO DO_NEXT
		END				

		-- Сохраняем ПП 
		Set @LINK_PP = NULL		
		IF @iCreatePP = 0 
		BEGIN
			EXEC dbo.X_SAVE_DOCUMENTS_PAY @LINK_PP OUT, @NUM_PP, @DATE_PP, @DATE_PROV, @SUMMA_PP, '',
				@varKSpKIND, @varKSpS_LINK, @varKSpS_ACC_LINK, @varKSpD_LINK, @varKSpD_ACC_LINK,
				@SROK, @varKSpORDER, @varKSpPAYKIND, @varKSpREASON,
				@varKSpTARGETTEXT, @varKSpNDS, @varKSpBK_IN_TGT, @varKSpPRINT_KPP,
				@varKSpNDS_LINK, 'DOCUMENTS_PAY'

			EXEC dbo.X_SAVE_DOCUMENTS_PAY_ADD @LINK_PP OUT, @varKSpDOH_LINK, @varKSpSGU_LINK, @varKSpOKATO, @varKSpP_REASON,
				 @varKSpPERIOD, @varKSpTREBNUM, @DATE_PP, @varKSpZERODATE, @varKSpP_TYPE, @varKSpSTATUS, @UIN
		END		 
		ELSE
		BEGIN
			EXEC dbo.X_SAVE_DOCUMENTS_PAY @LINK_PP OUT, @NUM_PP, @DATE_PP, @DATE_PROV, @SUMMA_PP, '',
				@varKSpKIND, @varKSpS_LINK, @varKSpS_ACC_LINK, @varKSpD_LINK, @varKSpD_ACC_LINK,
				@SROK, @varKSpORDER, NULL, DEFAULT, 
				@varKSpTARGETTEXT, @varKSpNDS, @varKSpBK_IN_TGT, NULL,
				@varKSpNDS_LINK, 'BB_ZAYAVKA_KR'

			SET @NDS_SUM = ISNULL(@SUMMA_PP * ISNULL(@varKSpNDS,0) / 100, 0)

			EXEC dbo.X_SAVE_DOCUMENTS_PAY2 @LINK_PP, NULL, @BO_NUM, NULL, @AVANSE, @NDS_SUM, @SHORT

			EXEC dbo.X_SAVE_DOCUMENTS_PAY_ADD @LINK_PP, @varKSpDOH_LINK, @varKSpSGU_LINK, @varKSpOKATO, @varKSpP_REASON,
				 @varKSpPERIOD, @varKSpTREBNUM, @DATE_PP, @varKSpZERODATE, @varKSpP_TYPE, @varKSpSTATUS, @UIN			
					
		END		 

		IF @SUBDIV_HEAD IS NOT NULL
			SET @Osnovanie = @Osnovanie + LEFT(CASE WHEN LEN(@Osnovanie) > 0 THEN ', ' else '' end + LTRIM(RTRIM(COALESCE(@SUBDIV_NAME,''))), 200)

		INSERT INTO dbo.sdoc_vedom_rko (LINK_VEDOM, LINK_RKO, LINK_PAYS, COMMENT) 
		VALUES(@LINK_DOC, @LINK_PP, @link_pay, @Osnovanie  + ' ' + @OBJ_SNAME + ' №' + CONVERT(VARCHAR(8), @NUM_PP)  + ' от ' + CONVERT(VARCHAR(10),@DATE_PP,104))
		
		Set @order = 0

		SET @Cur = CURSOR FORWARD_ONLY
		FOR 
			SELECT 
				LINK_KBK = F.KBK,
				LINK_KAU = F.KAU,
				LINK_DOP_KL = F.DOP_KL,
				USER_ACC = F.USER_ACC,
				CODE_SFIN = F.CODE,
				SUMMA= SUM(CJ.SUMMA),
				PAYS_CODE = P.CODE
			FROM 
				dbo.CALCULATE_JURNAL CJ 
				INNER JOIN dbo.PAYS P ON (CJ.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC = 4)
				LEFT JOIN  dbo.SAL_SFIN F ON F.LINK = CJ.LINK_VKR
				LEFT JOIN #EMPL_INFO E ON E.LINK = CJ.LINK_EMPL
			WHERE 
				LINK_DOC = @LINK_DOC AND COALESCE(CJ.link_ekr,@LINK_EKR_DEFAULT) = @LINK_EKR AND F.SOURCE = @Fin_Source
				AND (@GROUP_BY_SUB = 1 AND SUBDIV_HEAD = @SUBDIV_HEAD OR @GROUP_BY_SUB = 0)
				AND CJ.LINK_VKR = @LINK_SFIN
			GROUP BY 
				F.KBK, F.KAU, F.SOURCE, F.DOP_KL, F.USER_ACC, F.CODE, P.CODE
			HAVING 
				SUM(CJ.SUMMA) >= 0
				
		OPEN @Cur
		FETCH NEXT FROM @Cur INTO @LINK_KBK, @LINK_KAU, @LINK_DOP_KL,  @USER_ACC, @CODE_SFIN, @SUM_PROV, @PAYS_CODE
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN

				IF REPLACE(LTRIM(RTRIM(ISNULL(@DT_CODE_ACC,''))),'.','') = '' BEGIN
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
						'Не указан счет кредита в настройках удержания '+COALESCE(LTRIM(RTRIM(@PAYS_CODE)),''),
						'Укажите в настройках удержания '+COALESCE(LTRIM(RTRIM(@PAYS_CODE)),'')+' счет кредита.',
						'SALARY'
					GOTO DO_NEXT			
				END

				---			
				SET @P1 = NULL
				exec X_UPDATE_G_PROV1 @P1 output, @LINK_PP, NULL, @Osnovanie, 1
		
				Set @order = @order + 1

				---
				SET @Account1 = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @DT_CODE_ACC) AND cUser = RTRIM(LTRIM(COALESCE(@USER_ACC,''))))
				SET @DT_FULL_CODE_ACC = @Fin_Source + '.' + @DT_CODE_ACC + CASE WHEN RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> '' THEN '/' + RTRIM(LTRIM(COALESCE(@USER_ACC,''))) ELSE '' END
				
				IF COALESCE(@Account1,0) = 0 BEGIN 
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
						'В плане счетов не найден счет ' + @DT_FULL_CODE_ACC,
						'Добавьте в план счетов счет ' + @DT_FULL_CODE_ACC,
						'SALARY'
					GOTO DO_NEXT
				END					
			
				---
				SET @ACC_CODE = (select top 1 A2.CODE from dbo.S_ACCOUNTS A1 inner join dbo.S_ACCOUNTS A2 on A1.link_self = A2.link
					WHERE A2.LINK = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @DT_CODE_ACC) ) and A2.cSource <> '')

				IF  RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) <> '' AND RTRIM(LTRIM(COALESCE(@USER_ACC,''))) = '' BEGIN
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
						'У источника финансирования ' + RTRIM(LTRIM(@CODE_SFIN)) + ' не указан пользовательский субсчет, однако у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' есть субсчета',
						'Укажите пользовательский субсчет, либо уберите в плане счетов субсчет у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' с помощью слияния',
						'SALARY'
					GOTO DO_NEXT
				END

				--		
				SET @KD_CODE_ACC = (SELECT TOP 1 CODE_ACC FROM DBO.SAL_NASTR_PROV WHERE TYPE_OPER = 1 AND TYPE_DEP = @BUH_TYPE AND TYPE_FUNC = @Fin_Source)

				IF REPLACE(LTRIM(RTRIM(ISNULL(@KD_CODE_ACC,''))),'.','') = '' BEGIN
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF		
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
						'Не задан счет для выбытия ср-в с лиц. либо расч. счета для вида организации ' 
						+ ISNULL((SELECT TOP 1 BT_NAME FROM DBO.DICTIONARY_BUH_TYPE WHERE BUH_TYPE = @BUH_TYPE),'')
						+ ' для вида деятельности ' + ISNULL((SELECT TOP 1 NAME FROM DBO.BB_FIN_SOURCE WHERE CODE = @Fin_Source),''),
						'В настройках всех режимов задачи выберите раздел "Настройка счетов для проводок по зарплате" и укажите требуемый счёт в настройке "Счет для выбытия ср-в с лиц. либо расч. счета".',
						'SALARY'
					GOTO DO_NEXT
				END	

				SET @Account2 = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @KD_CODE_ACC) AND cUser = RTRIM(LTRIM(COALESCE(@USER_ACC,''))))
				SET @KD_FULL_CODE_ACC = @Fin_Source + '.' + @KD_CODE_ACC + CASE WHEN RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> '' THEN '/' + RTRIM(LTRIM(COALESCE(@USER_ACC,''))) ELSE '' END

				IF COALESCE(@Account2,0) = 0 BEGIN 
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
						'В плане счетов не найден счет ' + @KD_FULL_CODE_ACC,
						'Добавьте в план счетов счет ' + @KD_FULL_CODE_ACC,
						'SALARY'
					GOTO DO_NEXT
				END
		
				---
				SET @ACC_CODE = (select top 1 A2.CODE from dbo.S_ACCOUNTS A1 inner join dbo.S_ACCOUNTS A2 on A1.link_self = A2.link
					WHERE A2.LINK = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @KD_CODE_ACC) ) and A2.cSource <> '')

				IF  RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) <> '' AND RTRIM(LTRIM(COALESCE(@USER_ACC,''))) = '' BEGIN
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
						'У источника финансирования ' + RTRIM(LTRIM(@CODE_SFIN)) + ' не указан пользовательский субсчет, однако у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' есть субсчета',
						'Укажите пользовательский субсчет, либо уберите в плане счетов субсчет у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' с помощью слияния',
						'SALARY'
					GOTO DO_NEXT
				END
				
				IF COALESCE(@Account1,0) > 0 AND COALESCE(@Account2,0) > 0 BEGIN
	
					SET @HOZ_OPER = (SELECT TOP 1 LINK FROM dbo.BX_BPROV_VIBOR_ECON_OPER(@Account1,@Account2))
					IF COALESCE(@HOZ_OPER,0) = 0 BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'Не найдено подходящей хоз. операции для проводки ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account1) + '-' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account2),
							'Вероятно в общих настройках по зарплате указан неправильно счет для выбытия бюдж. или внебюдж средств с лицевого либо расчетного счета',
							'SALARY'
						GOTO DO_NEXT
					END	
			
					set @P2 = null
					exec X_UPDATE_G_PROV2 @P2 output, @P1, NULL, @SUM_PROV, 0, 0, @Osnovanie, @HOZ_OPER, @order

					---
					SET @SGU = (SELECT TOP 1 LINK_SGU FROM S_ACCOUNTS_SGU SGU INNER JOIN KOSGU ON SGU.LINK_SGU = KOSGU.LINK WHERE DB_KR = 0 AND ACCOUNT = @Account1)
					IF EXISTS (SELECT p_KASSA FROM dbo.s_accounts WHERE LINK = @Account1 AND p_KASSA = 1)
						SET @SGU = @LINK_EKR
	
					IF COALESCE(@SGU,0) = 0 BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'У счета ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account1) + ' не задано СГУ',
							'Укажите СГУ в настройках счета в плане счетов',
							'SALARY'
						GOTO DO_NEXT
					END	
					exec X_UPDATE_G_PROV_AP @P2, 0, @Account1, @LINK_KBK, @LINK_EKR, @LINK_ORG /*Получатель*/, NULL, NULL, NULL, NULL, @LINK_KAU, @varKSpD_ACC_LINK /*Счет получателя*/, NULL, NULL, NULL, @LINK_DOP_KL, NULL, @SGU

					---
					SET @SGU = (SELECT TOP 1 LINK_SGU FROM S_ACCOUNTS_SGU SGU INNER JOIN KOSGU ON SGU.LINK_SGU = KOSGU.LINK WHERE DB_KR = 1 AND ACCOUNT = @Account2)
					IF EXISTS (SELECT p_KASSA FROM dbo.s_accounts WHERE LINK = @Account2 AND p_KASSA = 1)
						SET @SGU = @LINK_EKR
	
					IF COALESCE(@SGU,0) = 0 BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'У счета ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account2) + ' не задано СГУ',
							'Укажите СГУ в настройках счета в плане счетов',
							'SALARY'
						GOTO DO_NEXT
					END	
					exec X_UPDATE_G_PROV_AP @P2, 1, @Account2, @LINK_KBK, @LINK_EKR, @LINK_DEP /*отправитель*/, @SUBDIV_HEAD, NULL, NULL, NULL, @LINK_KAU, @varKSpS_ACC_LINK /*Счет отправителя*/, NULL, NULL, NULL, @LINK_DOP_KL, NULL, @SGU

				END
				
			END
			
			IF @iCreatePP = 1
				EXEC dbo.BB_ZAYAVKA_KR_CREATE_TABLE @LINK_PP
			
			FETCH NEXT FROM @Cur INTO @LINK_KBK, @LINK_KAU, @LINK_DOP_KL,  @USER_ACC, @CODE_SFIN, @SUM_PROV, @PAYS_CODE
		END
		
		CLOSE @Cur
		DEALLOCATE @Cur

		IF @@TRANCOUNT > @varKStrancount BEGIN
			COMMIT TRAN
			SET IMPLICIT_TRANSACTIONS OFF
		END

		---Если надо, то сформировать БО
		DECLARE @TestBO tinyint
		exec @TestBO = dbo.XD_TEST_FORM_BO @LINK_PP 
		IF @TestBO = 0
		BEGIN
			create table #tProtocol1(txt varchar(1000), NEW_ROW tinyint, nSTATUS tinyint, nTAB tinyint, ord int identity(1,1))

			insert into #tProtocol1 (txt, NEW_ROW, nSTATUS, nTAB) 
			Exec dbo.XD_FORM_BO @LINK_PP

			IF EXISTS (SELECT * FROM #tProtocol1 WHERE nSTATUS >=1 )
				INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
				select 'Обнаружены замечания при формирование БО:', CASE WHEN nSTATUS = 1 THEN 'Предупреждение!' ELSE 'Ошибка!' END + SPACE(1) + LEFT(txt,240), 'Устраните замечания!', 'SALARY'
				FROM #tProtocol1	WHERE nSTATUS >= 1
			
			DROP TABLE #tProtocol1
				
		END				

	END

	DO_NEXT:
	FETCH NEXT FROM @CURSOR_EKR INTO @DATE_PP, @Osnovanie, @Add_Text, @link_pay, @SUMMA_PP, @varKSpTARGETTEXT, @link_ekr, @DT_CODE_ACC, @Fin_Source, @LINK_ORG, @LINK_ACC, @LINK_DOH, @SUBDIV_HEAD, @SUBDIV_NAME, @LINK_SFIN
END

CLOSE @CURSOR_EKR
DEALLOCATE @CURSOR_EKR

Select LINK_RKO, COMMENT from dbo.sdoc_vedom_rko where LINK_VEDOM = @LINK_DOC

exec X_SALDO_CommitChanges

SET NOCOUNT OFF
Return 0
END

GO


GRANT EXECUTE ON dbo.[SA_CREATE_PP] TO PUBLIC

GO

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

GO

CREATE PROCEDURE [dbo].[SA_CREATE_PP_BY_VEDOM] 
			@LINK_PP INT OUTPUT,
			@LINK_VEDOM INT,
			@DATE_DOC DATETIME

AS BEGIN

---
Set @LINK_PP = Coalesce((SELECT TOP 1 R.LINK_RKO 
						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', 'BB_ZAYAVKA_KR')
							AND
							LINK_vedom = @LINK_VEDOM),0)

IF @LINK_PP <> 0 BEGIN

	Select R.LINK_RKO, R.COMMENT 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', 'BB_ZAYAVKA_KR') 
		AND
		R.LINK_VEDOM = @LINK_VEDOM
	
	RETURN 0
END

/*Очистить старые сообщения об ошибках*/
delete from SAL_WORNINGS WHERE SID = SUSER_SID() AND TASK ='SALARY'

DECLARE 
	@NUM_PP 	VARCHAR(25),
	@NUM_VEDOM	VARCHAR(20),
	@DATE_VEDOM  	DATETIME,
	@SUMMA_PP	numeric(19,2),
	@DEP_LINK	INT,
	@var_EKR_LINK_adv	INT,
	@REF_EMPL	INT,
	@Osnovanie VARCHAR(254),
	@Add_text VARCHAR(254),
	@link_pay INT,
	@TYP_PAYMENT TINYINT,
	@LINK_CARD INT,
	@varKSpTARGETTEXT     VARCHAR(1000),
	@Cur CURSOR, 
	@CUR_F CURSOR,
	@SUM_PROV NUMERIC(18,2), 
	@ORDER INT, 
	@Account1 INT, 
	@Account2 INT,	
	@HOZ_OPER INT, 
	@P1 FLOAT, 
	@P2 FLOAT, 
	@SGU INT,
	@LINK_KBK INT, 
	@LINK_KAU INT, 
	@LINK_DOP_KL INT, 
	@USER_ACC VARCHAR(4), 
	@CODE_SFIN VARCHAR(20), 
	@Fin_Source CHAR(1),
	@LINK_EKR INT,
	@MONTH_BASE INT,
	@YEAR_BASE INT,
	@ACC_CODE VARCHAR(20),
	@UIN VARCHAR(20)
	

DECLARE @varKStrancount INT, @varKSERROR as INT

CREATE TABLE #tmp (CODE VARCHAR(254), [TNAME] VARCHAR(254), LINK INT, [ANAME] VARCHAR(254), REF_LINK_B INT, REF_LINK_K INT)

DECLARE @iCreatePP INT
SELECT @iCreatePP = dbo.sa_get_option_by_code('XB_NASTR_ZAYAVKA_KR_OR_PP')

/*Определим шаблон с параметрами*/
DECLARE @SHABLON_LINK INT, @OBJ_SNAME VARCHAR(10)
IF @iCreatePP = 0
	SELECT	@SHABLON_LINK = dbo.sa_get_option_by_code('VEDOM_OPTIONS_OPT9'),
			@OBJ_SNAME = 'ПП'
ELSE
	SELECT	@SHABLON_LINK = dbo.sa_get_option_by_code('VEDOM_OPTIONS_OPT15'),
			@OBJ_SNAME = 'ЗКР'

---
IF NOT EXISTS (SELECT * FROM G_PROV WHERE LINK = @SHABLON_LINK)
BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление зарплаты на карточки ',
	'Не указан шаблон ' + @OBJ_SNAME + ' в настройках ведомости на выплату, или ' + @OBJ_SNAME + ' , указанная в качестве шаблона удалена.',
	'Укажите в настройках шаблон.',
	'SALARY'
	GOTO DO_END
END

---
DECLARE
	@varKSpKIND           CHAR(50),
	@varKSpS_LINK         INT,		
	@varKSpS_ACC_LINK     INT,
	@varKSpD_LINK         INT,		
	@varKSpD_ACC_LINK     INT,
	@varKSpORDER          CHAR(1),
	@varKSpPAYKIND        CHAR(5),
	@varKSpREASON         CHAR(5),
	@varKSpSBANK_LINK     INT,	
	@varKSpDBANK_LINK     INT,
	@varKSpNDSKIND        VARCHAR(100),
	@varKSpNDS            INT,
	@varKSpBK_IN_TGT      tinyint,
	@varKSpPRINT_KPP      tinyint,
	@varKSpNDS_LINK       INT,
	@varKSpDOG_LINK       INT,
	--
	@AVANSE TINYINT,
	@SHORT BIT,
	@BO_NUM char(10),
	@NDS_SUM NUMERIC(18,2)	


IF @iCreatePP = 0
	--Реквизиты ПП
	SELECT  @varKSpKIND = PP.KIND,
		@varKSpD_LINK = PP.D_LINK,
		@varKSpD_ACC_LINK = PP.D_ACC_LINK,
		@varKSpORDER = PP.[ORDER],
		@varKSpPAYKIND = PP.PAYKIND,
		@varKSpREASON = PP.REASON,
		@varKSpSBANK_LINK = PP.SBANK_LINK,		
		@varKSpDBANK_LINK = PP.DBANK_LINK,		
		@varKSpNDSKIND = PP.NDSKIND,	
		@varKSpNDS = PP.NDS,
		@varKSpBK_IN_TGT = PP.BK_IN_TGT,
		@varKSpPRINT_KPP = PP.PRINT_KPP,
		@varKSpNDS_LINK = PP.NDS_LINK,
		@varKSpDOG_LINK = PP.DOG_LINK,
		@varKSpTARGETTEXT = RTRIM(LTRIM(PP.TARGETTEXT)),
		@UIN = ISNULL(ppA.UIN_CODE,'')
	FROM dbo.DOCUMENTS_PAY PP
		LEFT JOIN dbo.DOCUMENTS_PAY_ADD PPA on PP.LINK = PPA.LINK
	WHERE PP.LINK = @SHABLON_LINK
ELSE
	SELECT  
		@AVANSE = ISNULL(AVANSE,0), --Авансовый платеж 
		@varKSpKIND = KIND, --Вид платежа
		@varKSpD_LINK = KOR_LINK, -- Получатель
		@varKSpD_ACC_LINK = KOR_ACC_LINK, --Номер счета получателя 
		@varKSpORDER = [ORDER], --Очередность платежа     
		@varKSpNDS = NDS, --Процент НДС  
		@varKSpNDS_LINK = NDS_LINK, --Шаблон НДС  
--		@SROK 		= SROK, --Срок платежа 
		@SHORT = ISNULL(SHORT,0), -- Сокращенная форма заявки
		@varKSpTARGETTEXT = RTRIM(LTRIM(TARGETTEXT)), --Назначение платежа,
		@BO_NUM = ISNULL(BO_NUM,''),
		@UIN = ISNULL(UIN_CODE,'')
	FROM dbo.BB_ZAYAVKA_KR WHERE LINK = @SHABLON_LINK		

-- данные из ведомости
SELECT 	
	@DATE_VEDOM = CASE WHEN dbo.SA_GET_OPTION_BY_CODE('VEDOM_OPTIONS_OPT11') = 1 THEN dbo.DateEndOfMonth( dbo.ConvertDMY2Date(1, MONTH_BASE, YEAR_BASE)) ELSE [DATE] END,
	@NUM_VEDOM = NUMBER,
	@MONTH_BASE = MONTH_BASE,
	@YEAR_BASE = YEAR_BASE,
	@DEP_LINK=LINK_DEP,
	@REF_EMPL=REF_EMPL,
	@TYP_PAYMENT = TYP_PAYMENT,
	@Add_Text = 'Ведомость №' + RTRIM(LTRIM(COALESCE(NUMBER,''))) + ' от ' + COALESCE(convert(VARCHAR(10),[DATE], 104),''),
	@link_pay = REF_PAY,
	@LINK_CARD = CARD_LINK,
	@varKSpTARGETTEXT = @varKSpTARGETTEXT + case when dbo.sa_get_option_by_code('SALARY_OPTIONS_OPT9') = 1 then CASE WHEN LEN(@varKSpTARGETTEXT) > 0 THEN ', ' else '' end + [NAME_PAY] ELSE '' END 
FROM 
	(
	SELECT [DATE], MONTH_BASE, YEAR_BASE, NUMBER, LINK_DEP, REF_EMPL, TYP_PAYMENT, REF_PAY, CARD_LINK, NAME_PAY FROM dbo.DOCUMENTS_DED_PR V1 WHERE V1.LINK = @LINK_VEDOM
	UNION ALL
	SELECT [DATE], MONTH_BASE, YEAR_BASE, NUMBER, LINK_DEP, REF_EMPL, TYP_PAYMENT, REF_PAY, CARD_LINK, NAME_PAY FROM dbo.DOCUMENTS_DED_PR_DGH V2 WHERE V2.LINK = @LINK_VEDOM
	) V

--
SET @DATE_VEDOM = CASE WHEN COALESCE(@DATE_DOC,@DATE_VEDOM) > @DATE_VEDOM THEN @DATE_DOC ELSE @DATE_VEDOM END	

DECLARE	@DATE_PROV datetime
SET @DATE_PROV = CASE WHEN dbo.sa_get_option_by_code('SALARY_OPTIONS_OPT12') = 1 THEN @DATE_VEDOM ELSE NULL END

--Проверка рабочего периода
IF @DATE_PROV is not null and not exists(Select * from admin_info Where @DATE_PROV BETWEEN BEGINDATE AND ENDDATE)
BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление зарплаты на карточки по документу ' + @Add_Text,
		'Программа формирует дату проводки, равную дате платежки. Но эта дата не попадает в период редактирования!',
		'Отключите в общих настройках по зарплате опцию "В бух. документе автоматически ставить дату" проводки или измените период редактирования.',
		'SALARY'
	GOTO DO_END
END


--Платежка только если указана пластиковая карточка
IF COALESCE(@LINK_CARD,0) = 0
	RETURN 0

-- определим организацию и счет по умолчанию
SET @varKSpS_LINK = @DEP_LINK
INSERT INTO #tmp 
EXEC dbo.XD_DEP_ACCOUNT @varKSpS_ACC_LINK OUTPUT, @varKSpS_LINK, DEFAULT

IF NOT EXISTS (SELECT T1.LINK from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE IN (1,2,4) ) BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление зарплаты на карточки ',
	'Не указаны счета в настройках организации.',
	'Требуется указать счета в настройках организации.',
	'SALARY'
	RETURN 0		
END

----
DECLARE @CODE_OBJECT VARCHAR(254)
SET @CODE_OBJECT = (SELECT O.CODE FROM SDOC D INNER JOIN dbo.S_OBJECTS O ON D.OBJECT = O.LINK WHERE D.LINK = @LINK_VEDOM)

DECLARE @LINK_EKR_DEFAULT INT
SELECT @LINK_EKR_DEFAULT = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = CASE WHEN RTRIM(LTRIM(@CODE_OBJECT)) = 'DOCUMENTS_DED_PAYROLL' THEN '211' ELSE '226' END

---
Declare @ACC_304_03 VARCHAR(10)
SET @ACC_304_03 = (SELECT TOP 1 RTRIM(LTRIM(VALUE)) FROM dbo.S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SALARY_OPTIONS_OPT2'))) AND SID IS NULL)

IF RTRIM(LTRIM(COALESCE(@ACC_304_03,''))) IN ('','.') BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление зарплаты на карточки ',
		'Не указан счет для расчетов по удержаниям в общих настройках по зарплате.',
		'Укажите счет для расчетов по удержаниям в общих настройках по зарплате.',
		'SALARY'
	RETURN 0		
END	

---
DECLARE @LINK_ORG int, @LINK_ACC int
DECLARE @KD_CODE_ACC VARCHAR(6), @KD_FULL_CODE_ACC VARCHAR(13), @ACC_NAME VARCHAR(15)

DECLARE @BUH_TYPE TINYINT
SET @BUH_TYPE = ISNULL((SELECT BUH_TYPE FROM DBO.DEPARTMENTS WHERE LINK = @DEP_LINK),0)

DECLARE @WORKMODE157N INT
SET @WORKMODE157N = ISNULL((SELECT dbo.XK_GET_NASTR_INT ('XK_WORKMODE157N')),0)
--Если не выполнен переход, то считаем, что тип организации не определён!
SET @BUH_TYPE = CASE WHEN @WORKMODE157N = 0 THEN 0 ELSE @BUH_TYPE END

--IF @BUH_TYPE = 0 BEGIN
--	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
--	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление зарплаты на карточки ',
--		'Не определён вид государственного учреждения.',
--		'В реквизитах текущей организации установите реквизит "Вид государственного учреждения".',
--		'SALARY'
--	RETURN 0		
--END

IF NOT EXISTS (SELECT * FROM DBO.SAL_NASTR_PROV WHERE TYPE_OPER = 1 AND TYPE_DEP = @BUH_TYPE) BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление зарплаты на карточки ',
		'Не определён счет для выбытия ср-в с лиц. либо расч. счета.',
		'В настройках формирования проводок по зарплате укажите счёта в справочнике "Счета для выбытия ср-в с лиц. либо расч. счета" для данного вида гос. учреждения".',
		'SALARY'
	RETURN 0		
END

SET @CUR_F = CURSOR FORWARD_ONLY
FOR 
	SELECT F.KBK, COALESCE(CAST (F.SOURCE as CHAR(1)),'') ,
		T.LINK_ORG,
		T.LINK_ACC
	FROM dbo.CALCULATE_JURNAL CJ
		LEFT JOIN  dbo.SAL_SFIN F ON F.LINK = CJ.LINK_VKR
		LEFT JOIN TAX2_APP T on CJ.LINK_PAYS = T.link_up
	WHERE CJ.LINK_DOC = @LINK_VEDOM
	GROUP BY F.KBK, F.SOURCE, T.LINK_ORG, T.LINK_ACC
	HAVING SUM(CJ.SUMMA) <> 0
	ORDER BY F.KBK
OPEN @CUR_F
FETCH NEXT FROM @CUR_F INTO @LINK_KBK, @Fin_Source, @LINK_ORG, @LINK_ACC
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN	--Формирование расходников для каждого КБК по отдельности

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

		IF @varKSERROR <> 0
			RETURN @varKSERROR


		IF COALESCE(@LINK_ORG,0) = 0 BEGIN 
			ROLLBACK
			SET IMPLICIT_TRANSACTIONS OFF
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформированы проводки на перечисление зарплаты на карточки',
				'В настройках удержания, указанного в ведомости не указан получатель',
				'Укажите получателя в настройках удержания ',
				'SALARY'
			GOTO DO_NEXT
		END

		IF COALESCE(@LINK_ACC,0) = 0 BEGIN 
			ROLLBACK
			SET IMPLICIT_TRANSACTIONS OFF
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформированы проводки на перечисление зарплаты на карточки',
				'В настройках удержания, указанного в ведомости не указан счет получателя',
				'Укажите счет получателя в настройках удержания ',
				'SALARY'
			GOTO DO_NEXT
		END

		--------------------
		SELECT TOP 1 @Osnovanie = (case COALESCE(@TYP_PAYMENT,0) WHEN 1 THEN 'Перечисление з/пл' WHEN 2 THEN 'Перечисление аванса' ELSE 'Перечисление межрасч. выпл.' end) +
			' за ' + coalesce((SELECT TOP 1 MON FROM dbo.months WHERE NUM = @MONTH_BASE),'') + ',' + CONVERT(VARCHAR(4),coalesce(@YEAR_BASE,0)) + 'г.' +
			 ' по КБК ' + RTRIM(LTRIM(COALESCE(KBK.[CODE],''))) + ' ' + ISNULL((SELECT TOP 1 LTRIM(RTRIM(NAME)) FROM DBO.BB_FIN_SOURCE WHERE CODE = @Fin_Source),'')  + ', Вед.№' + RTRIM(LTRIM(COALESCE(@NUM_VEDOM,''))) + ' от ' + COALESCE(convert(VARCHAR(10),@DATE_VEDOM, 104),'')
		FROM dbo.KL_KBK KBK WHERE KBK.LINK = @LINK_KBK
		
		SET @ORDER = 0

		-- определим максимальный номер
		Set @NUM_PP = NULL
		IF @iCreatePP = 0		
			exec dbo.X_DOCUMENT_GET_NEXT_NUMBER 'DOCUMENTS_PAY', @NUM_PP output, @DEP_LINK
		ELSE
			exec dbo.X_DOCUMENT_GET_NEXT_NUMBER 'BB_ZAYAVKA_KR', @NUM_PP output, @DEP_LINK			

		--		
		SET @KD_CODE_ACC = (SELECT TOP 1 CODE_ACC FROM DBO.SAL_NASTR_PROV WHERE TYPE_OPER = 1 AND TYPE_DEP = @BUH_TYPE AND TYPE_FUNC = @Fin_Source)

		IF REPLACE(LTRIM(RTRIM(ISNULL(@KD_CODE_ACC,''))),'.','') = '' BEGIN
			ROLLBACK
			SET IMPLICIT_TRANSACTIONS OFF		
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление зарплаты на карточки ',
				'Не задан счет для выбытия ср-в с лиц. либо расч. счета для вида организации ' 
				+ ISNULL((SELECT TOP 1 BT_NAME FROM DBO.DICTIONARY_BUH_TYPE WHERE BUH_TYPE = @BUH_TYPE),'')
				+ ' для вида деятельности ' + ISNULL((SELECT TOP 1 NAME FROM DBO.BB_FIN_SOURCE WHERE CODE = @Fin_Source),''),
				'В настройках всех режимов задачи выберите раздел "Настройка счетов для проводок по зарплате" и укажите требуемый счёт в настройке "Счет для выбытия ср-в с лиц. либо расч. счета".',
				'SALARY'
			RETURN 0		
		END		

		SET @Account2 = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @KD_CODE_ACC) AND cUser = RTRIM(LTRIM(COALESCE(@USER_ACC,''))))
		SET @KD_FULL_CODE_ACC = @Fin_Source + '.' + @KD_CODE_ACC + CASE WHEN RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> '' THEN '/' + RTRIM(LTRIM(COALESCE(@USER_ACC,''))) ELSE '' END

		IF COALESCE(@Account2,0) = 0 BEGIN 
			ROLLBACK
			SET IMPLICIT_TRANSACTIONS OFF
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформированы проводки на перечисление зарплаты на карточки',
				'В плане счетов не найден счет ' + @KD_FULL_CODE_ACC,
				'Добавьте в план счетов счет ' + @KD_FULL_CODE_ACC,
				'SALARY'
			GOTO DO_NEXT
		END

		IF @KD_CODE_ACC LIKE '%.21' BEGIN
			
			SET @ACC_NAME = 'расчётный'
			
			IF NOT EXISTS (SELECT * from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE = 1 AND @varKSpS_ACC_LINK = T1.LINK)
				select TOP 1 @varKSpS_ACC_LINK = T1.LINK from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE = 1
			
		END
		ELSE BEGIN
			
			IF @Fin_Source = 1 BEGIN--бюджетная деятельность
			
				SET @ACC_NAME = 'лицевой'

				IF NOT EXISTS (SELECT * from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE = 2 AND @varKSpS_ACC_LINK = T1.LINK)
					select TOP 1 @varKSpS_ACC_LINK = T1.LINK from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE = 2			
			
			END
			ELSE BEGIN
			
				SET @ACC_NAME = 'внебюджетный'

				IF NOT EXISTS (SELECT * from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE = 4 AND @varKSpS_ACC_LINK = T1.LINK)
					select TOP 1 @varKSpS_ACC_LINK = T1.LINK from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE = 4
			
				IF 	COALESCE(@varKSpS_ACC_LINK,0) = 0 BEGIN
				
					SET @ACC_NAME = @ACC_NAME + ' или лицевой'

					IF NOT EXISTS (SELECT * from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE = 2 AND @varKSpS_ACC_LINK = T1.LINK)
						select TOP 1 @varKSpS_ACC_LINK = T1.LINK from #tmp T1 INNER JOIN dbo.DEPARTMENT_ACCOUNTS T2 ON T1.LINK = T2.LINK WHERE TYPE = 2			
				
				END
				
			END	
			
		END
		
		IF COALESCE(@varKSpS_ACC_LINK,0) = 0 BEGIN
			ROLLBACK
			SET IMPLICIT_TRANSACTIONS OFF
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформированы проводки на перечисление зарплаты на карточки',
				'В настройках реквизитов организации на вкладке "счета" не найден ' + @ACC_NAME + ' счет.',
				'Добавьте ' + @ACC_NAME + ' счет в настройках реквизитов организации на вкладке "счета".',
				'SALARY'
			GOTO DO_NEXT
		END		

		-- Сохраняем ПП 
		SET @LINK_PP = NULL
		SET @varKSpD_ACC_LINK = @LINK_ACC--COALESCE(@LINK_ACC,@varKSpD_ACC_LINK)
		SET @varKSpD_LINK = @LINK_ORG--COALESCE(@LINK_ORG,@varKSpD_LINK)
		
		IF @iCreatePP = 0 
		BEGIN
			EXEC dbo.X_SAVE_DOCUMENTS_PAY @LINK_PP OUT, @NUM_PP, @DATE_VEDOM, @DATE_PROV, 0, '',
				@varKSpKIND, @varKSpS_LINK, @varKSpS_ACC_LINK, @varKSpD_LINK, @varKSpD_ACC_LINK,
				@DATE_VEDOM, @varKSpORDER, @varKSpPAYKIND, @varKSpREASON,
				@varKSpTARGETTEXT, @varKSpNDS, @varKSpBK_IN_TGT, @varKSpPRINT_KPP,
				@varKSpNDS_LINK, 'DOCUMENTS_PAY'
		END		 
		ELSE
		BEGIN
			EXEC dbo.X_SAVE_DOCUMENTS_PAY @LINK_PP OUT, @NUM_PP, @DATE_VEDOM, @DATE_PROV, 0, '',
				@varKSpKIND, @varKSpS_LINK, @varKSpS_ACC_LINK, @varKSpD_LINK, @varKSpD_ACC_LINK,
				@DATE_VEDOM, @varKSpORDER, NULL, DEFAULT, 
				@varKSpTARGETTEXT, @varKSpNDS, @varKSpBK_IN_TGT, NULL,
				@varKSpNDS_LINK, 'BB_ZAYAVKA_KR'

			SET @NDS_SUM = ISNULL(@SUMMA_PP * ISNULL(@varKSpNDS,0) / 100 ,0)

			EXEC dbo.X_SAVE_DOCUMENTS_PAY2 @LINK_PP, NULL, @BO_NUM, NULL, @AVANSE, @NDS_SUM, @SHORT

		END					

		INSERT INTO dbo.sdoc_vedom_rko (LINK_VEDOM, LINK_RKO, COMMENT) VALUES(@LINK_VEDOM, @LINK_PP, @Osnovanie)

		SET @Cur = CURSOR FORWARD_ONLY
		FOR 
			-- Данные для проводок
			SELECT 	COALESCE(JC.LINK_EKR,@LINK_EKR_DEFAULT), 
				LINK_KAU = F.KAU,
				LINK_DOP_KL = F.DOP_KL,
				USER_ACC = F.USER_ACC,
				CODE_SFIN = F.CODE,
				SUMMA= SUM(JC.SUMMA) 
			FROM	
				dbo.CALCULATE_JURNAL JC INNER JOIN dbo.SAL_SFIN F ON F.LINK = JC.LINK_VKR
			WHERE   
				JC.LINK_DOC = @LINK_VEDOM AND F.KBK = @LINK_KBK AND COALESCE(CAST (F.SOURCE as CHAR(1)),'') = @Fin_Source
			GROUP BY 
				JC.LINK_EKR, JC.LINK_PAYS, F.KBK, F.KAU, F.DOP_KL, F.USER_ACC, F.CODE
			HAVING 
				SUM(JC.SUMMA) <> 0

		OPEN @Cur
		FETCH NEXT FROM @Cur INTO @LINK_EKR, @LINK_KAU, @LINK_DOP_KL, @USER_ACC, @CODE_SFIN, @SUM_PROV
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN
				IF COALESCE(@SUM_PROV,0) >= 0 BEGIN
						
					SET @P1 = NULL

					exec X_UPDATE_G_PROV1 @P1 output, @LINK_PP, NULL, @Osnovanie, 1
			
					Set @ORDER = @ORDER + 1
					--Найдем счет с пользовательским субсчетом

					IF RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> ''
						Set @Account1 = (SELECT TOP 1 link FROM dbo.S_ACCOUNTS WHERE cSource = RTRIM(LTRIM(@Fin_Source)) and cSinth = RTRIM(dbo.SA_GET_WORD_NUM(@ACC_304_03,1,'.')) and cAnalit = RTRIM(dbo.SA_GET_WORD_NUM(@ACC_304_03,2,'.')) AND cUser = RTRIM(LTRIM(COALESCE(@USER_ACC,''))))
					ELSE 
						Set @Account1 = (SELECT TOP 1 link FROM dbo.S_ACCOUNTS WHERE cSource = RTRIM(LTRIM(@Fin_Source)) and cSinth = RTRIM(dbo.SA_GET_WORD_NUM(@ACC_304_03,1,'.')) and cAnalit = RTRIM(dbo.SA_GET_WORD_NUM(@ACC_304_03,2,'.')) )

					--Если не нашли, то ошибка!
					IF COALESCE(@Account1,0) = 0 BEGIN 
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'В плане счетов не найден счет ' + @Fin_Source + '.' + RTRIM(dbo.SA_GET_WORD_NUM(@ACC_304_03,1,'.')) + '.' + RTRIM(dbo.SA_GET_WORD_NUM(@ACC_304_03,2,'.')) + + CASE WHEN RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> '' THEN '/' + RTRIM(LTRIM(COALESCE(@USER_ACC,''))) else '' END,
							'Добавьте в план счетов такой счет.',
							'SALARY'
						GOTO DO_NEXT
					END

					---
					SET @ACC_CODE = (select top 1 A2.CODE from dbo.S_ACCOUNTS A1 inner join dbo.S_ACCOUNTS A2 on A1.link_self = A2.link
						WHERE A2.LINK = @Account1 and A2.cSource <> '')

					IF  RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) <> '' AND RTRIM(LTRIM(COALESCE(@USER_ACC,''))) = '' BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'У источника финансирования ' + RTRIM(LTRIM(@CODE_SFIN)) + ' не указан пользовательский субсчет, однако у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' есть субсчета',
							'Укажите пользовательский субсчет, либо уберите в плане счетов субсчет у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' с помощью слияния',
							'SALARY'
						GOTO DO_NEXT
					END

					---
					SET @ACC_CODE = (select top 1 A2.CODE from dbo.S_ACCOUNTS A1 inner join dbo.S_ACCOUNTS A2 on A1.link_self = A2.link
						WHERE A2.LINK = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @KD_CODE_ACC) ) and A2.cSource <> '')

					IF  RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) <> '' AND RTRIM(LTRIM(COALESCE(@USER_ACC,''))) = '' BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'У источника финансирования ' + RTRIM(LTRIM(@CODE_SFIN)) + ' не указан пользовательский субсчет, однако у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' есть субсчета',
							'Укажите пользовательский субсчет, либо уберите в плане счетов субсчет у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' с помощью слияния',
							'SALARY'
						GOTO DO_NEXT
					END
	
					IF COALESCE(@Account1,0) > 0 AND COALESCE(@Account2,0) > 0 BEGIN

						SET @HOZ_OPER = (SELECT TOP 1 LINK FROM dbo.BX_BPROV_VIBOR_ECON_OPER(@Account1,@Account2))
						IF COALESCE(@HOZ_OPER,0) = 0 BEGIN
							ROLLBACK
							SET IMPLICIT_TRANSACTIONS OFF
							INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
								'Не найдено подходящей хоз. операции для проводки ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account1) + '-' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account2),
								'Вероятно в общих настройках по зарплате указан неправильно счет для выбытия бюдж. или внебюдж средств с лицевого либо расчетного счета',
								'SALARY'
							GOTO DO_NEXT
						END	
				
						set @P2 = null
						exec X_UPDATE_G_PROV2 @P2 output, @P1, NULL, @SUM_PROV, 0, 0, @Osnovanie, @HOZ_OPER, @ORDER
						
						UPDATE dbo.G_PROV
						SET SUMMA = SUMMA + @SUM_PROV
						WHERE LINK = @LINK_PP
			
						SET @SGU = (SELECT TOP 1 LINK_SGU FROM S_ACCOUNTS_SGU SGU INNER JOIN KOSGU ON SGU.LINK_SGU = KOSGU.LINK WHERE DB_KR = 0 AND ACCOUNT = @Account1)
						IF EXISTS (SELECT p_KASSA FROM dbo.s_accounts WHERE LINK = @Account1 AND p_KASSA = 1)
							SET @SGU = @LINK_EKR
		
						IF COALESCE(@SGU,0) = 0 BEGIN
							ROLLBACK
							SET IMPLICIT_TRANSACTIONS OFF
							INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
								'У счета ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account1) + ' не задано СГУ',
								'Укажите СГУ в настройках счета в плане счетов',
								'SALARY'
							GOTO DO_NEXT
						END	
						exec X_UPDATE_G_PROV_AP @P2, 0, @Account1, @LINK_KBK, @LINK_EKR, @varKSpD_LINK, NULL, NULL, NULL, NULL, @LINK_KAU, @varKSpD_ACC_LINK, NULL, NULL, NULL, @LINK_DOP_KL, NULL, @SGU
		
						SET @SGU = (SELECT TOP 1 LINK_SGU FROM S_ACCOUNTS_SGU SGU INNER JOIN KOSGU ON SGU.LINK_SGU = KOSGU.LINK WHERE DB_KR = 1 AND ACCOUNT = @Account2)
						IF EXISTS (SELECT p_KASSA FROM dbo.s_accounts WHERE LINK = @Account2 AND p_KASSA = 1)
							SET @SGU = @LINK_EKR
		
						IF COALESCE(@SGU,0) = 0 BEGIN
							ROLLBACK
							SET IMPLICIT_TRANSACTIONS OFF
							INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
								'У счета ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account2) + ' не задано СГУ',
								'Укажите СГУ в настройках счета в плане счетов',
								'SALARY'
							GOTO DO_NEXT
						END	
						exec X_UPDATE_G_PROV_AP @P2, 1, @Account2, @LINK_KBK, @LINK_EKR, @DEP_LINK, NULL, NULL, NULL, NULL, @LINK_KAU, @varKSpS_ACC_LINK, NULL, NULL, NULL, @LINK_DOP_KL, NULL, @SGU
					END
		
				END
			END

			IF @iCreatePP = 1
				EXEC dbo.BB_ZAYAVKA_KR_CREATE_TABLE @LINK_PP
			
			FETCH NEXT FROM @Cur INTO @LINK_EKR, @LINK_KAU, @LINK_DOP_KL, @USER_ACC, @CODE_SFIN, @SUM_PROV
		END
		
		CLOSE @Cur
		DEALLOCATE @Cur

		IF @@TRANCOUNT > @varKStrancount BEGIN
			COMMIT TRAN
			SET IMPLICIT_TRANSACTIONS OFF
		END
		---Если надо, то сформировать БО
		DECLARE @TestBO tinyint
		exec @TestBO = dbo.XD_TEST_FORM_BO @LINK_PP 

		IF @TestBO = 0
		BEGIN
			create table #tProtocol1(txt varchar(1000), NEW_ROW tinyint, nSTATUS tinyint, nTAB tinyint, ord int identity(1,1))

			insert into #tProtocol1 (txt, NEW_ROW, nSTATUS, nTAB) 
			Exec dbo.XD_FORM_BO @LINK_PP

			IF EXISTS (SELECT * FROM #tProtocol1 WHERE nSTATUS >=1 )
				INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
				select 'Обнаружены замечания при формирование БО:', CASE WHEN nSTATUS = 1 THEN 'Предупреждение!' ELSE 'Ошибка!' END + SPACE(1) + LEFT(txt,240), 'Устраните замечания!', 'SALARY'
				FROM #tProtocol1	WHERE nSTATUS >= 1
			
			DROP TABLE #tProtocol1
				
		END				

	END

	DO_NEXT:

	FETCH NEXT FROM @CUR_F INTO @LINK_KBK, @Fin_Source, @LINK_ORG, @LINK_ACC
END

CLOSE @CUR_F
DEALLOCATE @CUR_F

exec X_SALDO_CommitChanges

DO_END:

Select LINK_RKO, COMMENT from dbo.sdoc_vedom_rko where LINK_VEDOM = @LINK_VEDOM

Return 0
END



GO


GRANT EXECUTE ON dbo.[SA_CREATE_PP_BY_VEDOM] TO PUBLIC

GO

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

GO

CREATE   PROCEDURE [dbo].SA_SZV4_PACHKA_CALC_Buffer3 (@BufferCode varchar(10), @link int, @Year int, @Month tinyint) 
AS

DECLARE @SQL VARCHAR(1000)

SET @SQL = '
delete from dbo.Buffer
where RTRIM(LTRIM(ID)) = RTRIM(LTRIM( ''' + @BufferCode + ''' ))
	and link IN (select S.link_pers from dbo.SZV4_SVEDENIA S where S.link_up = ' + CONVERT(VARCHAR(20),@LINK) + ')'
--EXEC (@SQL)	

CREATE TABLE #PERSON (LINK INT)	

SET @SQL = '
INSERT INTO #PERSON (LINK)
SELECT DISTINCT LINK FROM dbo.Buffer WHERE RTRIM(LTRIM(ID)) = RTRIM(LTRIM(''' + @BufferCode + '''))'
EXEC (@SQL)	

declare @DEP_LINK int
exec dbo.xd_whats_zb @DEP_LINK output

DECLARE @PER TINYINT, @MONTH_END TINYINT, @MONTH_BEG TINYINT, @VID_KOR TINYINT 

SELECT @VID_KOR = VID_KOR
FROM dbo.SZV4_PACHKA WHERE LINK = @link

IF @VID_KOR = 2
begin  
	SELECT @Year = @Year, @PER = PER_EDT, @MONTH_END = @Month
	FROM dbo.SZV4_PACHKA WHERE LINK = @link
end 
else 
begin
	SELECT @Year = YEAR_BEGIN, @PER = PER, @MONTH_END = MONTH_END
	FROM dbo.SZV4_PACHKA WHERE LINK = @link
end 
DECLARE @PeriodBegin datetime, @PeriodEnd datetime

SET @MONTH_BEG = (CASE @PER WHEN 1 THEN 1 WHEN 2 THEN 4 WHEN 3 THEN 7 WHEN 4 THEN 10 END)
SET @MONTH_END = (CASE WHEN @MONTH_END < (@MONTH_BEG+3-1) THEN @MONTH_END ELSE (@MONTH_BEG+3-1) END)

SELECT @PeriodBegin = dbo.ConvertDMY2Date(1,@MONTH_BEG,@Year), @PeriodEnd = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@MONTH_END,@Year))

--ВЫДЕЛЕНИЕ КАТЕГОРИЙ ФИЗ.ЛИЦ
--ИНВАЛИДЫ
DECLARE @LINK_OZOI INT
SET @LINK_OZOI = ISNULL((SELECT TOP 1 LINK FROM dbo.SA_PFR_KATEG WHERE LINK2 = 3 AND @Year BETWEEN YBEG AND YEND),1)

------	у кого была инвалидность в заданном периоде
SELECT PERS_LINK, DATE_BEGIN = MIN(ISNULL(I.DATE_BEGIN,@PeriodBegin)), DATE_END = MAX(ISNULL(I.DATE_END,@PeriodEnd))
INTO #PERS_INV
FROM dbo.PERS_INVALID I
WHERE ISNULL(I.DATE_BEGIN,@PeriodBegin) <= @PeriodEnd AND ISNULL(I.DATE_END,@PeriodEnd) >= @PeriodBegin
GROUP BY PERS_LINK

--forma в отчётности за 2013 год содержит тип договора (1 трудовой, 2 ГПХ)
insert into dbo.SZV4_SVEDENIA (link_up, orders, forma, link_pers, sum_doh, sum_str, sum_nak, sum_dop, dper_vn_m, dper_vn_d,dper_oz_m, dper_oz_d, isum_str, isum_nak, LINK_KATEG, DATE_BEG, DATE_END) 
Select distinct @link, 0, DOG, B.link, 0, 0, 0, 0, 
	DIS_M = 0,
	DIS_D = 0,
	VAC_M = 0,
	VAC_D = 0,
	0,0,
	@LINK_OZOI,
	CASE WHEN ISNULL(I.DATE_BEGIN,@PeriodBegin) < @PeriodBegin THEN @PeriodBegin ELSE ISNULL(I.DATE_BEGIN,@PeriodBegin) END,
	CASE WHEN ISNULL(I.DATE_END,@PeriodEnd) > @PeriodEnd THEN @PeriodEnd ELSE ISNULL(I.DATE_END,@PeriodEnd) END
from 
	(	SELECT B.LINK, DOG = 1 
		FROM 
			#PERSON B
			INNER JOIN dbo.EMPL E ON E.pers_link = B.LINK AND E.DEP_LINK = @DEP_LINK
		UNION 
		SELECT B.LINK, DOG = 2 
		FROM 
			#PERSON B
			INNER JOIN dbo.SALARY_REESTR_DGH DGH ON DGH.PERS_LINK = B.LINK AND DGH.DEP_LINK = @DEP_LINK
	) B
	INNER JOIN #PERS_INV I ON I.PERS_LINK = B.LINK AND ISNULL(I.DATE_BEGIN,@PeriodBegin) <= @PeriodEnd AND ISNULL(I.DATE_END,@PeriodEnd) >= @PeriodBegin		

----ОБЩИЕ
DECLARE @LINK_NR INT
SET @LINK_NR = ISNULL((SELECT TOP 1 LINK FROM dbo.SA_PFR_KATEG WHERE LINK2 = 1 AND @Year BETWEEN YBEG AND YEND),1)

--forma в отчётности за 2013 год содержит тип договора (1 трудовой, 2 ГПХ)	
insert into dbo.SZV4_SVEDENIA (link_up, orders, forma, link_pers, sum_doh, sum_str, sum_nak, sum_dop, dper_vn_m, dper_vn_d,dper_oz_m, dper_oz_d, isum_str, isum_nak, LINK_KATEG, DATE_BEG, DATE_END) 
Select distinct @link, 0, DOG, B.link, 0, 0, 0, 0, 
	DIS_M = 0,
	DIS_D = 0,
	VAC_M = 0,
	VAC_D = 0,
	0,0,
	@LINK_NR,
	CASE WHEN I.PERS_LINK IS NULL OR @PeriodBegin < CASE WHEN ISNULL(I.DATE_BEGIN,@PeriodBegin) < @PeriodBegin THEN @PeriodBegin ELSE ISNULL(I.DATE_BEGIN,@PeriodBegin) END
		THEN @PeriodBegin 
		ELSE CASE WHEN ISNULL(I.DATE_END,@PeriodEnd) > @PeriodEnd THEN @PeriodEnd ELSE ISNULL(I.DATE_END,@PeriodEnd) END + 1
	END,
	CASE WHEN I.PERS_LINK IS NULL OR @PeriodEnd > CASE WHEN ISNULL(I.DATE_END,@PeriodEnd) > @PeriodEnd THEN @PeriodEnd ELSE ISNULL(I.DATE_END,@PeriodEnd) END
		THEN @PeriodEnd
		ELSE CASE WHEN ISNULL(I.DATE_BEGIN,@PeriodBegin) < @PeriodBegin THEN @PeriodBegin ELSE ISNULL(I.DATE_BEGIN,@PeriodBegin) END - 1
	END
from 
	(	
		SELECT B.LINK, DOG = 1 
		FROM 
			#PERSON B
			INNER JOIN dbo.EMPL E ON E.pers_link = B.LINK AND E.DEP_LINK = @DEP_LINK
		UNION 
		SELECT B.LINK, DOG = 2
		FROM 
			#PERSON B
			INNER JOIN dbo.SALARY_REESTR_DGH DGH ON DGH.PERS_LINK = B.LINK AND DGH.DEP_LINK = @DEP_LINK
	) B
	LEFT JOIN #PERS_INV I ON I.PERS_LINK = B.LINK AND ISNULL(I.DATE_BEGIN,@PeriodBegin) <= @PeriodEnd AND ISNULL(I.DATE_END,@PeriodEnd) >= @PeriodBegin		
WHERE --Добавляем если не было инвалидов или инвалидность была не весь период
	I.PERS_LINK IS NULL --не было инвалидов
	OR --инвалидность была не весь период
	CASE WHEN ISNULL(I.DATE_BEGIN,@PeriodBegin) < @PeriodBegin THEN @PeriodBegin ELSE ISNULL(I.DATE_BEGIN,@PeriodBegin) END
		BETWEEN @PeriodBegin+1 AND @PeriodEnd-1
	OR --инвалидность была не весь период
	CASE WHEN ISNULL(I.DATE_END,@PeriodEnd) > @PeriodEnd THEN @PeriodEnd ELSE ISNULL(I.DATE_END,@PeriodEnd) END
		BETWEEN @PeriodBegin+1 AND @PeriodEnd-1	

----ЕНВД
DECLARE @LINK_USEN INT
SET @LINK_USEN = ISNULL((SELECT TOP 1 LINK FROM dbo.SA_PFR_KATEG WHERE LINK2 = 2 AND @Year BETWEEN YBEG AND YEND),1)		
	
insert into dbo.SZV4_SVEDENIA 
	(link_up, orders, forma, link_pers, sum_doh, sum_str, sum_nak, sum_dop, dper_vn_m, dper_vn_d,dper_oz_m, dper_oz_d, isum_str, isum_nak, LINK_KATEG, DATE_BEG, DATE_END) 
SELECT 	
	link_up, orders, forma, link_pers, ISNULL(sum_doh,0), ISNULL(sum_str,0), ISNULL(sum_nak,0), ISNULL(sum_dop,0), ISNULL(dper_vn_m,0), ISNULL(dper_vn_d,0), ISNULL(dper_oz_m,0), ISNULL(dper_oz_d,0), ISNULL(isum_str,0), ISNULL(isum_nak,0), @LINK_USEN, DATE_BEG, DATE_END
FROM
	#PERSON B INNER JOIN dbo.SZV4_SVEDENIA S ON B.LINK = S.link_pers 
WHERE
	link_up = @link
	AND
	LINK_KATEG = @LINK_NR	
	

----СУММЫ ВЗНОСОВ В ЗАВИСИМОСТИ ОТ КАТЕГОРИИ ПО ЖУРНАЛУ ОПЕРАЦИЙ
CREATE TABLE #PERS_SUM_J (LINK_PERS INT, LINK_KATEG INT, DOG TINYINT, MON INT, INCOME NUMERIC(18,2), SUMMA_BASE NUMERIC(18,2), SUMMA_I NUMERIC(18,2), SUMMA_G NUMERIC(18,2))
INSERT INTO #PERS_SUM_J (LINK_PERS, LINK_KATEG, DOG, MON, INCOME, SUMMA_BASE, SUMMA_I, SUMMA_G)
SELECT LINK_PERS, LINK_KATEG, DOG, MON,
	SUM(CASE WHEN [OBJECT] = 1 THEN SUMMA ELSE 0 END), --ВСЕГО ДОХОД (INCOME)
	SUM(CASE WHEN [OBJECT] = 3 AND WAY_CALC = 6 THEN SUMMA_BASE ELSE 0 END),
	SUM(CASE WHEN [OBJECT] = 3 AND WAY_CALC = 6 THEN SUMMA ELSE 0 END),
	SUM(CASE WHEN [OBJECT] = 3 AND WAY_CALC = 7 THEN SUMMA ELSE 0 END)	
FROM
(
	SELECT 
		S.LINK_PERS, P.[WAY_CALC], S.LINK_KATEG, DOG = S.FORMA, P.[OBJECT], MON = MONTH(J.PERIOD_BEGIN), SUMMA_BASE = SUM(SUMMA_BASE), SUMMA = SUM(SUMMA)
	FROM 
		#PERSON B 
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.link_pers = B.LINK
		INNER JOIN dbo.EMPL E ON E.PERS_LINK = S.LINK_PERS
		INNER JOIN dbo.CALCULATE_JURNAL J ON J.LINK_EMPL = E.LINK 
			AND YEAR(J.PERIOD_BEGIN) = @Year AND MONTH(J.PERIOD_BEGIN) BETWEEN MONTH(S.DATE_BEG) AND MONTH(S.DATE_END)
		INNER JOIN dbo.PAYS P ON P.LINK = J.LINK_PAYS
		INNER JOIN dbo.SAL_SFIN F ON F.LINK = J.LINK_VKR
	WHERE
		S.LINK_UP = @link
		AND 
		(
			P.[OBJECT] = 3 AND P.[WAY_CALC] IN (6, 7)
			OR
			P.[OBJECT] = 1
		)
		AND J.LINK_DEP = @DEP_LINK
		AND S.FORMA = 1 --ВИД ДОГОВОРА (ТРУДОВОЙ)
		AND (LINK_KATEG = @LINK_OZOI OR (LINK_KATEG = @LINK_USEN AND F.ENVD = 1) OR (LINK_KATEG = @LINK_NR AND F.ENVD = 0))
	GROUP BY
		S.LINK_PERS, P.[WAY_CALC], S.LINK_KATEG, S.FORMA, P.[OBJECT], J.PERIOD_BEGIN
	UNION ALL	
	SELECT 
		S.LINK_PERS, P.[WAY_CALC], S.LINK_KATEG, DOG = S.FORMA, P.[OBJECT], MON = MONTH(J.PERIOD_BEGIN), SUMMA_BASE = SUM(SUMMA_BASE), SUMMA = SUM(SUMMA)
	FROM 
		#PERSON B 
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = B.LINK
		INNER JOIN dbo.CALCULATE_JURNAL J ON J.PERS_LINK = S.LINK_PERS 
			AND YEAR(J.PERIOD_BEGIN) = @Year AND MONTH(J.PERIOD_BEGIN) BETWEEN MONTH(S.DATE_BEG) AND MONTH(S.DATE_END)
		INNER JOIN dbo.PAYS P ON P.LINK = J.LINK_PAYS
		INNER JOIN dbo.SAL_SFIN F ON F.LINK = J.LINK_VKR
	WHERE
		S.LINK_UP = @link
		AND 
		(
			P.[OBJECT] = 3 AND P.[WAY_CALC] IN (6, 7)
			OR
			P.[OBJECT] = 1
		)
		AND J.LINK_DEP = @DEP_LINK
		AND S.FORMA = 2 --ВИД ДОГОВОРА (ГПХ)
		AND (LINK_KATEG = @LINK_OZOI OR (LINK_KATEG = @LINK_USEN AND F.ENVD = 1) OR (LINK_KATEG = @LINK_NR AND F.ENVD = 0))
	GROUP BY
		S.LINK_PERS, P.[WAY_CALC], S.LINK_KATEG, S.FORMA, P.[OBJECT], J.PERIOD_BEGIN
) T
GROUP BY LINK_PERS, LINK_KATEG, DOG, MON

--
CREATE INDEX #TMP_IDX_#PERS_SUM_J ON #PERS_SUM_J (LINK_PERS, LINK_KATEG)

--рАСЧЁТ ОБЛАГАЕМОЙ СУММЫ ДОХОДА ЗА ПЕРИОД
--в РАСЧЁТ НЕ ДОЛЖНА ПОПАСТЬ СУММА С ПРЕВЫШЕНИЯ СУММЫ ДОХОДА 512 ТЫС С УЧЁТОМ СКИДОК
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, KATEG TINYINT, DOG TINYINT)

Insert InTo #SPR_ESN ([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG, DOG)
SELECT [MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG, DOG = 1
FROM 
	dbo.SA_ESN_VIEW(@Year, @Month, @DEP_LINK, 0) S
WHERE 
	WAY_CALC IN (6,7,10,11)
	AND EXISTS (SELECT * FROM #PERSON B WHERE B.LINK = S.REF_PHYS_PERS)

--Суммы по договорникам
INSERT INTO #SPR_ESN 
	([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG, DOG)
SELECT 
	MONTH(G.[DATE]) AS MONTH_BASE, 
	GT.SUMMA_BASE, 0, 0, GT.SUMMA, GT.WAY_CALC, GT.PERS_LINK, 
	CASE WHEN dbo.is_invalid(GT.PERS_LINK,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,G.[MONTH],@Year))) = 2
		THEN 3
		ELSE
		CASE WHEN F.ENVD = 1 THEN 2 ELSE 1 END
	END, 
	DOG = 2
FROM 
	dbo.DOCUMENTS_DGH G 
	INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
	inner join dbo.PERSON P on GT.PERS_LINK = P.link
	INNER JOIN #PERSON B ON B.LINK = P.LINK
	inner join dbo.SAL_SFIN F on F.LINK = GT.LINK_VKR
WHERE 
	FLAG_JC = 1
	AND GT.WAY_CALC  IN (6,7,10,11)
	AND YEAR(G.[DATE]) = @Year
	AND MONTH(G.[DATE]) <= @Month
	AND LINK_DEP = @DEP_LINK

--
CREATE INDEX #TMP_IDX_SPR_ESN ON #SPR_ESN (REF_PHYS_PERS, KATEG, DOG)

--
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)

--Информация о ставках
DECLARE @STAVKI TABLE ( LINK_PERS INT, TARIF TINYINT, PREDEL NUMERIC(15,2), [PERCENT] NUMERIC(8,2), WAY_CALC TINYINT)

INSERT INTO @STAVKI (LINK_PERS, TARIF, PREDEL, [PERCENT], WAY_CALC)
SELECT 
	LINK_PERS, TARIF, PREDEL, [PERCENT], WAY_CALC 
FROM 
	dbo.SA_ESN_TARIF(DEFAULT, @PeriodEnd, DEFAULT) S
WHERE 
	WAY_CALC IN (6,7)
	AND EXISTS (SELECT * FROM #PERSON P WHERE P.LINK = S.LINK_PERS)

--	
DECLARE @LIMIT NUMERIC(18,2)
SET @LIMIT = ISNULL((SELECT MIN(PREDEL) FROM @STAVKI WHERE TARIF = 1 AND WAY_CALC = 6),0)

------СУММЫ В ЗАВИСИМОСТИ ОТ КАТЕГОРИИ ПО РАСЧЁТАМ ЕСН С УЧЁТОМ ПРЕВЫШЕНИЯ 512Т.
CREATE TABLE #SUM_PERSON (LINK_PERSON INT, KATEG TINYINT, DOG TINYINT, WAY_CALC TINYINT, [PERCENT] NUMERIC(18,2), MON TINYINT, 
				BAZA NUMERIC(18,2), SUM_LIM NUMERIC(18,2), SUM_KOR NUMERIC(18,2),BAZA2 NUMERIC(18,2),  NALOG NUMERIC(20,6), M BIT)

INSERT INTO #SUM_PERSON (LINK_PERSON, KATEG, DOG, WAY_CALC, [PERCENT], MON, BAZA, NALOG, M)
SELECT
	E.REF_PHYS_PERS, E.KATEG, E.DOG, S.WAY_CALC, S.[PERCENT], E.MONTH_BASE,
	SUM(ISNULL(SUMMA_BASE,0) - ISNULL(DED_M,0) - ISNULL(INV_M,0)) AS BAZA,
	SUM(SUMMA),
	0
FROM 
	#SPR_ESN E
	INNER JOIN @STAVKI S ON S.LINK_PERS = E.REF_PHYS_PERS AND S.WAY_CALC = E.WAY_CALC AND S.TARIF = E.KATEG
WHERE 
	S.PREDEL = @LIMIT
GROUP BY
	E.REF_PHYS_PERS, E.KATEG, E.DOG, S.WAY_CALC, S.[PERCENT], E.MONTH_BASE

--ТОЛЬКО ТЕ, У КОГО ДОХОД ПРЕВЫСИЛ ЛИМИТ
CREATE TABLE #PERS_AFTER (LINK_PERSON INT, KATEG TINYINT, DOG TINYINT)

INSERT INTO #PERS_AFTER (LINK_PERSON, KATEG, DOG)
SELECT LINK_PERSON, KATEG, DOG
FROM #SUM_PERSON 
WHERE WAY_CALC = 6
GROUP BY LINK_PERSON, KATEG, DOG
HAVING SUM(BAZA) > @LIMIT
DECLARE @Cur2 CURSOR, @MON TINYINT, @KATEG TINYINT, @DOG TINYINT

SET @Cur2 = CURSOR FORWARD_ONLY
FOR SELECT DISTINCT MON, KATEG, DOG FROM #SUM_PERSON SP
	ORDER BY MON, KATEG ASC, DOG DESC
OPEN @Cur2
FETCH NEXT FROM @Cur2 INTO @MON, @KATEG, @DOG
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN

		UPDATE SP --ДОХОД С НАКОПЛЕНИЕМ С НАЧАЛА ГОДА
		SET 
			M = 1,
			SUM_LIM = (SELECT SUM(BAZA) FROM #SUM_PERSON SP1 WHERE SP1.LINK_PERSON = SP.LINK_PERSON AND SP1.WAY_CALC = SP.WAY_CALC AND (M=1 OR SP1.MON = SP.MON AND SP1.KATEG = SP.KATEG AND SP1.DOG = SP.DOG))
		FROM #SUM_PERSON SP
		WHERE MON = @MON AND KATEG = @KATEG AND DOG = @DOG
		
		UPDATE #SUM_PERSON --ПРЕВЫШЕНИЕ ЛИМИТА
		SET SUM_KOR = CASE WHEN ISNULL(SUM_LIM,0) > @LIMIT THEN ISNULL(SUM_LIM,0) - @LIMIT ELSE 0 END

		UPDATE #SUM_PERSON
		SET BAZA2 = CASE WHEN (ISNULL(BAZA,0) > ISNULL(SUM_KOR,0) OR ISNULL(BAZA,0) < 0)
							THEN ISNULL(BAZA,0) - ISNULL(SUM_KOR,0) ELSE 0 END
		
		UPDATE SP
		SET NALOG = 
					CASE WHEN BAZA <> BAZA2 
						THEN 
							
							CONVERT(NUMERIC(18,2),
							ISNULL((SELECT SUM(SP1.BAZA2) FROM #SUM_PERSON SP1 WHERE SP1.LINK_PERSON = SP.LINK_PERSON AND SP1.KATEG = SP.KATEG AND SP1.DOG = SP.DOG  AND SP1.WAY_CALC = SP.WAY_CALC AND SP1.MON <= SP.MON),0)
							* ISNULL([PERCENT],0) / 100)
							-
							CONVERT(NUMERIC(18,2),
							ISNULL((SELECT SUM(SP1.BAZA2) FROM #SUM_PERSON SP1 WHERE SP1.LINK_PERSON = SP.LINK_PERSON AND SP1.KATEG = SP.KATEG AND SP1.DOG = SP.DOG  AND SP1.WAY_CALC = SP.WAY_CALC AND SP1.MON < SP.MON),0)
							* ISNULL([PERCENT],0) / 100)

						ELSE 
							(SELECT CASE WHEN SP.WAY_CALC = 6 THEN SUM(SUMMA_I) ELSE SUM(SUMMA_G) END FROM #PERS_SUM_J PS WHERE PS.LINK_PERS = SP.LINK_PERSON AND SP.KATEG = PS.LINK_KATEG AND SP.DOG = PS.DOG AND PS.MON = SP.MON)
					END
					
					--CASE WHEN BAZA <> BAZA2 
					--	THEN ISNULL(BAZA2,0) * ISNULL([PERCENT],0) / 100
					--	ELSE (SELECT CASE WHEN SP.WAY_CALC = 6 THEN SUM(SUMMA_I) ELSE SUM(SUMMA_G) END FROM #PERS_SUM_J PS WHERE PS.LINK_PERS = SP.LINK_PERSON AND SP.KATEG = PS.LINK_KATEG AND PS.MON = SP.MON)
					--END	
		FROM
			#SUM_PERSON SP
		WHERE --ТОЛЬКО У ТЕХ, У КОГО ПРЕВЫШЕНИЕ ЛИМИТА
			EXISTS (SELECT * FROM #PERS_AFTER PA WHERE PA.LINK_PERSON = SP.LINK_PERSON AND PA.KATEG = SP.KATEG AND PA.DOG = SP.DOG)

	END
	FETCH NEXT FROM @Cur2 INTO @MON, @KATEG, @DOG
END

CLOSE @Cur2
DEALLOCATE @Cur2

--СУММЫ В ЗАВИСИМОСТИ ОТ КАТЕГОРИИ
CREATE TABLE #PERS_SUM (LINK_PERS INT, LINK_KATEG INT, DOG TINYINT, SUMMA_BASE NUMERIC(18,2), SUMMA_I NUMERIC(18,2), SUMMA_G NUMERIC(18,2))
INSERT INTO #PERS_SUM (LINK_PERS, LINK_KATEG, DOG, SUMMA_BASE, SUMMA_I, SUMMA_G)
SELECT LINK_PERS, LINK_KATEG, DOG,
	SUM(CASE WHEN WAY_CALC = 6 THEN SUMMA_BASE ELSE 0 END),
	SUM(CASE WHEN WAY_CALC = 6 THEN SUMMA ELSE 0 END),
	SUM(CASE WHEN WAY_CALC = 7 THEN SUMMA ELSE 0 END)	
FROM
(
	SELECT 
		S.LINK_PERS, SP.[WAY_CALC], S.LINK_KATEG, DOG = S.FORMA, SUMMA_BASE = SUM(BAZA2), SUMMA = SUM(NALOG)
	FROM 
		#PERSON B 
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.link_pers = B.LINK
		INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG
		INNER JOIN #SUM_PERSON SP ON SP.LINK_PERSON = S.LINK_PERS AND SP.KATEG = K.LINK2 AND S.FORMA = SP.DOG AND SP.MON BETWEEN MONTH(S.DATE_BEG) AND MONTH(S.DATE_END)
	WHERE
		S.LINK_UP = @link
		AND
		@Year BETWEEN K.YBEG AND K.YEND
	GROUP BY
		S.LINK_PERS, SP.[WAY_CALC], S.LINK_KATEG, S.FORMA
) T
GROUP BY LINK_PERS, LINK_KATEG, DOG

--
UPDATE S SET
	sum_doh = ISNULL(SUMMA_I,0), --После 10 года содержит начисленную страховую часть
	sum_str = 0, --После 10 года должен содержать перечисленную страховую часть, но т.к. ее не знаем - то 0, потом определим
	sum_nak = ISNULL(SUMMA_G,0), --Для все периодов содержит начисленную накопительную часть
	sum_dop = 0 -- После 10 года должен содержать перечисленную накопительную часть, но т.к. ее не знаем - то 0, потом определим
FROM
	dbo.SZV4_SVEDENIA S 
	INNER JOIN #PERS_SUM P ON P.LINK_PERS = S.LINK_PERS AND P.LINK_KATEG = S.LINK_KATEG AND P.DOG = S.FORMA
WHERE
	link_up = @link

---Заполняются суммы по доптарифам
CREATE TABLE #INCOME_T1T2 (
	LINK_PERS INT, 
	KATEG TINYINT,
	DOG TINYINT, 
	INCOME_T1_M1 NUMERIC(18,2),
	INCOME_T2_M1 NUMERIC(18,2),
	INCOME_T1_M2 NUMERIC(18,2),
	INCOME_T2_M2 NUMERIC(18,2),
	INCOME_T1_M3 NUMERIC(18,2),
	INCOME_T2_M3 NUMERIC(18,2)
	)

INSERT INTO #INCOME_T1T2 (LINK_PERS, KATEG, DOG, INCOME_T1_M1, INCOME_T2_M1, INCOME_T1_M2, INCOME_T2_M2, INCOME_T1_M3, INCOME_T2_M3)
SELECT REF_PHYS_PERS, KATEG, E.DOG, 
	INCOME_T1_M1 = SUM(CASE WHEN WAY_CALC = 10 AND MONTH_BASE = (@Month - 2) THEN SUMMA_BASE - DED_M - INV_M ELSE 0 END), 
	INCOME_T2_M1 = SUM(CASE WHEN WAY_CALC = 11 AND MONTH_BASE = (@Month - 2) THEN SUMMA_BASE - DED_M - INV_M ELSE 0 END),
	INCOME_T1_M2 = SUM(CASE WHEN WAY_CALC = 10 AND MONTH_BASE = (@Month - 1) THEN SUMMA_BASE - DED_M - INV_M ELSE 0 END),
	INCOME_T2_M2 = SUM(CASE WHEN WAY_CALC = 11 AND MONTH_BASE = (@Month - 1) THEN SUMMA_BASE - DED_M - INV_M ELSE 0 END),
	INCOME_T1_M3 = SUM(CASE WHEN WAY_CALC = 10 AND MONTH_BASE = @Month THEN SUMMA_BASE - DED_M - INV_M ELSE 0 END),
	INCOME_T2_M3 = SUM(CASE WHEN WAY_CALC = 11 AND MONTH_BASE = @Month THEN SUMMA_BASE - DED_M - INV_M ELSE 0 END)
FROM #SPR_ESN E
WHERE WAY_CALC IN (10,11)	
GROUP BY REF_PHYS_PERS, KATEG, E.DOG

UPDATE S SET
	S.INCOME_T1_M1 = P.INCOME_T1_M1,
	S.INCOME_T2_M1 = P.INCOME_T2_M1,
	S.INCOME_T1_M2 = P.INCOME_T1_M2,
	S.INCOME_T2_M2 = P.INCOME_T2_M2,
	S.INCOME_T1_M3 = P.INCOME_T1_M3,
	S.INCOME_T2_M3 = P.INCOME_T2_M3
FROM
	dbo.SZV4_SVEDENIA S 
	INNER JOIN #INCOME_T1T2 P ON P.LINK_PERS = S.LINK_PERS AND P.KATEG = S.LINK_KATEG AND P.DOG = S.FORMA
WHERE
	link_up = @link

--Всего начислено по физлицам дохода
CREATE TABLE #INCOME(
	LINK_PERS INT, 
	KATEG TINYINT,
	DOG TINYINT, 
	INCOME_M1 NUMERIC(18,2),
	INCOME_M2 NUMERIC(18,2),
	INCOME_M3 NUMERIC(18,2)
	)

INSERT INTO #INCOME (LINK_PERS, KATEG, DOG, INCOME_M1, INCOME_M2, INCOME_M3)
SELECT 
	LINK_PERS, LINK_KATEG, DOG,
	INCOME_M1 = SUM(CASE WHEN MON = (@Month - 2) THEN INCOME ELSE 0 END),
	INCOME_M2 = SUM(CASE WHEN MON = (@Month - 1) THEN INCOME ELSE 0 END),
	INCOME_M3 = SUM(CASE WHEN MON = @Month THEN INCOME ELSE 0 END)
FROM #PERS_SUM_J
GROUP BY 
	LINK_PERS, LINK_KATEG, DOG

UPDATE S SET
	S.INCOME_M1 = P.INCOME_M1,
	S.INCOME_M2 = P.INCOME_M2,
	S.INCOME_M3 = P.INCOME_M3
FROM
	dbo.SZV4_SVEDENIA S 
	INNER JOIN #INCOME P ON P.LINK_PERS = S.LINK_PERS AND P.KATEG = S.LINK_KATEG AND P.DOG = S.FORMA
WHERE
	link_up = @link	

--База для страховых взносов
CREATE TABLE #BASE(
	LINK_PERS INT, 
	KATEG TINYINT,
	DOG TINYINT, 
	BASE_BEFORE_M1 NUMERIC(18,2),
	BASE_AFTER_M1 NUMERIC(18,2),
	BASE_BEFORE_M2 NUMERIC(18,2),
	BASE_AFTER_M2 NUMERIC(18,2),
	BASE_BEFORE_M3 NUMERIC(18,2),
	BASE_AFTER_M3 NUMERIC(18,2)	
	)

INSERT INTO #BASE (LINK_PERS, KATEG, DOG, BASE_BEFORE_M1, BASE_AFTER_M1, BASE_BEFORE_M2, BASE_AFTER_M2, BASE_BEFORE_M3, BASE_AFTER_M3 )
SELECT LINK_PERSON, KATEG, DOG,
	BASE_BEFORE_M1	= SUM(CASE WHEN MON = (@Month - 2) THEN BAZA2 ELSE 0 END),
	BASE_AFTER_M1	= SUM(CASE WHEN MON = (@Month - 2) THEN BAZA - BAZA2 ELSE 0 END),
	BASE_BEFORE_M2	= SUM(CASE WHEN MON = (@Month - 1) THEN BAZA2 ELSE 0 END),
	BASE_AFTER_M2	= SUM(CASE WHEN MON = (@Month - 1) THEN BAZA - BAZA2 ELSE 0 END),
	BASE_BEFORE_M3	= SUM(CASE WHEN MON = @Month THEN BAZA2 ELSE 0 END),
	BASE_AFTER_M3	= SUM(CASE WHEN MON = @Month THEN BAZA - BAZA2 ELSE 0 END)		
FROM #SUM_PERSON 
WHERE 
	WAY_CALC = 6
GROUP BY
	LINK_PERSON, KATEG, DOG

UPDATE S SET
	S.BASE_BEFORE_M1 = P.BASE_BEFORE_M1,
	S.BASE_AFTER_M1 = P.BASE_AFTER_M1,
	S.BASE_BEFORE_M2 = P.BASE_BEFORE_M2,
	S.BASE_AFTER_M2 = P.BASE_AFTER_M2,
	S.BASE_BEFORE_M3 = P.BASE_BEFORE_M3,
	S.BASE_AFTER_M3 = P.BASE_AFTER_M3	
FROM
	dbo.SZV4_SVEDENIA S 
	INNER JOIN #BASE P ON P.LINK_PERS = S.LINK_PERS AND P.KATEG = S.LINK_KATEG AND P.DOG = S.FORMA
WHERE
	link_up = @link	

--У кого нет дохода, но есть стаж
SELECT LINK_PERS, FORMA, LINK_KATEG INTO #TAB FROM dbo.SZV4_SVEDENIA WHERE LINK_UP = @link GROUP BY LINK_PERS, FORMA, LINK_KATEG HAVING SUM(sum_doh) = 0 AND SUM(sum_nak) = 0 AND SUM(INCOME_M1) = 0
--	
DELETE FROM dbo.SZV4_SVEDENIA 
WHERE link_up = @link AND sum_doh = 0 AND sum_nak = 0 AND INCOME_M1 = 0 AND LINK_KATEG NOT IN( @LINK_NR, @LINK_OZOI)

DELETE FROM dbo.SZV4_SVEDENIA
WHERE link_up = @link AND sum_doh = 0 AND sum_nak = 0 AND INCOME_M1 = 0 
	AND NOT EXISTS (SELECT LINK_PERS FROM #TAB T WHERE T.LINK_PERS = dbo.SZV4_SVEDENIA.LINK_PERS AND T.FORMA = dbo.SZV4_SVEDENIA.FORMA AND T.LINK_KATEG = dbo.SZV4_SVEDENIA.LINK_KATEG)

---- РАСПРЕДЕЛЕНИЕ ПЕРЕЧИСЛЕННОЙ СУММЫ ПО ФИЗЛИЦАМ
EXEC [dbo].SA_SZV4_PACHKA_RASPIL @link

IF @VID_KOR != 3
	begin  
	---СВЕДЕНИЯ О СТАЖЕ
	----------------------------------------------------------------------------
	CREATE TABLE #PERIODY (link int identity(1,1), link_face int, LINK_KATEG INT, date1 datetime, date2 datetime, [type] int, NUM_STAKE NUMERIC(5,2), [IS_DOP] VARCHAR(20))

	--/*Стаж сотрудников*/
	INSERT INTO 
		#PERIODY (link_face, LINK_KATEG, date1, date2, type)
	SELECT 	DISTINCT
		PERS_LINK, LINK_KATEG,
		CASE WHEN S.DATE_BEG < (case when P.DATE_BEGIN >= @PeriodBegin then P.DATE_BEGIN else @PeriodBegin end)
			THEN (case when P.DATE_BEGIN >= @PeriodBegin then P.DATE_BEGIN else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
			THEN (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
			ELSE S.DATE_END
		END,	
		0
	FROM
		#PERSON B
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = B.LINK
		INNER JOIN dbo.EMPL E ON S.LINK_PERS = E.PERS_LINK AND E.DEP_LINK = @DEP_LINK
		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
		S.LINK_UP = @link
		AND
		P.DATE_BEGIN <= @PeriodEnd
		AND
		coalesce(U.DIS_DATE,'20990101') >= @PeriodBegin

	/*Стаж договорников*/
	Select DISTINCT
		link_face = DGH.PERS_LINK, LINK_KATEG,
		date1 = CASE WHEN S.DATE_BEG < (case when DGH.DATE1 >= @PeriodBegin then DGH.DATE1 else @PeriodBegin end)
				THEN (case when DGH.DATE1 >= @PeriodBegin then DGH.DATE1 else @PeriodBegin end)
				ELSE S.DATE_BEG
			END,
		date2 = CASE WHEN S.DATE_END > (case when coalesce(DGH.DATE2,@PeriodEnd) <= @PeriodEnd then coalesce(DGH.DATE2,@PeriodEnd) else @PeriodEnd end)
				THEN (case when coalesce(DGH.DATE2,@PeriodEnd) <= @PeriodEnd then coalesce(DGH.DATE2,@PeriodEnd) else @PeriodEnd end)
				ELSE S.DATE_END
			END,
		[type] = 0
	INTO #DGH	
	FROM
		#PERSON B
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = B.LINK
		INNER JOIN dbo.SALARY_REESTR_DGH DGH ON S.LINK_PERS = DGH.PERS_LINK
	WHERE 
		S.LINK_UP = @link
		AND
		DGH.DEP_LINK = @DEP_LINK
		and
		DGH.DATE1 <= @PeriodEnd
		and
		coalesce(DGH.DATE2,'20990101') >= @PeriodBegin

	-- Периоды в сведениях впишем в периоды работы
	SELECT LINK_FACE, DB = MIN(DATE1), DE = MAX(DATE2)
	INTO #WORK
	FROM #PERIODY
	GROUP BY LINK_FACE

	UPDATE S SET 
		S.DATE_BEG = CASE WHEN W.DB < S.DATE_BEG THEN S.DATE_BEG ELSE W.DB END,
		S.DATE_END = CASE WHEN W.DE > S.DATE_END THEN S.DATE_END ELSE W.DE END
	FROM 
		dbo.SZV4_SVEDENIA S INNER JOIN #WORK W ON S.LINK_PERS = W.LINK_FACE
	WHERE 
		S.LINK_UP = @link

	--
	CREATE TABLE #ADD_TYPE (
		[type] INT IDENTITY(1,1),
		[TERR_USL_TRUD] int NULL ,
		[TERR_RK] numeric(3, 2) NULL ,
		[OSOB_USL_TRUD] int NULL ,
		[COD_POS_SPISOK] int NULL ,
		[COD_POS_SPISOK2] int NULL ,
		[USL_DOSROCH_PENS] int NULL ,
		[STAVKA_PED_MED] numeric(3, 2) NULL,
		[VID] VARCHAR(20),
		[IS_DOP] VARCHAR(20),
		[COD_SPO_USL_TRUD] INT NULL
	)	
	--Новые типы
	INSERT INTO #ADD_TYPE 
	SELECT DISTINCT ISNULL(TERR_USL_TRUD,0), ISNULL(TERR_RK,0), ISNULL(OSOB_USL_TRUD,0), ISNULL(COD_POS_SPISOK,0), ISNULL(COD_POS_SPISOK2,0), ISNULL(USL_DOSROCH_PENS,0), ISNULL(STAVKA_PED_MED,0), VID = 'ADD_TYPE', IS_DOP = '', ISNULL([COD_SPO_USL_TRUD],0)
	FROM dbo.staff
	WHERE ISNULL(TERR_USL_TRUD,0) <> 0 OR ISNULL(TERR_RK,0) <> 0 OR ISNULL(OSOB_USL_TRUD,0) <> 0 OR ISNULL(COD_POS_SPISOK,0) <> 0 OR ISNULL(COD_POS_SPISOK2,0) <> 0 OR ISNULL(USL_DOSROCH_PENS,0) <> 0 OR ISNULL(STAVKA_PED_MED,0) <> 0 OR ISNULL([COD_SPO_USL_TRUD],0) <> 0

	--
	DECLARE @MAX_TYPE INT
	SET @MAX_TYPE = ISNULL((SELECT MAX(type) FROM #ADD_TYPE),0)

	INSERT INTO #ADD_TYPE (VID, IS_DOP)
	VALUES ('TMP_TYPE', '')

	INSERT INTO #ADD_TYPE (VID, IS_DOP)
	VALUES ('PERIOD1', 'ДЕКРЕТ')

	INSERT INTO #ADD_TYPE (VID, IS_DOP)
	SELECT DISTINCT
		'PERIOD2',
		ISNULL(V.IS_DOP,'ДЕТИ')
	FROM
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK 
		inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
		INNER JOIN dbo.VACATION_VID V ON V.LINK = IV.TYPE_LINK
		INNER JOIN (SELECT VV.LINK FROM dbo.VACATION_VID VV INNER join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK WHERE WORK_D = 7 AND ISNULL(VV.NOT_LGOT_EXPIR,0) = 0) VV ON VV.LINK = IV.TYPE_LINK
		left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and coalesce(ivb.active,0) = 1
	where 
		S.LINK_UP = @link
		AND		
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin

	INSERT INTO #ADD_TYPE (VID, IS_DOP)
	SELECT DISTINCT
		'PERIOD2LS',
		ISNULL(V.IS_DOP,'ДЕТИ')
	FROM
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK 
		inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
		INNER JOIN dbo.VACATION_VID V ON V.LINK = IV.TYPE_LINK
		INNER JOIN (SELECT VV.LINK FROM dbo.VACATION_VID VV INNER join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK WHERE WORK_D = 7 AND ISNULL(VV.NOT_LGOT_EXPIR,0) = 1) VV ON VV.LINK = IV.TYPE_LINK
		left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and coalesce(ivb.active,0) = 1
	where 
		S.LINK_UP = @link
		AND		
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin		

	INSERT INTO #ADD_TYPE (VID, IS_DOP)
	VALUES ('PERIOD3', 'ВРНЕТРУД')

	INSERT INTO #ADD_TYPE (VID, IS_DOP)
	Select DISTINCT
		'PERIOD4',
		ISNULL(VV.IS_DOP,'АДМИНИСТР')
	FROM
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK  
		inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
		INNER JOIN dbo.VACATION_VID VV ON VV.LINK = IV.type_link AND VV.NO_SAL = 1
		left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and coalesce(ivb.active,0) = 1
	where
		S.LINK_UP = @link
		AND		 	
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin

	--Периоды работы на должности c параметрами для персучета
	INSERT INTO 
		#PERIODY (link_face, LINK_KATEG, date1, date2, [type], NUM_STAKE)
	SELECT DISTINCT 
		link_face = E.PERS_LINK, S.LINK_KATEG,
		date1 = CASE WHEN S.DATE_BEG < (case when st.DATE_BEGIN >= @PeriodBegin then st.DATE_BEGIN else @PeriodBegin end)
					THEN (case when st.DATE_BEGIN >= @PeriodBegin then st.DATE_BEGIN else @PeriodBegin end)
					ELSE S.DATE_BEG
				END,
		date2 = CASE WHEN 
						(CASE WHEN S.DATE_END > (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
							THEN (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
							ELSE S.DATE_END
						END)
							> (case when st.DATE_END <= @PeriodEnd then st.DATE_END else @PeriodEnd end)
					THEN 
						(case when st.DATE_END <= @PeriodEnd then st.DATE_END else @PeriodEnd end)
					ELSE 
						(CASE WHEN S.DATE_END > (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
							THEN (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
							ELSE S.DATE_END
						END)
				END,	
		ISNULL(T.[type],0),
		ISNULL(im.NUM_STAKE,0)--, ST.*
	FROM 
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK	
		INNER JOIN dbo.sa_item_move im ON im.EMPL_LINK = e.link
		inner join dbo.staff_head sh on sh.link = STAFF_LINK
		inner join dbo.staff st on st.link_up = sh.link
		LEFT JOIN dbo.ITEM_DIS_FACE U on E.link = U.empl_link AND U.ACTIVE=1	
		left join #ADD_TYPE T on 
				ISNULL(st.TERR_USL_TRUD,0) = ISNULL(T.TERR_USL_TRUD,0) 
				AND ISNULL(st.TERR_RK,0) = ISNULL(T.TERR_RK,0) 
				AND ISNULL(st.OSOB_USL_TRUD,0) = ISNULL(T.OSOB_USL_TRUD,0) 
				AND ISNULL(st.COD_POS_SPISOK,0) = ISNULL(T.COD_POS_SPISOK,0) 
				AND ISNULL(st.COD_POS_SPISOK2,0) = ISNULL(T.COD_POS_SPISOK2,0) 
				AND ISNULL(st.USL_DOSROCH_PENS,0) = ISNULL(T.USL_DOSROCH_PENS,0) 
				AND ISNULL(st.STAVKA_PED_MED,0) = ISNULL(T.STAVKA_PED_MED,0) 
				AND ISNULL(st.[COD_SPO_USL_TRUD],0) = ISNULL(T.[COD_SPO_USL_TRUD],0)
	where 
		S.LINK_UP = @link
		AND
		IM.NUM_STAKE >= 1 
		AND
		IM.[STATUS] <> 2 --Совместителям доп. тариф не считаем
		AND
		im.DATE_BEGIN <= @PeriodEnd and im.DATE_END3 >= @PeriodBegin
		and 
		st.DATE_BEGIN <= @PeriodEnd and st.DATE_END >= @PeriodBegin
		AND
		T.[TYPE] IS NOT NULL AND T.VID = 'ADD_TYPE'
		AND
		COALESCE(U.DIS_DATE,'20990101') >= @PeriodBegin
	order by
		E.PERS_LINK

	---**************************************

	DECLARE @TMP_TYPE INT
	SET @TMP_TYPE = (SELECT TOP 1 TYPE FROM #ADD_TYPE WHERE VID = 'TMP_TYPE')

	/*Перерыв - отпуска без кодов (для корр. льготных периодов)*/
	INSERT INTO 
		#PERIODY (link_face, LINK_KATEG, date1, date2, [type])
	Select DISTINCT 
		E.pers_link, LINK_KATEG,
		CASE WHEN S.DATE_BEG < (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			THEN (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when ISNULL(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then ISNULL(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			THEN (case when ISNULL(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then ISNULL(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		@TMP_TYPE
	FROM 
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK	
		inner join dbo.item_vacation iv on E.link = iv.EMPL_LINK 
		inner join dbo.orders o on iv.order_link=o.link
		-- Только отпуск, помеченный как "Не включать в льготный стаж", --Не административный (Для него свой код)
		INNER JOIN dbo.VACATION_VID VV ON VV.LINK = IV.type_link AND ISNULL(VV.NOT_LGOT_EXPIR,0) = 1 AND NO_SAL <> 1
		left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and ISNULL(ivb.active,0) = 1
	--	LEFT JOIN #PERIODY P ON P.link_face = P.LINK AND P.LINK_KATEG = S.LINK_KATEG AND P.[TYPE] = @TMP_TYPE
	where
		S.LINK_UP = @link
		AND 	
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		ISNULL(ISNULL(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin
		and -- Не по уходу за ребенком (Для него свой код)
		IV.type_link not in (SELECT VV.LINK FROM dbo.VACATION_VID VV INNER join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK WHERE WORK_D = 7)
		--AND
		--P.link_face IS NOT NULL AND 

	/*Перерыв - командировки без кодов (для корр. льготных периодов)*/	
	INSERT INTO 
		#PERIODY (link_face, LINK_KATEG, date1, date2, [type])
	SELECT DISTINCT
		E.pers_link, LINK_KATEG,
		CASE WHEN S.DATE_BEG < (case when T.date_begin >= @PeriodBegin then T.date_begin else @PeriodBegin end)
			THEN (case when T.date_begin >= @PeriodBegin then T.date_begin else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when ISNULL(ITL.NEW_DATE_END,T.date_end) <= @PeriodEnd then ISNULL(ITL.NEW_DATE_END,T.date_end) else @PeriodEnd end)
			THEN (case when ISNULL(ITL.NEW_DATE_END,T.date_end) <= @PeriodEnd then ISNULL(ITL.NEW_DATE_END,T.date_end) else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		@TMP_TYPE
	FROM 
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK	
		inner join dbo.item_travel T on E.link = T.EMPL_LINK
		left join dbo.ITEM_TRAVEL_LONG ITL on ITL.TRAVEL_LINK = T.LINK and ISNULL(ITL.ACTIVE,0) = 1	
	WHERE
		S.LINK_UP = @link
		AND 	
		E.DEP_LINK = @DEP_LINK
		AND 
		T.ACTIVE = 1 
		AND 
		T.DATE_BEGIN <= @PeriodEnd
		AND 
		ISNULL(ISNULL(ITL.NEW_DATE_END,T.date_end),'20990101') >= @PeriodBegin
		
	/*Перерыв - Больничный по Беременности и родам ДЕКРЕТ*/
	SET @TMP_TYPE = (SELECT TOP 1 TYPE FROM #ADD_TYPE WHERE VID = 'PERIOD1')

	INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
	SELECT 
		E.PERS_LINK, LINK_KATEG, 
		CASE WHEN S.DATE_BEG < (case when D.date1 >= @PeriodBegin then D.date1 else @PeriodBegin end)
			THEN (case when D.date1 >= @PeriodBegin then D.date1 else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when D.date2 <= @PeriodEnd then D.date2 else @PeriodEnd end)
			THEN (case when D.date2 <= @PeriodEnd then D.date2 else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		@TMP_TYPE
	FROM 
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK
		inner join dbo.SDOC_DIS D on E.LINK = D.LINK_EMPL
		INNER JOIN dbo.NETRUD N ON N.LINK = [TYPE] AND N.DEKRET = 1
	WHERE 
		S.LINK_UP = @link
		AND	
		E.DEP_LINK = @DEP_LINK
		and
		D.date1 <= @PeriodEnd
		and
		coalesce(D.date2,'20990101') >= @PeriodBegin

	/*Перерыв - Больничный ВРНЕТРУД*/
	SET @TMP_TYPE = (SELECT TOP 1 TYPE FROM #ADD_TYPE WHERE VID = 'PERIOD3')

	INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
	SELECT 
		E.PERS_LINK, LINK_KATEG, 
		CASE WHEN S.DATE_BEG < (case when D.date1 >= @PeriodBegin then D.date1 else @PeriodBegin end)
			THEN (case when D.date1 >= @PeriodBegin then D.date1 else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when D.date2 <= @PeriodEnd then D.date2 else @PeriodEnd end)
			THEN (case when D.date2 <= @PeriodEnd then D.date2 else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		@TMP_TYPE
	FROM 
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK
		inner join dbo.SDOC_DIS D on E.LINK = D.LINK_EMPL
	WHERE
		S.LINK_UP = @link
		AND	 
		E.DEP_LINK = @DEP_LINK
		and
		D.date1 <= @PeriodEnd
		and
		coalesce(D.date2,'20990101') >= @PeriodBegin
		and
		[TYPE] not in (select LINK from dbo.NETRUD where DEKRET = 1)

	/*Перерыв - Уход за ребенком до 1,5 и до 3 лет*/
	INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
	SELECT 
		E.pers_link, LINK_KATEG,
		CASE WHEN S.DATE_BEG < (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			THEN (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			THEN (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		(SELECT TOP 1 TYPE FROM #ADD_TYPE AT WHERE AT.VID = 'PERIOD2' AND AT.IS_DOP = LTRIM(RTRIM(ISNULL(V.IS_DOP,'ДЕТИ'))))
	FROM
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK 
		inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
		INNER JOIN dbo.VACATION_VID V ON V.LINK = IV.TYPE_LINK
		INNER JOIN (SELECT VV.LINK FROM dbo.VACATION_VID VV INNER join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK WHERE WORK_D = 7 AND ISNULL(VV.NOT_LGOT_EXPIR,0) = 0) VV ON VV.LINK = IV.TYPE_LINK
		LEFT JOIN DBO.ITEM_VACATION_BREAK IVB ON IVB.VAC_LINK = IV.LINK AND COALESCE(IVB.ACTIVE,0) = 1
	WHERE 
		S.LINK_UP = @link
		AND		
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin

	INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
	SELECT 
		E.pers_link, LINK_KATEG,
		CASE WHEN S.DATE_BEG < (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			THEN (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			THEN (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		(SELECT TOP 1 TYPE FROM #ADD_TYPE AT WHERE AT.VID = 'PERIOD2LS' AND AT.IS_DOP = LTRIM(RTRIM(ISNULL(V.IS_DOP,'ДЕТИ'))))
	FROM
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK 
		inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
		INNER JOIN dbo.VACATION_VID V ON V.LINK = IV.TYPE_LINK
		INNER JOIN (SELECT VV.LINK FROM dbo.VACATION_VID VV INNER join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK WHERE WORK_D = 7 AND ISNULL(VV.NOT_LGOT_EXPIR,0) = 1) VV ON VV.LINK = IV.TYPE_LINK
		LEFT JOIN DBO.ITEM_VACATION_BREAK IVB ON IVB.VAC_LINK = IV.LINK AND COALESCE(IVB.ACTIVE,0) = 1
	WHERE 
		S.LINK_UP = @link
		AND		
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin

	/*Перерыв - Отпуск без сохранения содержания АДМИНИСТР*/
	INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
	Select E.pers_link, LINK_KATEG,
		CASE WHEN S.DATE_BEG < (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			THEN (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			THEN (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		(SELECT TOP 1 TYPE FROM #ADD_TYPE AT WHERE AT.VID = 'PERIOD4' AND AT.IS_DOP = LTRIM(RTRIM(ISNULL(VV.IS_DOP,'АДМИНИСТР'))))
	FROM
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK  
		inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
		INNER JOIN dbo.VACATION_VID VV ON VV.LINK = IV.type_link AND VV.NO_SAL = 1
		left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and coalesce(ivb.active,0) = 1
	WHERE
		S.LINK_UP = @link
		AND		 	
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin
		
	--------------------------------------------------------------------------
	-- 2. Выстроим последовательность периодов с учетом их пересечений и приоритетов по полю type.
	--- Предполагается, что на первом шаге однотипные периоды уже нормализованы, т.е. следующие подряд и вложенные объединены
	CREATE TABLE #PERIODY3 (link int identity(1,1), link_face int, LINK_KATEG INT, date1 datetime, date2 datetime, [type] INT, orders int, i int, NUM_STAKE NUMERIC(5,2), TYPE_ADD INT)

	--Все промежутки заполняются типом -1  т.е. несуществующими днями
	INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, [type])
	SELECT DISTINCT link_face, LINK_KATEG, @PeriodBegin, @PeriodEnd, [type] = -1  FROM #PERIODY

	CREATE TABLE #DAYS (ID INT IDENTITY(1,1), LINK_FACE INT, LINK_KATEG INT, [DATE] DATETIME, [TYPE] INT, NUM INT, NUM_STAKE NUMERIC(5,2), [TYPE_ADD] INT)

	INSERT INTO #DAYS (LINK_FACE, LINK_KATEG, [DATE], [TYPE], NUM, NUM_STAKE, [TYPE_ADD])
	SELECT P.LINK_FACE, P.LINK_KATEG, [DATE], [TYPE] = MAX([TYPE]), 0, 
		NUM_STAKE = MAX(ISNULL(NUM_STAKE,0)), 
		[TYPE_ADD] = MAX(CASE WHEN [TYPE] <= @MAX_TYPE THEN [TYPE] ELSE 0 END)
	FROM 
		#PERIODY P
		INNER JOIN dbo.days_ex(@PeriodBegin, @PeriodEnd) D ON 1=1
	WHERE
		D.[DATE] BETWEEN P.DATE1 AND P.DATE2
	GROUP BY
		P.LINK_FACE, P.LINK_KATEG, [date]
	ORDER BY	
		P.LINK_FACE, P.LINK_KATEG, [date]

	--Убрать льготы для периодов, в которых не сохраняются льготы
	UPDATE #DAYS SET [TYPE_ADD] = 0 
	WHERE 
		--Тип периода, в котором не сохраняются льготы
		EXISTS (SELECT * FROM #ADD_TYPE AT WHERE VID = 'TMP_TYPE' AND AT.[TYPE] = #DAYS.[TYPE])
		OR --ОТПУСК ПО УХОДУ ЗА РЕБЁНКОМ (ЕСЛИ ВКЛЮЧЕНА НАСТРОЙКА В ВИДЕ ОТПУСКА
		EXISTS (SELECT * FROM #ADD_TYPE AT WHERE AT.VID = 'PERIOD2LS' AND AT.[TYPE] = #DAYS.[TYPE])
		--OR --ДЕКРЕТ (БОЛЬНИЧНЫЙ 140 ДНЕЙ ПО БЕРЕМЕННОСТИ И РОДАМ
		--EXISTS (SELECT * FROM #ADD_TYPE AT WHERE AT.VID = 'PERIOD1' AND AT.[TYPE] = #DAYS.[TYPE])
		

	--Пронумеровать группы
	DECLARE 
		@ID INT, @ID1 INT, @ID2 INT, @LINK_FACE INT, @LINK_KATEG INT, @TYPE INT, @NUM INT,
		@LINK_FACE1 INT, @LINK_KATEG1 INT, @TYPE1 INT

	--Убрать временные периоды, которые заводились для корректировки льготных периодов
	SET @TMP_TYPE = (SELECT TOP 1 TYPE FROM #ADD_TYPE WHERE VID = 'TMP_TYPE')
	UPDATE #DAYS SET [type] = 0 WHERE [type] = @TMP_TYPE

	--	
	SELECT TOP 1 @ID1 = 0, @ID2 = 0, @NUM = 0, @LINK_FACE1 = LINK_FACE, @LINK_KATEG1 =LINK_KATEG, @TYPE1 = [TYPE]
	FROM #DAYS
	order by ID
	--
	DECLARE @Cur1 CURSOR
	SET @Cur1 = CURSOR FORWARD_ONLY
	FOR SELECT ID, LINK_FACE, LINK_KATEG, [TYPE] from #DAYS order by ID
	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @ID, @LINK_FACE, @LINK_KATEG, @TYPE
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN

			IF NOT (@LINK_FACE = @LINK_FACE1 AND @LINK_KATEG = @LINK_KATEG1 AND @TYPE = @TYPE1)
			BEGIN
				
				SELECT @NUM = @NUM + 1, @LINK_FACE1 = @LINK_FACE, @LINK_KATEG1 = @LINK_KATEG, @TYPE1 = @TYPE
				UPDATE #DAYS SET NUM = @NUM WHERE ID BETWEEN @ID1 AND @ID-1
				SELECT @ID1 = @ID 

			END

		END

		FETCH NEXT FROM @Cur1 INTO @ID, @LINK_FACE, @LINK_KATEG, @TYPE
	END

	CLOSE @Cur1
	DEALLOCATE @Cur1
	--
	UPDATE #DAYS SET NUM = @NUM+1 WHERE ID >= @ID1

	--

	INSERT INTO #PERIODY3 (link_face, LINK_KATEG, date1, date2, [type], orders, i, NUM_STAKE, TYPE_ADD)
	SELECT LINK_FACE, LINK_KATEG, DATE_BEG =  MIN([DATE]), DATE_END = MAX([DATE]), [TYPE], 0, 0, NUM_STAKE = MAX(ISNULL(NUM_STAKE,0)), TYPE_ADD
	FROM #DAYS	
	GROUP BY LINK_FACE, LINK_KATEG, NUM, [TYPE], TYPE_ADD
	ORDER BY LINK_FACE, LINK_KATEG, DATE_BEG, DATE_END

	--Удаляем временные промежутки
	DELETE FROM #PERIODY3 WHERE [TYPE] = -1

	/*пронумеруем периоды*/
	DECLARE @uslovie INT
	set @uslovie = 1
	while @uslovie > 0
	begin
		update #PERIODY3 set orders = @uslovie 
		from #PERIODY3 as tt
		where 	coalesce(orders,0) = 0
			and date1 = (select min(t.date1) from #PERIODY3 t where coalesce(orders,0) = 0 and t.link_face = tt.link_face AND T.LINK_KATEG = TT.LINK_KATEG)

		if @@rowcount > 0
			set @uslovie = @uslovie + 1
		else
			set @uslovie = 0
	end

	--СТАХ ПО ТРУДОВОМУ ДОГОВРУ
	insert into dbo.SZV4_STAZH (link_up, orders, date1, date2, ter_usl, ter_koef, osob_usl, osob_k1, osob_k2, osob_k3, is_osnov, is_dop, is_dop_m, is_dop_d, ud_osnov, ud_dop_m, ud_dop_d, ud_dop_k, osob_spo)
	Select S.link, P.orders, P.date1, P.date2, 
		ter_usl = ISNULL(spr1.CODE,spr1A.CODE),
		ter_koef = ISNULL(T.TERR_RK,TA.TERR_RK),
		osob_usl = ISNULL(spr2.CODE,spr2A.CODE),
		osob_k1 = ISNULL(spr6.CODE,spr6A.CODE),
		osob_k2 = ISNULL(spr7.CODE,spr7A.CODE),
		osob_k3 = NULL,
		is_osnov = NULL, 
		is_dop = LTRIM(RTRIM(ISNULL(T.IS_DOP,TA.IS_DOP))),
		is_dop_m = NULL, 
		is_dop_d = NULL, 
		ud_osnov = ISNULL(spr5.CODE,spr5A.CODE), 
		ud_dop_m = NULL, 
		ud_dop_d = NULL, 
		ud_dop_k = ISNULL(T.STAVKA_PED_MED,TA.STAVKA_PED_MED) * P.NUM_STAKE,
		osob_spo = ISNULL(spr9.CODE,spr9A.CODE)
	from
		#PERSON B 
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = B.LINK
		inner join #PERIODY3 P on S.link_pers = P.link_face AND S.LINK_KATEG = P.LINK_KATEG
		
		LEFT JOIN #ADD_TYPE T ON P.[TYPE] = T.[TYPE]
		LEFT JOIN dbo.szv4_spr spr1 on spr1.spr_code = 'TERR_USL' and spr1.LINK = T.TERR_USL_TRUD
		LEFT JOIN dbo.szv4_spr spr2 on spr2.spr_code = 'OSOB_USL_TRUDA' and spr2.LINK = T.OSOB_USL_TRUD
		--left join dbo.szv4_spr spr3 on spr3.spr_code = 'ISCHISL_STAZH_OSNOV' and spr3.code = T.is_osnov
		--left join dbo.szv4_spr spr4 on spr4.spr_code = 'ISCHISL_STAZH_DOP_SV' and spr4.code = T.is_dop
		left join dbo.szv4_spr spr5 on spr5.spr_code = 'DOSR_NAZN_PEN_OSNOV' and spr5.LINK = T.USL_DOSROCH_PENS
		left join dbo.szv4_spr spr6 on spr6.SPR_CODE LIKE 'SPISOK%' and spr6.LINK = T.COD_POS_SPISOK
		left join dbo.szv4_spr spr7 on spr7.SPR_CODE LIKE 'SPISOK%' and spr7.LINK = T.COD_POS_SPISOK2
		--left join dbo.szv4_spr spr8 on spr8.spr_code = 'LGOT_PROFES' and spr8.code = T.osob_k3
		left join dbo.szv4_spr spr9 on spr9.SPR_CODE LIKE 'SPO_USL_TRUDA' and spr9.LINK = T.[COD_SPO_USL_TRUD]

		LEFT JOIN #ADD_TYPE TA ON P.[TYPE_ADD] = TA.[TYPE] AND P.[TYPE_ADD] <> P.[TYPE]
		LEFT JOIN dbo.szv4_spr spr1A on spr1A.spr_code = 'TERR_USL' and spr1A.LINK = TA.TERR_USL_TRUD
		LEFT JOIN dbo.szv4_spr spr2A on spr2A.spr_code = 'OSOB_USL_TRUDA' and spr2A.LINK = TA.OSOB_USL_TRUD
		--left join dbo.szv4_spr spr3 on spr3.spr_code = 'ISCHISL_STAZH_OSNOV' and spr3.code = T.is_osnov
		--left join dbo.szv4_spr spr4 on spr4.spr_code = 'ISCHISL_STAZH_DOP_SV' and spr4.code = T.is_dop
		left join dbo.szv4_spr spr5A on spr5A.spr_code = 'DOSR_NAZN_PEN_OSNOV' and spr5A.LINK = TA.USL_DOSROCH_PENS
		left join dbo.szv4_spr spr6A on spr6A.SPR_CODE LIKE 'SPISOK%' and spr6A.LINK = TA.COD_POS_SPISOK
		left join dbo.szv4_spr spr7A on spr7A.SPR_CODE LIKE 'SPISOK%' and spr7A.LINK = TA.COD_POS_SPISOK2
		--left join dbo.szv4_spr spr8 on spr8.spr_code = 'LGOT_PROFES' and spr8.code = T.osob_k3	
		left join dbo.szv4_spr spr9A on spr9A.SPR_CODE LIKE 'SPO_USL_TRUDA' and spr9A.LINK = TA.[COD_SPO_USL_TRUD]
	where
		S.link_up = @link
		AND
		S.FORMA = 1
	order by
		S.link, P.orders

	--СТАХ ПО ГПХ
	CREATE TABLE #STAGE_DOG (
		LINK_PERS INT, 
		KATEG TINYINT,
		BERIOD_BEG DATETIME,
		BERIOD_END DATETIME
		)

	INSERT INTO #STAGE_DOG (LINK_PERS, KATEG, BERIOD_BEG, BERIOD_END)
	SELECT LINK_FACE, LINK_KATEG, MIN(date1), MAX(date2) 
	FROM #DGH A
	GROUP BY LINK_FACE, LINK_KATEG

	insert into dbo.SZV4_STAZH (link_up, orders, date1, date2)
	Select S.link, 1, P.BERIOD_BEG, P.BERIOD_END
	from
		#PERSON B 
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = B.LINK
		INNER JOIN #STAGE_DOG P on S.link_pers = P.LINK_PERS AND S.LINK_KATEG = P.KATEG
	where
		S.link_up = @link
		AND
		S.FORMA = 2
	order by
		S.link
		
end
--------------------------------------------------------------------------
exec dbo.SZV4_NUMERATOR @link



GO


GRANT EXECUTE ON dbo.[SA_SZV4_PACHKA_CALC_Buffer3] TO PUBLIC

GO



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

GO

CREATE PROCEDURE [dbo].SALARY_FILL_DED_ESN_VKR
--Начисление страховых взносов
@RefPay int, 
@LinkVKR int,
@LINK_EKR INT, 
@linkPers int, 
@Month int, 
@Year int, 
@FlagMS  tinyint,
@FlagShow int = 0,
@DEP_LINK INT  = NULL
AS

SET NOCOUNT ON

DECLARE @DATE1 datetime, 
		  @linkFace int,
		  @LINK_213EKR INT,
		  @LINK_211EKR INT,
		  @TARIF TINYINT,
		  @SHOW_212 TINYINT,
		  @LINK_EKR_ADD INT
		
		  
SET @TARIF = ISNULL((SELECT TOP 1 ENVD FROM dbo.SAL_SFIN WHERE LINK = @LinkVKR),0) + 1	
		  
SET @LINK_211EKR = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '211')
SET @LINK_EKR_ADD = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '212')
SET @LINK_213EKR = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '213')
SET @FlagMS = 1
SET @SHOW_212 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_3')

IF @SHOW_212 = 1 OR @LINK_EKR <> @LINK_211EKR
	SET @LINK_EKR_ADD = @LINK_EKR

DECLARE @DATE_BEG DATETIME
SET @DATE_BEG = dbo.convertDMY2Date(1,@Month,@Year)
SET @DATE1 = dbo.DateEndOfMonth(@DATE_BEG)

DECLARE @DATE_YEAR_BEG DATETIME
SET @DATE_YEAR_BEG = dbo.convertDMY2Date(1,1,@Year)

SELECT @linkFace = @linkPers 

DECLARE @T1 TABLE
([NUM]			[int],
 [SUMMA]		[numeric](19,2),
 [SUMMA_VKR]		[numeric](19,2),
 [SUMMA_M]		[numeric](19,2),
 [SUMMA_M_VKR]		[numeric](19,2))


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

declare @linkEmpl int,  @Pred_Mesto_Rab numeric(15,2), 	  @FlagD int

Set @linkEmpl = (Select top 1 link from dbo.empl where PERS_LINK = @linkPers)

---------------------------------------------------
DECLARE @item_move TABLE (LINK INT, EMPL_LINK INT, STAFF_LINK INT, DATE_BEGIN DATETIME, DATE_END DATETIME, NUM_STAKE NUMERIC(5,3), active TINYINT, NEW_FACE TINYINT, [STATUS] TINYINT)
INSERT INTO @item_move (LINK, EMPL_LINK, STAFF_LINK, DATE_BEGIN, DATE_END, NUM_STAKE, active, NEW_FACE, [STATUS])
Select 
	P1.LINK, P1.EMPL_LINK, P1.STAFF_LINK, P1.DATE_BEGIN, P1.DATE_END, P1.NUM_STAKE, P1.active, P1.NEW_FACE, P1.[STATUS]
from 
	dbo.empl e INNER JOIN dbo.item_move P1 ON P1.EMPL_LINK = e.link
WHERE
	E.DEP_LINK = @DEP_LINK AND E.PERS_LINK	= @linkPers
---------------------------------------------------

--Информация о размере ставок по каждому табельному номеру
DECLARE @NUM_STAKE TABLE (LINK_EMPL INT, NUM_STAKE NUMERIC(18,4), DATE_BEG DATETIME, DATE_END DATETIME)
INSERT INTO @NUM_STAKE (LINK_EMPL, NUM_STAKE, DATE_BEG, DATE_END)
SELECT DISTINCT
	EMPL_LINK, NUM_STAKE, DATE_BEGIN, DATE_END 
FROM @item_move
WHERE active = 1 AND NEW_FACE <> 3 AND @DATE1 BETWEEN DATE_BEGIN AND DATE_END

if @FlagShow = 1 
	select 'Сотрудник:  '+ LTRIM(RTRIM(P.FM)) + ' ' + SUBSTRING(LTRIM(RTRIM(P.IM)),1,1) + '.' + SUBSTRING(LTRIM(RTRIM(P.OT)),1,1)
		+  ', месяц ' + convert(varchar(2),@Month)+ ', год ' +convert(varchar(4),@Year) as [Исходные данные],
		[Отчисление] = (select rtrim(name) from pays where link =@RefPay)  FROM dbo.PERSON P where link = @linkFace


DECLARE @NASTR TABLE
([LINK_MINROT] 	[int],
 [REF_PAY]			[int],
 [CODE]				[varchar](5),
 [NAME]				[varchar](254),
 [PREDEL]			[numeric](19, 2))

INSERT INTO @NASTR([LINK_MINROT],[REF_PAY],[CODE],[NAME],[PREDEL])
SELECT [LINK_MINROT],[REF_PAY],[CODE],[NAME],[PREDEL] FROM dbo.Salary_deduct_esn(@DATE1)

SELECT @Pred_Mesto_Rab = 0, @FlagD = 0

IF dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_6 ') = 1
BEGIN
	IF YEAR(dbo.kd_DateBeginWork(@linkEmpl,null)) = @Year
	BEGIN
		SET @Pred_Mesto_Rab = (SELECT ISNULL(SUM(SUMMA_DED),0) FROM dbo.SD_EMPL_PREV_DED WHERE LINK_EMPL = @linkEmpl and LINK_DED in (select REF_PAY from @NASTR))
		IF @Pred_Mesto_Rab IS null or @Pred_Mesto_Rab < 0
			SET @Pred_Mesto_Rab = 0
		SET @FlagD = 1
		
		IF  @FlagShow = 1 
			SELECT 'Совокупный доход: '+ rtrim(isnull(convert(varchar(100),(select sum(summa_TYP_INCOMS) from dbo.SD_EMPL_PREV_DOHOD where link_empl =@linkEmpl)),'0')) + ' , вычеты: '+
			 rtrim( isnull( convert(varchar(100),(select sum(summa_ded) from dbo.SD_EMPL_PREV_DED where link_empl =@linkEmpl and LINK_DED in (select REF_PAY from @NASTR) )),'0'))  as 'Данные с предыдущего места работы'
	END
END	

---Учитываются доходы по договорам ГПХ в данной организации, чтобы правильно применить регрессионную шкалу---
DECLARE @SUM_DGH numeric(15,2)
SET @SUM_DGH = 
	ISNULL(
	(
	SELECT SUM(GT.SUMMA_BASE)
	FROM dbo.DOCUMENTS_DGH G INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
	WHERE FLAG_JC = 1
			AND YEAR(G.[DATE]) = @Year
			AND MONTH(G.[DATE]) <= @Month
			AND G.LINK_DEP = @DEP_LINK
			AND GT.LINK_PAY = @RefPay
			AND GT.PERS_LINK = @linkFace
	),0)

IF @SUM_DGH <> 0 AND @FlagShow = 1 
	SELECT 'Совокупный доход: '+ rtrim(isnull(convert(varchar(100),@SUM_DGH),'0')) as 'Доход по договорам ГПХ'


CREATE TABLE #PERIODY (LINK_EMPL INT, TAB VARCHAR(10), NUM_STAKE NUMERIC(18,4), POSTNAME VARCHAR(50), st_date1 datetime, st_date2 datetime, im_date1 datetime, im_date2 datetime, [COD_SPO_USL_TRUD] int)

---------------------------------------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC IN (10,11) AND LINK = @RefPay)
BEGIN

	--sa_item_move
	--	
	DECLARE @sa_item_move TABLE (EMPL_LINK INT, STAFF_LINK INT, DATE_BEGIN DATETIME, DATE_END3 DATETIME, NUM_STAKE NUMERIC(5,3), [STATUS] TINYINT )

	INSERT INTO @sa_item_move (EMPL_LINK, STAFF_LINK, DATE_BEGIN, DATE_END3, NUM_STAKE, [STATUS])
	Select 
		P1.EMPL_LINK, P1.STAFF_LINK, P1.DATE_BEGIN, date_end3 = min(P2.date_begin) - 1, P1.NUM_STAKE, P1.[STATUS]
	from 
		dbo.empl e
		INNER JOIN @item_move P1 ON P1.EMPL_LINK = e.link
		INNER JOIN @item_move P2 on P1.EMPL_LINK = P2.EMPL_LINK
	where
		E.PERS_LINK	= @linkPers 
		AND P1.active = 1 AND P2.active = 1 AND P1.NEW_FACE <> 3 AND P2.NEW_FACE <> 3
		AND P1.[date_begin] < P2.[date_begin] 
	group by 
		P1.EMPL_LINK, P1.STAFF_LINK, P1.DATE_BEGIN, P1.NUM_STAKE, P1.[STATUS]

	INSERT INTO @sa_item_move (EMPL_LINK, STAFF_LINK, DATE_BEGIN, DATE_END3, NUM_STAKE, [STATUS])
	Select 
		P3.EMPL_LINK, P3.STAFF_LINK, P3.DATE_BEGIN, date_end3 = '99991231', P3.NUM_STAKE, P3.[STATUS]
	from
		dbo.empl e 
		INNER JOIN @item_move P3 ON P3.EMPL_LINK = e.link
	where
		E.PERS_LINK	= @linkPers  
		AND
		P3.active = 1 AND P3.NEW_FACE <> 3
		AND
		NOT EXISTS (
					Select *
					from 
						@item_move P1 inner join @item_move P2 on P1.EMPL_LINK = P2.EMPL_LINK
					where
						P1.LINK = P3.link
						AND P1.active = 1 and P2.active = 1 AND P1.NEW_FACE <> 3 AND P2.NEW_FACE <> 3
						and P1.[date_begin] < P2.[date_begin] 
					)
	-----------------------------------------------------------------------------------------------------

	CREATE TABLE #ADD_TYPE (
		[type] INT IDENTITY(1,1),
		[TERR_USL_TRUD] int NULL ,
		[TERR_RK] numeric(3, 2) NULL ,
		[OSOB_USL_TRUD] int NULL ,
		[COD_POS_SPISOK] int NULL ,
		[COD_POS_SPISOK2] int NULL ,
		[USL_DOSROCH_PENS] int NULL ,
		[STAVKA_PED_MED] numeric(3, 2) NULL,
		[COD_SPO_USL_TRUD] int NULL
	)

	INSERT INTO #ADD_TYPE 
	SELECT DISTINCT ISNULL(TERR_USL_TRUD,0), ISNULL(TERR_RK,0), ISNULL(OSOB_USL_TRUD,0), ISNULL(COD_POS_SPISOK,0), ISNULL(COD_POS_SPISOK2,0), ISNULL(USL_DOSROCH_PENS,0), ISNULL(STAVKA_PED_MED,0), ISNULL([COD_SPO_USL_TRUD],0)
	FROM dbo.staff
	WHERE ISNULL(COD_POS_SPISOK,0) <> 0 OR ISNULL(COD_POS_SPISOK2,0) <> 0

	INSERT INTO 
		#PERIODY (LINK_EMPL, TAB, NUM_STAKE, POSTNAME, st_date1, st_date2, im_date1, im_date2, [COD_SPO_USL_TRUD])
	SELECT DISTINCT
		E.LINK, TAB,
		IM.NUM_STAKE,
		LEFT(PT.NAME,50),
		st_date1 = dbo.DateBeginOfMonth((case when st.DATE_BEGIN >= @DATE_YEAR_BEG then st.DATE_BEGIN else @DATE_YEAR_BEG end)),
		st_date2 = dbo.DateEndOfMonth((case when coalesce(st.DATE_END,@DATE1) <= @DATE1 then coalesce(st.DATE_END,@DATE1) else @DATE1 end)	),
		im_date1 = dbo.DateBeginOfMonth((case when im.DATE_BEGIN >= @DATE_YEAR_BEG then im.DATE_BEGIN else @DATE_YEAR_BEG end)),
		im_date2 = dbo.DateEndOfMonth( 
							CASE WHEN COALESCE(U.DIS_DATE,'20990101') <= (case when ISNULL(ISNULL(U.DIS_DATE,im.DATE_END3),@DATE1) <= @DATE1 then ISNULL(ISNULL(U.DIS_DATE,im.DATE_END3),@DATE1) else @DATE1 end)
								THEN COALESCE(U.DIS_DATE,'20990101')
								ELSE (case when ISNULL(ISNULL(U.DIS_DATE,im.DATE_END3),@DATE1) <= @DATE1 then ISNULL(ISNULL(U.DIS_DATE,im.DATE_END3),@DATE1) else @DATE1 end)
							END	),
		T.[COD_SPO_USL_TRUD]							
	FROM 
		dbo.empl e
		INNER JOIN @sa_item_move im ON im.EMPL_LINK = e.link
		inner join dbo.staff_head sh on sh.link = STAFF_LINK
		inner join dbo.staff st on st.link_up = sh.link
		INNER JOIN dbo.POST PT ON PT.LINK = st.post_link
		INNER join #ADD_TYPE T on ISNULL(st.TERR_USL_TRUD,0) = ISNULL(T.TERR_USL_TRUD,0) 
								AND ISNULL(st.TERR_RK,0) = ISNULL(T.TERR_RK,0) 
								AND ISNULL(st.OSOB_USL_TRUD,0) = ISNULL(T.OSOB_USL_TRUD,0) 
								AND ISNULL(st.COD_POS_SPISOK,0) = ISNULL(T.COD_POS_SPISOK,0) 
								AND ISNULL(st.COD_POS_SPISOK2,0) = ISNULL(T.COD_POS_SPISOK2,0) 
								AND ISNULL(st.USL_DOSROCH_PENS,0) = ISNULL(T.USL_DOSROCH_PENS,0) 
								AND ISNULL(st.STAVKA_PED_MED,0) = ISNULL(T.STAVKA_PED_MED,0)
								AND ISNULL(st.COD_SPO_USL_TRUD,0) = ISNULL(T.COD_SPO_USL_TRUD,0)
		LEFT JOIN dbo.ITEM_DIS_FACE U on E.link = U.empl_link AND U.ACTIVE=1	
	where
		E.PERS_LINK	= @linkPers
		and  
		im.DATE_BEGIN <= @DATE1 and im.DATE_END3 >= @DATE_YEAR_BEG
		AND
		IM.[STATUS] <> 2 --Совместителям доп. тариф не считаем
		and 
		st.DATE_BEGIN <= @DATE1 and st.DATE_END >= @DATE_YEAR_BEG
		AND
		T.[TYPE] IS NOT NULL
		AND
		(
			ISNULL(T.[COD_POS_SPISOK],0) <> 0 AND EXISTS (SELECT * FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 AND LINK = @RefPay)
			OR
			ISNULL(T.[COD_POS_SPISOK2],0) <> 0 AND EXISTS (SELECT * FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 AND LINK = @RefPay)	
		)	

	if @FlagShow = 1 
		SELECT DISTINCT TAB AS [Таб_номер],  LEFT(dbo.ku_GetEmplSubdivName(LINK_EMPL,@DATE1),50) AS [Отдел], POSTNAME AS [Должность], CONVERT(VARCHAR(10), ST_DATE1, 104) AS 'Нач_пер_с_вредн_ШР', CONVERT(VARCHAR(10),ST_DATE2,104) AS 'Оконч_пер_с_вредн_ШР' FROM #PERIODY
			
	if @FlagShow = 1 
		SELECT DISTINCT TAB AS [Таб_номер],  NUM_STAKE AS [Кол-во ставок], LEFT(dbo.ku_GetEmplSubdivName(LINK_EMPL,@DATE1),50) AS [Отдел], POSTNAME AS [Должность], CONVERT(VARCHAR(10), IM_DATE1, 104) AS 'Нач_пер_с_вредн_должность', CONVERT(VARCHAR(10),IM_DATE2,104) AS 'Оконч_пер_с_вредн_должность', CASE WHEN NUM_STAKE < 1 THEN 'Доп. тариф не начисляется, т.к. не полный день' ELSE '' END AS [Примечание]
		FROM #PERIODY
	
	INSERT INTO @T1 ([NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR])
	SELECT M.NUM,SUM(SJ.SUMMA) AS SUMMA, 			
			 [SUMMA_VKR]	= SUM(CASE WHEN SJ.LINK_VKR = @LinkVKR AND SJ.LINK_EKR IN (@LINK_EKR,@LINK_EKR_ADD) THEN SJ.SUMMA ELSE 0 END),
			 [SUMMA_M] 		= SUM(CASE WHEN MONTH(SJ.PERIOD_BEGIN) = M.NUM THEN SJ.SUMMA ELSE 0 END),
			 [SUMMA_M_VKR] = SUM(CASE WHEN (MONTH(SJ.PERIOD_BEGIN) = M.NUM) AND (SJ.LINK_VKR = @LinkVKR AND SJ.LINK_EKR  IN (@LINK_EKR,@LINK_EKR_ADD)) THEN SJ.SUMMA ELSE 0 END)
	FROM 
		dbo.MONTHS M
		INNER JOIN dbo.EMPL E ON 1=1
		INNER JOIN dbo.CALCULATE_JURNAL SJ ON SJ.LINK_EMPL = E.LINK
		INNER JOIN dbo.TAX_REF TR ON TR.LINK_PAYS =  SJ.LINK_PAYS
	WHERE 
		E.PERS_LINK = @linkFace
		AND (M.NUM <= @Month) 
		AND (MONTH(SJ.PERIOD_BEGIN) <= M.NUM) 
		AND (YEAR(SJ.PERIOD_BEGIN) = @Year)
		AND TR.LINK_TAX = @RefPay 
		AND EXISTS (SELECT * FROM #PERIODY P WHERE P.NUM_STAKE >=1 
												AND P.LINK_EMPL = SJ.LINK_EMPL 
												AND SJ.PERIOD_BEGIN <= P.ST_DATE2 
												AND SJ.PERIOD_END >= P.ST_DATE1 
												AND SJ.PERIOD_BEGIN <= P.IM_DATE2 
												AND SJ.PERIOD_END >= P.IM_DATE1)
	GROUP BY  M.NUM	

	
END
---------------------------------------------------------------------------------------------------------------
ELSE
	INSERT INTO @T1 ([NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR])
	SELECT M.NUM,SUM(SJ.SUMMA) AS SUMMA, 			
			 [SUMMA_VKR]	= SUM(CASE WHEN SJ.LINK_VKR = @LinkVKR AND SJ.LINK_EKR IN (@LINK_EKR,@LINK_EKR_ADD) THEN SJ.SUMMA ELSE 0 END),
			 [SUMMA_M] 		= SUM(CASE WHEN MONTH(SJ.PERIOD_BEGIN) = M.NUM THEN SJ.SUMMA ELSE 0 END),
			 [SUMMA_M_VKR] = SUM(CASE WHEN (MONTH(SJ.PERIOD_BEGIN) = M.NUM) AND (SJ.LINK_VKR = @LinkVKR AND SJ.LINK_EKR  IN (@LINK_EKR,@LINK_EKR_ADD)) THEN SJ.SUMMA ELSE 0 END)
	FROM 
		dbo.MONTHS M
		INNER JOIN dbo.CALCULATE_JURNAL SJ ON 1=1 
		INNER JOIN dbo.TAX_REF TR ON TR.LINK_PAYS =  SJ.LINK_PAYS
		INNER JOIN dbo.EMPL E ON SJ.LINK_EMPL = E.LINK
	WHERE 
		(TR.LINK_TAX = @RefPay) 
		AND (E.PERS_LINK = @linkFace) 
		AND (MONTH(SJ.PERIOD_BEGIN) <= M.NUM) AND (M.NUM <= @Month) AND (YEAR(SJ.PERIOD_BEGIN)=@Year)
		AND sj.LINK_DEP = @DEP_LINK
	GROUP BY  M.NUM


if @FlagShow = 1 
	SELECT [num] as [Месяц], [summa] as [Сумма с нач года],summa_vkr as [Сумма с нач года по ВКР/ЕКР], summa_m as [Сумма за месяц], 
	summa_m_vkr as [Сумма за месяц по ВКР/ЕКР]  FROM @T1

--Если суммы, которые раньше были в базе убрали из базы, теперь базовой суммы вообще нет
IF NOT EXISTS(SELECT * FROM @T1)
	INSERT INTO @T1 ([NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR])
	VALUES(@Month, 0, 0, 0, 0)

DECLARE @Temp1_1 TABLE
([NUM]			[int],
 [LINK_PAYS]	[int],
 [MP]				[numeric](19,2),
 [MP_M]			[numeric](19,2),
 [MP_M_VKR]		[numeric](19,2))

--------------------------------------------------
CREATE TABLE #DICTIONARY_TYP_INCOMS (LINK INT)
INSERT INTO #DICTIONARY_TYP_INCOMS (LINK)
SELECT LINK FROM dbo.DICTIONARY_TYP_INCOMS WHERE EXISTS (SELECT * FROM @NASTR WHERE REF_PAY = REF_DEDUCT)
CREATE INDEX #DICTIONARY_TYP_INCOMS_IDX1 ON #DICTIONARY_TYP_INCOMS (LINK)

-------------------------------------------------
CREATE TABLE #PAYS (LINK INT)
INSERT INTO #PAYS (LINK)
SELECT P.LINK FROM dbo.PAYS P INNER JOIN #DICTIONARY_TYP_INCOMS I ON I.LINK = P.LINK_INC
CREATE INDEX #PAYS_IDX1 ON #PAYS (LINK)


--------------------------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC IN (10,11) AND LINK = @RefPay)
	
	INSERT INTO @Temp1_1 ([NUM],[LINK_PAYS],[MP],[MP_M],[MP_M_VKR])
	SELECT M.NUM,
			 [LINK_PAYS]= (SELECT LINK_INC  from pays where link = sj.LINK_PAYS),
			 [MP] 		= SUM(CASE WHEN month(SJ.PERIOD_BEGIN)<=m.num then SJ.summa else 0 end), 
			 [MP_M] 		= SUM(CASE WHEN month(SJ.PERIOD_BEGIN)=m.num then (CASE WHEN month(SJ.PERIOD_BEGIN)<=m.num then SJ.summa else 0 end) else 0 end),
			 [MP_M_VKR] = SUM(CASE WHEN ( month(SJ.PERIOD_BEGIN)=m.num)AND(sj.link_vkr = @LinkVKR AND SJ.LINK_EKR  IN (@LINK_EKR,@LINK_EKR_ADD)) 
								THEN (CASE WHEN month(SJ.PERIOD_BEGIN)<=m.num then SJ.summa else 0 end) else 0 end)
	FROM 
		dbo.MONTHS M 
		INNER JOIN dbo.S_J_C_Short SJ ON 1=1 
		INNER JOIN #PAYS P ON P.LINK = SJ.LINK_PAYS
		INNER JOIN dbo.TAX_REF TR ON TR.LINK_PAYS =  SJ.LINK_PAYS
	WHERE 
		TR.LINK_TAX = @RefPay 
		AND (SJ.LINK_FACE = @linkFace)
		AND YEAR(SJ.PERIOD_BEGIN)=@Year AND M.NUM <= @Month 
		AND sj.LINK_DEP = @DEP_LINK
		AND EXISTS (SELECT * FROM #PERIODY P WHERE P.LINK_EMPL = SJ.LINK_EMPL AND SJ.PERIOD_BEGIN <= P.ST_DATE2 AND SJ.PERIOD_END >= P.ST_DATE1)		
		AND EXISTS (SELECT * FROM #PERIODY P WHERE P.LINK_EMPL = SJ.LINK_EMPL AND P.NUM_STAKE >=1 AND SJ.PERIOD_BEGIN <= P.IM_DATE2 AND SJ.PERIOD_END >= P.IM_DATE1)		
	GROUP BY 
		M.NUM,SJ.LINK_PAYS
ELSE
	INSERT INTO @Temp1_1 ([NUM],[LINK_PAYS],[MP],[MP_M],[MP_M_VKR])
	SELECT M.NUM,
			 [LINK_PAYS]= (SELECT LINK_INC  from pays where link = sj.LINK_PAYS),
			 [MP] 		= SUM(CASE WHEN month(SJ.PERIOD_BEGIN)<=m.num then SJ.summa else 0 end), 
			 [MP_M] 		= SUM(CASE WHEN month(SJ.PERIOD_BEGIN)=m.num then (CASE WHEN month(SJ.PERIOD_BEGIN)<=m.num then SJ.summa else 0 end) else 0 end),
			 [MP_M_VKR] = SUM(CASE WHEN ( month(SJ.PERIOD_BEGIN)=m.num)AND(sj.link_vkr = @LinkVKR AND SJ.LINK_EKR  IN (@LINK_EKR,@LINK_EKR_ADD)) 
								THEN (CASE WHEN month(SJ.PERIOD_BEGIN)<=m.num then SJ.summa else 0 end) else 0 end)
	FROM 
		dbo.MONTHS M 
		INNER JOIN dbo.S_J_C_Short SJ ON 1=1
		INNER JOIN #PAYS P ON P.LINK = SJ.LINK_PAYS
		INNER JOIN dbo.TAX_REF TR ON TR.LINK_PAYS =  SJ.LINK_PAYS
	WHERE 
		TR.LINK_TAX = @RefPay 
		AND (SJ.LINK_FACE = @linkFace)
		AND YEAR(SJ.PERIOD_BEGIN)=@Year AND M.NUM <= @Month 
		AND sj.LINK_DEP = @DEP_LINK
	GROUP BY 
		M.NUM,SJ.LINK_PAYS
	

/*if @FlagShow = 1  
	select *  from @Temp1_1*/

DECLARE @Temp1 TABLE
([NUM]			[int],
 [LINK_PAYS]	[int],
 [PREDEL]		[numeric](19,2),
 [MP]				[numeric](19,2),
 [MP_M]			[numeric](19,2),
 [MP_M_VKR]		[numeric](19,2))

INSERT INTO @Temp1 ([NUM],[LINK_PAYS],[PREDEL],[MP],[MP_M],[MP_M_VKR])
SELECT NUM,LINK_PAYS,
		[PREDEL] =  ISNULL((SELECT TOP 1 PREDEL FROM @NASTR 
								WHERE REF_PAY = (SELECT TOP 1 REF_DEDUCT FROM dbo.DICTIONARY_TYP_INCOMS WHERE LINK = LINK_PAYS)),0),
		SUM(MP) AS MP,
		SUM(MP_M) AS MP_M, 
		SUM(MP_M_VKR) AS MP_M_VKR
FROM @Temp1_1
GROUP BY NUM,LINK_PAYS

DECLARE @Temp2 TABLE
([NUM]			[int],
 [LINK_PAYS]	[int],
 [PREDEL]		[numeric](19,2),
 [MP]				[numeric](19,2),
 [MP_M]			[numeric](19,2),
 [MP_M_VKR]		[numeric](19,2),
 [SALDO]			[numeric](19,2),
 [KOEF]			[numeric](19,2))

---


INSERT INTO @Temp2 ([NUM],[LINK_PAYS],[PREDEL],[MP],[MP_M],[MP_M_VKR],[SALDO],[KOEF]) 
SELECT T1.[NUM],T1.[LINK_PAYS],T1.[PREDEL],T1.[MP],T1.[MP_M],T1.[MP_M_VKR],
		 [SALDO] = (CASE WHEN @Pred_Mesto_Rab + ISNULL((SELECT SUM(MP_M) FROM @Temp1 T2 WHERE T2.NUM <= T1.NUM AND T2.LINK_PAYS = T1.LINK_PAYS),0) > PREDEL
				THEN PREDEL
				ELSE @Pred_Mesto_Rab + ISNULL((SELECT SUM(MP_M) FROM @Temp1 T2 WHERE T2.NUM <= T1.NUM AND T2.LINK_PAYS = T1.LINK_PAYS),0)
				END)
				- (CASE WHEN @Pred_Mesto_Rab + ISNULL((SELECT SUM(MP_M) FROM @Temp1 T2 WHERE T2.NUM < T1.NUM AND T2.LINK_PAYS = T1.LINK_PAYS),0) > PREDEL
				THEN PREDEL
				ELSE @Pred_Mesto_Rab + ISNULL((SELECT SUM(MP_M) FROM @Temp1 T2 WHERE T2.NUM < T1.NUM AND T2.LINK_PAYS = T1.LINK_PAYS),0)
				END),
		 [KOEF] 	= (CASE WHEN (SELECT SUM(MP_M) FROM @Temp1 T3 WHERE T3.NUM = T1.NUM AND T3.LINK_PAYS = T1.LINK_PAYS) = 0 
						THEN 0 ELSE (CASE WHEN (SELECT SUM(MP_M) 
				                         FROM @Temp1 T3 WHERE T3.NUM = T1.NUM AND T3.LINK_PAYS = T1.LINK_PAYS)= 0 
										  THEN 0 ELSE 										
											MP_M_VKR/(SELECT SUM(MP_M) 
                    				     FROM @Temp1 T3 WHERE T3.NUM = T1.NUM AND T3.LINK_PAYS = T1.LINK_PAYS) END) END)
FROM @Temp1 T1


declare @predel numeric(18,2)
Set @predel = COALESCE((SELECT TOP 1 PREDEL FROM @Temp1),0)


DECLARE @Temp3 TABLE
([NUM]			[int],
 [LINK_PAYS]	[int],
 [SUMMA]			[numeric](19,2),
 [SUMMA_ALL]	[numeric](19,2),
 [SUMMA_M]		[numeric](19,2),
 [SUMMA_M_VKR]		[numeric](19,2)
)

INSERT INTO @Temp3 ([NUM],[LINK_PAYS],[SUMMA],[SUMMA_ALL],[SUMMA_M], SUMMA_M_VKR)
SELECT  T.[NUM], T.[LINK_PAYS],
		  [SUMMA] 	= dbo.IS_MIN((SELECT SUM(T3.SALDO * KOEF) FROM @Temp2 T3 WHERE  T3.NUM <= T.NUM AND T3.LINK_PAYS = T.LINK_PAYS),T.PREDEL), 
		  [SUMMA_ALL] 	= dbo.IS_MIN((SELECT SUM(T3.SALDO) FROM @Temp2 T3 WHERE  T3.NUM <= T.NUM AND T3.LINK_PAYS = T.LINK_PAYS),T.PREDEL),
		  [SUMMA_M] 	= CASE WHEN ABS(SUM(MP_M)) < ABS(T.SALDO) THEN ABS(T.SALDO) ELSE T.SALDO END,
		SUMMA_M_VKR 	= CASE WHEN ABS(SUM(MP_M)) < ABS(T.SALDO) THEN ABS(T.SALDO) ELSE T.SALDO END * KOEF
FROM @Temp2 T --WHERE SALDO > 0
GROUP BY T.NUM,T.PREDEL,T.SALDO,T.LINK_PAYS, KOEF 
ORDER BY T.NUM

if @FlagShow = 1  
	select num as [Месяц], LINK_PAYS as [Вычет], summa as [Скидка по ВКР/ЕКР], summa_all as [Скидка с начала года], summa_m as [Скидка за месяц]  from @Temp3


DECLARE @PREDEL_INV [numeric](15, 2)
SET @PREDEL_INV = ISNULL((SELECT TOP 1 PREDEL FROM dbo.DICTIONARY_MROT_TABLE3 DMT 
									WHERE LINK_MINROT = (SELECT TOP 1 LINK FROM dbo.DICTIONARY_MROT 
									WHERE PERIOD <=@DATE1 ORDER BY PERIOD DESC) AND (REF_PAY = @RefPay)),0)

DECLARE @T2_1 TABLE
([NUM]			[int],
 [SUMMA]			[numeric](19, 2),
 [SUMMA_VKR]	[numeric](19, 2),
 [SUMMA_M]		[numeric](19, 2),
 [SUMMA_M_VKR]	[numeric](19, 2),
 [MP]				[numeric](19, 2),
 [MP_VKR]		[numeric](19, 2),
 [MP_M]			[numeric](19, 2),
 [MP_M_VKR]		[numeric](19, 2),
 [STATUS]		[int],
 [INV]			[numeric](19, 2))


INSERT INTO @T2_1 ([NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR],[MP],[MP_VKR],[MP_M],[MP_M_VKR],[STATUS],[INV])
SELECT T1.[NUM],T1.[SUMMA],T1.[SUMMA_VKR],T1.[SUMMA_M],T1.[SUMMA_M_VKR],
--		 [MP] 		= ISNULL((SELECT SUM(SUMMA) FROM @Temp3 T WHERE T.NUM <= T1.NUM),0),  
		 [MP] 		= ISNULL((SELECT SUM(SUMMA_ALL) FROM @Temp3 T WHERE T.NUM = T1.NUM),0),  
		 [MP_VKR]	= ISNULL((SELECT SUM(SUMMA) FROM @Temp3 T WHERE T.NUM = T1.NUM),0),  
		 [MP_M] 	= ISNULL((SELECT SUM(SUMMA_M) FROM @Temp3 T WHERE T.NUM = T1.NUM),0),  
		 [MP_M_VKR] = ISNULL((SELECT SUM(SUMMA_M_VKR) FROM @Temp3 T WHERE T.NUM = T1.NUM),0),  
--		 [MP_M_VKR] = ISNULL((SELECT SUM(SUMMA) FROM @Temp3 T WHERE T.NUM = T1.NUM),0),  
		 [STATUS] 	= dbo.is_invalid(@linkFace,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,T1.NUM,@Year))), 
		 [INV] 		= cast(0 as numeric(15,2))
FROM @T1 T1 
GROUP BY T1.NUM,T1.SUMMA,T1.SUMMA_VKR,T1.SUMMA_M,T1.SUMMA_M_VKR
ORDER BY T1.NUM


DECLARE @summa_m 	[numeric](15, 2), 
		  @mp_m 		[numeric](15, 2),
		  @num 		[int], 
		  @Flag 		[bit], 
		  @itog 		[numeric](15, 2)

SET @itog = 0
DECLARE TMP_CUR CURSOR
FOR SELECT SUMMA_M, MP_M,NUM FROM @T2_1 WHERE STATUS = 2
OPEN TMP_CUR
FETCH TMP_CUR INTO @summa_m,@mp_m,@num
WHILE (@@FETCH_STATUS  = 0) AND (@PREDEL_INV - @itog) > 0 BEGIN
	IF @PREDEL_INV < (@itog+ @summa_m - @mp_m)
		UPDATE @T2_1 SET INV =(@PREDEL_INV-@itog) WHERE NUM = @num
	ELSE
		UPDATE @T2_1 SET INV =(@summa_m - @mp_m) WHERE NUM = @num
	
	SET @itog = @itog + @summa_m - @mp_m
	FETCH TMP_CUR INTO @summa_m,@mp_m,@num
END
CLOSE TMP_CUR
DEALLOCATE TMP_CUR

-- Другие льготы за месяц помимо инвалидов
---Вычеты от удержаний
select 
	TA.LINK_DED, MON = MONTH(CJ.PERIOD_BEGIN),
	SUMMA_G = CAST(0 AS NUMERIC(18,2)),
	SUMMA_M = SUM(SUMMA),
	LIMIT = ISNULL((SELECT TOP 1 PREDEL FROM @NASTR WHERE REF_PAY = TA.LINK_DED),0)
INTO #DED_U
from 
	dbo.EMPL E inner join dbo.calculate_jurnal cj on e.link = cj.link_empl
	inner join dbo.TAX2_APP TA on TA.LINK_UP = CJ.LINK_PAYS
where 
	cj.LINK_DEP = @DEP_LINK
	AND
	year(period_begin) = @Year
	and
	E.PERS_LINK = @linkPers	
	and 
	MONTH(cj.PERIOD_BEGIN) <= @Month
	and
	ISNULL(TA.LINK_DED,0) > 0
GROUP BY 
	TA.LINK_DED, MONTH(CJ.PERIOD_BEGIN)


UPDATE A
SET SUMMA_G = (SELECT SUM(SUMMA_M) FROM #DED_U B WHERE B.MON <= A.MON )
FROM #DED_U A

UPDATE #DED_U
SET 
	SUMMA_G = CASE WHEN ISNULL(SUMMA_G,0) < ISNULL(LIMIT,0) THEN ISNULL(SUMMA_G,0) ELSE ISNULL(LIMIT,0) END,
	SUMMA_M = CASE WHEN ISNULL(SUMMA_G,0) < ISNULL(LIMIT,0) THEN ISNULL(SUMMA_M,0)
				ELSE 
					CASE WHEN ISNULL(LIMIT,0) - (ISNULL(SUMMA_G,0) - ISNULL(SUMMA_M,0)) > 0 THEN 
						ISNULL(LIMIT,0) - (ISNULL(SUMMA_G,0) - ISNULL(SUMMA_M,0))
					ELSE 0
					END
			  END

UPDATE @T2_1 SET INV = ISNULL(INV,0) + ISNULL((SELECT SUM(SUMMA_M) FROM #DED_U WHERE MON = NUM),0)

--Расчет налога
--
DECLARE @T2 TABLE 
([NUM]				[int],
 [SUMMA]			[numeric](19, 2),
 [SUMMA_VKR]		[numeric](19, 2),
 [SUMMA_M]			[numeric](19, 2),
 [SUMMA_M_VKR]		[numeric](19, 2),
 [MP]				[numeric](19, 2),
 [MP_VKR]			[numeric](19, 2),
 [MP_M]				[numeric](19, 2),
 [MP_M_VKR]			[numeric](19, 2),
 [STATUS]			[int],
 [INV]				[numeric](19, 2),
 [INV_VKR]			[numeric](19, 2),
 [TARIF]			[TINYINT],
 [SPECO] [INT]
  ) -- Категория тарифа

INSERT INTO @T2 ([NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR],[MP],[MP_VKR],[MP_M],[MP_M_VKR],[STATUS],[INV],[INV_VKR],[TARIF],[SPECO])
SELECT [NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR],[MP],[MP_VKR],[MP_M],[MP_M_VKR],[STATUS],[INV],
		 [INV_VKR] = (CASE WHEN (SUMMA_M - MP_M) = 0 THEN 0 ELSE (SUMMA_M_VKR - MP_M_VKR)*INV/(SUMMA_M - MP_M) END),
		 TARIF = CASE WHEN dbo.is_invalid(@linkFace,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,NUM,@Year))) = 2 THEN 3 ELSE @TARIF END,
		 [SPECO] = (SELECT TOP 1 [COD_SPO_USL_TRUD] FROM #PERIODY 
						WHERE dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,NUM,@Year)) BETWEEN st_date1 AND st_date2
						AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,NUM,@Year)) BETWEEN im_date1 AND im_date2)
FROM 
	@T2_1

if @FlagShow = 1 
	select [num] as [Месяц], [summa] as [Сумма с Н/Г],summa_vkr as [Сумма с Н/Г по ВКР/ЕКР], summa_m as [За мес], 
	summa_m_vkr as [За мес.по ВКР/ЕКР], mp as [Ск.всего], mp_vkr as [Ск.всего по ВКР/ЕКР],mp_m as [Ск. за мес],
	mp_m_vkr as [Ск.за мес.по ВКР/ЕКР], inv as [Льготы], inv_vkr as [Льготы по ВКР/ЕКР], TARIF as [ТАРИФ], [SPECO]  from @T2


DECLARE @WAY_CALC [int]
SELECT @WAY_CALC = WAY_CALC FROM dbo.PAYS WHERE LINK = @RefPay

DECLARE @Pred table  
(
 TARIF TINYINT,	
 [PREDEL]  [numeric](15, 2), 
 [PERCENT] [numeric](8, 2),
 WAY_CALC TINYINT,
 SPECO INT,
 NSPECO VARCHAR(254) )

IF @WAY_CALC<5
	
	IF @FlagMS = 1
		INSERT INTO @Pred (TARIF, [PREDEL],[PERCENT],SPECO,NSPECO)
		SELECT TARIF, [PREDEL],[PERCENT],SPECO=0,NSPECO='' FROM dbo.DICTIONARY_RANGE D
		WHERE
			(LINK_PAYS = @RefPay) 
			AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE D1 WHERE D1.TARIF = D.TARIF AND (LINK_PAYS = @RefPay) AND DATE < @DATE1 ORDER BY [DATE] DESC) 
		ORDER BY 1 
	ELSE 
		INSERT INTO @Pred (TARIF, [PREDEL],[PERCENT],SPECO,NSPECO)
		SELECT TOP 1 TARIF, [PREDEL] = 999999999999, [PERCENT],SPECO=0,NSPECO='' 
		FROM dbo.DICTIONARY_RANGE D
		WHERE 
			(LINK_PAYS = @RefPay) 
			AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE D1 WHERE D1.TARIF = D.TARIF AND (LINK_PAYS = @RefPay) AND DATE < @DATE1 ORDER BY [DATE] DESC) 
		ORDER BY 1 
ELSE 
BEGIN	
		
	DECLARE @Sex 		[int], 
			  @YearB 	[int], 
			  @Type 		[int]

	SELECT @Sex = SEX, @YearB = CASE WHEN RESIDENT = 1 THEN ISNULL(YEAR(BIRTHDATE),0) 
												ELSE 1966 END -- иностранцы по тарифам как для 66 года и страрше
											FROM dbo.PERSON WHERE LINK =@linkFace
	SET 	@Type = (CASE WHEN (@Sex = 1 AND @YearB < 1953) OR (@Sex = 2 AND @YearB<1957) THEN 1
						WHEN (@Sex = 1 AND @YearB BETWEEN 1953 AND 1966) OR (@Sex = 2 AND  @YearB BETWEEN 1957 AND 1966) THEN 2 
						ELSE 3 END)

	IF @FlagMS = 1 
		INSERT INTO @Pred (TARIF, [PREDEL],[PERCENT],WAY_CALC,SPECO,NSPECO)
		SELECT 
			TARIF,  
			[PREDEL],
			[PERCENT] = (CASE WHEN @Type = 1 THEN PERCENT1 WHEN @Type = 2 THEN PERCENT2 ELSE PERCENT3 END),
			WAY_CALC,
			SPECO,
			NSPECO
		FROM 
			dbo.DICTIONARY_RANGE_PF D
		WHERE
			LINK_PAYS = @RefPay 
			AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE_PF D1 WHERE D1.TARIF = D.TARIF AND ISNULL(D1.SPECO,0) = ISNULL(D.SPECO,0) AND LINK_PAYS = @RefPay AND DATE < @DATE1 ORDER BY [DATE] DESC) 
		ORDER BY 1 
	ELSE 
		INSERT INTO @Pred (TARIF, [PREDEL],[PERCENT],WAY_CALC,SPECO,NSPECO)
		SELECT TOP 1 
			TARIF, 
			[PREDEL] = 999999999999,
			[PERCENT] = (CASE WHEN @Type = 1 THEN PERCENT1 WHEN @Type = 2 THEN PERCENT2 ELSE PERCENT3 END),
			WAY_CALC,
			SPECO,NSPECO
		FROM 
			dbo.DICTIONARY_RANGE_PF D
		WHERE
			LINK_PAYS = @RefPay 
			AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE_PF D1 WHERE D1.TARIF = D.TARIF AND ISNULL(D1.SPECO,0) = ISNULL(D.SPECO,0) AND LINK_PAYS = @RefPay AND DATE < @DATE1 ORDER BY [DATE] DESC) 
		ORDER BY 1 
	END

IF @FlagShow = 1 
	select TARIF as [Тариф], Predel as [Предел], [Percent] as [Процент], NSPECO AS [Спецоценка] from @Pred P
	WHERE EXISTS (SELECT * FROM @T2 B WHERE B.TARIF = P.TARIF AND ISNULL(B.[SPECO],0) = ISNULL(P.[SPECO],0))

DECLARE @res TABLE
([NUM]			[int],
 [SUMMA]		[numeric] (19, 2),
 [SUMMA_M_VKR]	[numeric] (19, 2),
 [PERC]			[numeric] (19, 2),
 [SUM_MON]		[numeric] (19, 2),
 [TARIF]		INT,
 [SPECO]		INT)

INSERT INTO @res([NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],[TARIF],[SPECO])
SELECT T7.[NUM],T7.[SUMMA],T7.[SUMMA_M_VKR],T7.[PERC], CAST(0 as numeric(15,2)) AS SUM_MON, [TARIF], [SPECO]
FROM  
	(
	SELECT 
		[NUM], 
		[SUMMA] 		 = SUMMA - MP, 
		[SUMMA_M_VKR] = SUMMA_M_VKR - MP_M_VKR,	
		[PERC] 		 = ISNULL((SELECT TOP 1 T.[PERCENT] FROM (SELECT TOP 1 * FROM @Pred P WHERE B.TARIF = P.TARIF AND ISNULL(B.SPECO,0) = ISNULL(P.[SPECO],0) AND PREDEL > (SUMMA - MP + @SUM_DGH) ORDER BY PREDEL) T),0),
		B.[TARIF],
		B.[SPECO]
	 FROM @T2	B
	 UNION
	 SELECT DISTINCT
		[NUM] 			= ISNULL((SELECT MIN(NUM) FROM @T2 B1 WHERE B1.TARIF = B.TARIF AND ISNULL(B1.[SPECO],0) = ISNULL(B.[SPECO],0) AND (SUMMA-MP+@SUM_DGH) > PREDEL),12), 
		[SUMMA] 		= PREDEL - @SUM_DGH, 
		[SUMMA_M_VKR]= 0, 
		[PERC] 		= [PERCENT],  
		B.[TARIF],
		B.[SPECO]		
 	 FROM 
 		@T2 B INNER JOIN @Pred T ON B.TARIF = T.TARIF AND ISNULL(B.[SPECO],0) = ISNULL(T.[SPECO],0)
 	 WHERE 
 		PREDEL < (SELECT TOP 1 (SUMMA - MP + @SUM_DGH) FROM @T2 B1 WHERE B1.TARIF = B.TARIF AND ISNULL(B1.[SPECO],0) = ISNULL(B.[SPECO],0) ORDER BY 1 DESC)
 	) T7


DECLARE Curs CURSOR FAST_FORWARD FOR
SELECT NUM,SUMMA FROM @res ORDER BY [NUM]  

DECLARE @Summa [numeric] (19, 2), 
	@summa_prev [numeric] (19, 2), 
	@num1 [int]


SET @summa_prev = 0
OPEN Curs
FETCH NEXT FROM Curs INTO @num1, @Summa
WHILE @@FETCH_STATUS = 0 BEGIN
	UPDATE @res SET SUM_MON = @Summa - @summa_prev WHERE NUM = @num1 AND SUMMA = @Summa
	SET @summa_prev = @Summa
  	FETCH NEXT FROM Curs INTO @num1, @Summa
END
CLOSE Curs
DEALLOCATE Curs

DECLARE @Result1 TABLE
([NUM]			[int],
 [SUMMA]			[numeric] (19, 2),
 [SUMMA_M_VKR]	[numeric] (19, 2),
 [PERC]			[numeric] (19, 2),
 [SUM_MON]		[numeric] (19, 2),
 [SKIDKA]		[numeric] (19, 2),
 [KOEF]			[numeric] (19, 10), 
 [TARIF]		INT,
 [SPECO]		INT)


INSERT INTO @Result1 ([NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],[SKIDKA],[KOEF], [TARIF], [SPECO])
SELECT [NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],
		 [SKIDKA] = dbo.is_min(T1.SUM_MON, ISNULL((SELECT INV FROM @T2 T4  WHERE T4.NUM = T1.NUM),0)  
						- ISNULL((SELECT SUM(T3.SUM_MON) FROM @res T3 WHERE T3.NUM = T1.NUM AND T3.SUMMA < T1.SUMMA), 0)),
		 [KOEF] = (SELECT (CASE WHEN (SUMMA_M - MP_M) = 0 THEN 0 ELSE (SUMMA_M_VKR - MP_M_VKR)/(SUMMA_M - MP_M) END) FROM @T2 T2 WHERE T2.NUM = T1.NUM),
		 [TARIF], [SPECO]
FROM @res T1

DECLARE @RESULT TABLE
([NUM]			[int],
 [SUMMA]			[numeric] (19, 2),
 [SUMMA_M_VKR]	[numeric] (19, 2),
 [PERC]			[numeric] (19, 2),
 [SUM_MON]		[numeric] (19, 2),
 [SKIDKA]		[numeric] (19, 2),
 [KOEF]			[numeric] (19, 10),
 [VYCH] 		[numeric] (19, 2),
 [TARIF]		INT,
 [SPECO]		INT)

INSERT INTO @RESULT ([NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],[SKIDKA],[KOEF], [TARIF], [SPECO])
SELECT [NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],
		 [SKIDKA] = (CASE WHEN SKIDKA < 0 THEN 0 ELSE SKIDKA END),
		 [KOEF], [TARIF], [SPECO]
FROM @Result1

DECLARE @Razn 			[numeric](15, 2), 
	  @NalCurr 	[numeric](15, 2),
	  @Sum1 		[numeric](15, 2)

--Расчет с копейками
SET @NalCurr = (SELECT sum(ROUND((PERC * (COALESCE(SUM_MON,0) - COALESCE(SKIDKA,0))* COALESCE(KOEF,0)/100) * 100, 2) / 100) FROM @RESULT )

--Сумма ранее начисленного взноса
SET @Sum1 = ISNULL((SELECT SUM(SJ.SUMMA) FROM dbo.S_J_C_Short SJ 
WHERE SJ.LINK_VKR = @LinkVKR 
	--AND ( (SJ.LINK_EKR IN (@LINK_EKR,@LINK_EKR_ADD) AND @LINK_EKR <> @LINK_211EKR) OR (@LINK_EKR = @LINK_211EKR AND SJ.LINK_EKR IN (@LINK_211EKR,@LINK_213EKR)) )
	AND ( (SJ.LINK_EKR IN (@LINK_EKR,@LINK_EKR_ADD) AND @LINK_EKR <> @LINK_211EKR) OR (@LINK_EKR = @LINK_211EKR AND SJ.LINK_EKR = @LINK_EKR) )
	AND SJ.LINK_PAYS = @RefPay 
	AND (SJ.LINK_FACE = @linkFace) 
	AND MONTH_BEGIN <= @Month 
	AND YEAR_BEGIN=@Year 
	AND sj.LINK_DEP = @DEP_LINK),0)

--IF --ЕСЛИ ГОДОВОЙ ДОХОД ПО ВСЕМ ИСТОЧНИКАМ < 0
--	(SELECT SUM(SUMMA) FROM @RESULT) < 0 
--		--AND @Sum1 = 0 
--		-- И ЕСЛИ ТЕКУЩИЙ НАЛОГ ПОЛУЧАЕТСЯ < 0
--		AND @NalCurr < 0
--	SET @NalCurr = 0
	
SET @Razn = @NalCurr - @Sum1

DECLARE @FLG INT
SELECT TOP 1 @FLG = ISNULL(CONVERT(INT,VALUE),0) 
FROM S_OPTIONS WHERE OBJECT = (SELECT TOP 1 LINK FROM S_OBJECTS WHERE CODE = 'ESN_OPTIONS_FLG') AND SID IS NULL

IF @Razn <0 AND @FLG = 0
	SET @Razn=0

SELECT [SUMMA] 		= ISNULL(SUMMA_VKR,0), 
	 [SUMMA_VKR] 	= ISNULL(SUMMA_M_VKR, 0),
	 [SUM_DED] 		=	CASE WHEN ISNULL(SUMMA_VKR, 0) > 0 
						THEN
							ISNULL((SELECT TOP 1 MP_VKR FROM @T2 WHERE NUM = @Month), 0)
						ELSE 0 END,	
	 [INV_M] 		= CASE WHEN ISNULL(SUMMA_VKR, 0) > 0 
						THEN
							ISNULL((SELECT SUM(SKIDKA*KOEF) FROM @RESULT WHERE NUM = @Month),0)
						ELSE 0 END,
	 [INV] 			= CASE WHEN ISNULL(SUMMA_VKR, 0) > 0 
						THEN
							ISNULL((SELECT SUM(SKIDKA*KOEF) FROM @RESULT WHERE NUM <= @Month),0)
						ELSE 0 END,
	 [DED_M] 		= CASE WHEN ISNULL(SUMMA_VKR, 0) > 0 
						THEN
							ISNULL((SELECT TOP 1 MP_M_VKR FROM @T2 WHERE NUM = @Month), 0)
						ELSE 0 END,
	 [PERC]			= ISNULL((SELECT MIN(PERC) FROM @RESULT WHERE NUM = @Month),0),
	 [NALOG] 		= @NalCurr, 
	 [NAL_DED] 		= @Sum1, 
	 [NAL_CUR] 		= @Razn,
	 [TARIF]		= ISNULL((SELECT MIN([TARIF]) FROM @RESULT WHERE NUM = @Month),0), 
	 [SPECO]		= ISNULL((SELECT MIN([SPECO]) FROM @RESULT WHERE NUM = @Month),0),
	 [NSPECO]		= (SELECT TOP 1 CODE FROM dbo.SZV4_SPR WHERE LINK = ISNULL((SELECT MIN([SPECO]) FROM @RESULT WHERE NUM = @Month),0) )
FROM 
	@T1 
WHERE 
	NUM = @Month

SET NOCOUNT OFF




GO


GRANT EXECUTE ON dbo.[SALARY_FILL_DED_ESN_VKR] TO PUBLIC

GO


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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE dbo.SD_O_ESN_PROV

@varKSparLINK int
AS

IF (SELECT SO.CODE FROM S_OBJECTS SO,SDOC DOC WHERE DOC.LINK = @varKSparLINK AND
		 DOC.OBJECT = SO.LINK) <> 'DOCUMENTS_DEDUCT_ESN_G'
	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


DECLARE @LinkEKR213 int
SELECT @LinkEKR213 = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '213'

EXEC dbo.SALARY_SDOC_FLAG_JC @varKSparLINK,0

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,LINK_VKR,LINK_EKR,TARIF,SPECO,PROCENT)
SELECT 
		[LINK_EMPL] = T.LINK_EMPL,
		[LINK_PAYS] = T.LINK_PAY,
		[LINK_DOC] = s.LINK,
	  	[PERIOD_BEGIN] = dbo.DateBeginOfMonth(s.DATE),	
		[PERIOD_END] = dbo.DateEndOfMonth(s.DATE),	
		[DAYS] =0,
		[HOURS] = 0,
		[SUMMA_BASE] = T.SUMMA_BASE,
		[SUMMA] = T.SUMMA,
		[ORDERS] = T.ORDERS,
		[DATE_BEGIN] = dbo.DateBeginOfMonth(S.DATE_CALC), 
		[DATE_END] = dbo.DateEndOfMonth(S.DATE_CALC), 
		[LINK_DEP] = S.LINK_DEP,
		[LINK_ORG] = NULL,
		[LINK_VKR] = T.LINK_VKR,
		T.LINK_EKR,--CASE WHEN E.CODE IN ('211') THEN @LinkEKR213 ELSE T.LINK_EKR END
		T.TARIF,
		T.SPECO,
		T.PERC
FROM 
	dbo.SDOC S
	inner join dbo.SDOC_ESN_TABLE T on S.link = T.LINK_UP
	inner join dbo.USER_INFO UI on 1=1
	INNER JOIN dbo.KOSGU E ON E.LINK = T.LINK_EKR
WHERE 
	UI.SID = SUSER_SID() 
	and s.LINK = @varKSparLINK 
	and T.SUMMA<>0


EXEC dbo.SALARY_SDOC_FLAG_JC @varKSparLINK,1


IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0

GO


GRANT EXECUTE ON dbo.[SD_O_ESN_PROV] TO PUBLIC

GO

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

GO
----------------------
CREATE PROCEDURE [dbo].[RA_EXPORT_FORM_FNS_710]
 @iLINK_SAVED_FORM INT,                    -- Линк выгружаемой формы  
 @vcFILE_NAME     VARCHAR(100)='' OUTPUT,  -- Имя текстового файла  
 @iMODE            INT=1                   -- Формат: 2-внутренний, 1-минфиновский    
 AS
SET NOCOUNT ON  
SET DATEFORMAT dmy  

DECLARE @iLINK_FORM		 INT,
        @iLINK_ORG       INT, 
      	@iLINK_TABLE	 INT,
        @dBEGIN_DATE     DATETIME,
        @dFORM_DATE      DATETIME,  
        @sYear           SMALLINT, 
        @vcOrgname       VARCHAR(1000),
        @vcKOD_ORGAN     VARCHAR(8000),
        @vcVersion       VARCHAR(8000),
        @vcProgramName   VARCHAR(100),
        @vcCRC           VARCHAR(8000),  
        @vcInn           VARCHAR(50),
        @vcKpp           VARCHAR(9),
        @vcOkpo          VARCHAR(20),
        @vcOkato         VARCHAR(11),
        @vcPPP           VARCHAR(50),
        @iUchr_Link    INT,
        @vcOrgname_Uchr  VARCHAR(1000),
        @vcInn_Uchr      VARCHAR(50),
        @vcKpp_Uchr      VARCHAR(9),
        @vcOkpo_Uchr     VARCHAR(20),
        @vcSurname       VARCHAR(60),
        @vcFirstName     VARCHAR(60),
        @vcMiddleName    VARCHAR(60),
        @vcSurname_GB    VARCHAR(60),
        @vcFirstName_GB  VARCHAR(60),
        @vcMiddleName_GB VARCHAR(60),
        @vcDateRegl      VARCHAR(10),
        @vcExec          VARCHAR(8000),  
        @bCancel         BIT,
        @iReturn         INT,
        @vcNAME          VARCHAR(8000),
        @vcFORM_CODE     VARCHAR(8000),  
        @vcFILE_NAME_XSD VARCHAR(100),    
        @CODE            VARCHAR(100)
DECLARE @val             VARCHAR(8000), 
        @str             VARCHAR(8000)
          
CREATE TABLE #tabXML ([TXT]	  VARCHAR(8000),
							 [ORDERS] INT IDENTITY(1,1))

IF OBJECT_ID('tempdb..#tabExportOutput') IS NOT NULL  
BEGIN  
   SELECT @vcVersion = [VERSION]  
   FROM #tabExportOutput   
END  
  
IF @bCancel = 1  
BEGIN  
   RETURN 0  
END  
  
SET @bCancel = 0         
SET @vcNAME = 'Справка по заключению счетов бух. учета отчетного финанс. года'  
SET @vcFORM_CODE = '0503710'  
SET @vcVersion='5.01'  
SELECT @vcProgramName = CASE WHEN CODE_TASK = 'SMETA'   THEN 'СМЕТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'KADRY'   THEN 'КАДРЫ-КС'
                             WHEN CODE_TASK = 'SALARY'  THEN 'ЗАРПЛАТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'DELO'    THEN 'ДЕЛО-КС'
                             WHEN CODE_TASK = 'ADMIN'   THEN 'АДМИНИСТРАТОР'
                             ELSE ''
                        END       
FROM [dbo].USER_INFO                                  

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_ORG  = [Link_Organization]         
FROM dbo.[report_saved_forms] A  
WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM   

SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 1

CREATE TABLE #tabAttr ([CHECKED] INT, 
                       [UPD]     INT, 
                       [DEL]     INT, 
                       [LINK_SAVED_FORM] INT, 
                       [LINK_ROW] INT, 
                       [ORDERS]   INT, 
                       [CALC_ORDERS] INT, 
                       [PRINT_NULL] INT, 
                       [CODE] VARCHAR(50),  COL1 VARCHAR(8000), 
                       COL2  NUMERIC(14,2), COL3  NUMERIC(14,2), COL4  NUMERIC(14,2), 
                       COL5  NUMERIC(14,2), COL6  NUMERIC(14,2), COL7  NUMERIC(14,2), 
                       COL8  NUMERIC(14,2), COL9  NUMERIC(14,2), COL10 NUMERIC(14,2), 
                       COL11 NUMERIC(14,2), COL12 NUMERIC(14,2), COL13 NUMERIC(14,2) )
  SET @vcExec = 'INSERT #tabAttr
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  EXEC(@vcExec)

-- Выгрузка подписей.
 SELECT   @vcOrgname = substring(dbo.[RA_XML_MASK](d.[FULL_NAME]),1,1000),
          @vcInn     = rtrim(ltrim(d.[INN])),
          @vcKpp     = rtrim(ltrim(d.[KPP])),
          @vcOkpo    = d.[OKPO],
          @vcOkato   = d.[OKATO],
          @iUchr_Link    = d.[UCHR_LINK]
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iLINK_ORG
 SELECT   @vcInn_Uchr     = isnull(d.[INN],''),
          @vcKpp_Uchr     = isnull(d.[KPP],''),
          @vcOkpo_Uchr    = isnull(d.[OKPO],''),
          @vcOrgName_Uchr = isnull(dbo.[RA_XML_MASK](d.[FULL_NAME]),'')
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iUchr_Link
 SELECT @vcKOD_ORGAN = [SONO],
        @vcPPP       = [VED]
 FROM PrintDoc_GetDepData2(@iLINK_ORG)   
 SELECT @vcSurname=ch.[FM],
        @vcFirstName=ch.[IM],
        @vcMiddleName=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Руководитель') ch
 WHERE ch.link_dep = @iLINK_ORG
 SELECT @vcSurname_GB=ch.[FM],
        @vcFirstName_GB=ch.[IM],
        @vcMiddleName_GB=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Главный бухгалтер') ch
 WHERE ch.link_dep = @iLINK_ORG
 IF (@vcSurname='' OR @vcSurname IS NULL OR LEN(@vcSurname)=0) SELECT @vcSurname='A'
 IF (@vcFirstName='' OR @vcFirstName IS NULL OR LEN(@vcFirstName)=0) SELECT @vcFirstName='A'
 IF @vcInn IS NULL SELECT @vcInn='9999999999'
 IF @vcKpp IS NULL SELECT @vcKpp='999999999'
 IF @vcKOD_ORGAN IS NULL SELECT @vcKOD_ORGAN=''
--Дата начала   
SELECT @dBEGIN_DATE = A.[Begin_Date],
       @sYear = CAST(YEAR(@dBEGIN_DATE) AS VARCHAR(4)),  
       @vcDateRegl = convert(varchar(12), @dBEGIN_DATE+1, 104) 
  FROM dbo.[report_saved_forms] A
  WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM
--Дата документа
 SELECT @dFORM_DATE=GETDATE()
  
SET @vcCRC = RTRIM(CONVERT(VARCHAR(100), NEWID()))  
--Имя файла
SELECT @vcExec =  'NO_BOUCHR2_' +  @vcKOD_ORGAN+ '_' +  
                  @vcKOD_ORGAN+ '_' + @vcINN + @vcKPP + '_' +  
                  CAST(YEAR(@dFORM_DATE) AS VARCHAR(4)) + 
                  RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '_' + @vcCRC,
       @vcFILE_NAME =  @vcExec + '.xml',
       @vcFILE_NAME_XSD =  @vcExec + '.xsd'
--Вставка XML
INSERT #tabXML([TXT]) VALUES ('<?xml  version ="1.0"  encoding ="windows-1251"?>')
INSERT #tabXML([TXT]) VALUES ('<Файл ИдФайл="'+@vcExec+'" '+'ВерсПрог="'+@vcProgramName+'" '+'ВерсФорм="'+@vcVersion+'">')
INSERT #tabXML([TXT]) VALUES ('  <Документ КНД="' + @vcFORM_CODE + '" ДатаДок="'+RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '.' +  
                               RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ '.' + CAST(YEAR(@dFORM_DATE) AS VARCHAR(4))+
                               '" Период="34" ОтчетГод="'+CAST(@sYear AS VARCHAR(4))+'" НомКорр="0">')
INSERT #tabXML([TXT]) VALUES ('    <СвНП')
IF @vcOkpo<>'' AND LEN(@vcOkpo) BETWEEN 8 AND 10 
begin INSERT #tabXML([TXT]) VALUES (' ОКПО="'+LTRIM(RTRIM(@vcOkpo))+'"') end
IF @vcOkato<>'' AND LEN(@vcOkato)=11
begin INSERT #tabXML([TXT]) VALUES (' ОКАТО="'+@vcOkato+'"') END
IF @vcOkpo_Uchr<>'' AND LEN(@vcOkpo_Uchr) BETWEEN 8 AND 10 
INSERT #tabXML([TXT]) VALUES (' ОКПО_Учр="'+LTRIM(RTRIM(@vcOkpo_Uchr))+'"') 
IF @vcPPP<>'' AND LEN(@vcPPP)<4
INSERT #tabXML([TXT]) VALUES (' ГлаваБК="' + @vcPPP + '"')
INSERT #tabXML([TXT]) VALUES ('>')
INSERT #tabXML([TXT]) VALUES ('      <НПЮЛ НаимОрг="'+@vcOrgname+'" ИННЮЛ="'+@vcInn+'" КПП="'+@vcKpp+'"')
IF @vcOrgName_Uchr<>'' 
begin INSERT #tabXML([TXT]) VALUES (' Учредит="'+@vcOrgName_Uchr+'"') end
IF @vcInn_Uchr<>''
begin INSERT #tabXML([TXT]) VALUES (' ИННЮЛ_Учр="'+@vcInn_Uchr+'"') end
IF @vcKpp_Uchr<>''
begin INSERT #tabXML([TXT]) VALUES (' КПП_Учр="'+@vcKpp_Uchr+'"') end
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('    </СвНП>')
INSERT #tabXML([TXT]) VALUES ('<Подписант ПрПодп="3">')
INSERT #tabXML([TXT]) VALUES ('<ФИО Фамилия="'+@vcSurname+'" Имя="'+@vcFirstName+'"')
IF @vcMiddleName<>''
INSERT #tabXML([TXT]) VALUES ('           Отчество="'+@vcMiddleName+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('</Подписант>')
IF @vcSurname_GB<>'' AND @vcFirstName_GB<>''
begin
INSERT #tabXML([TXT]) VALUES ('<Подписант ПрПодп="4">')
INSERT #tabXML([TXT]) VALUES ('<ФИО Фамилия="'+@vcSurname_GB+'" Имя="'+@vcFirstName_GB+'"')
IF @vcMiddleName_GB<>''
INSERT #tabXML([TXT]) VALUES ('Отчество="'+@vcMiddleName_GB+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('</Подписант>')
end
INSERT #tabXML([TXT]) VALUES ('	   <СпрЗаклСч ДатаОтч="'+@vcDateRegl+'" ОКЕИ="383">')
INSERT #tabXML([TXT]) VALUES ('<СведСчет>')
--------------------------------------
IF EXISTS (SELECT * FROM #tabAttr WHERE [CODE]=888888888 AND (col2<>'0.00' OR col3<>'0.00' OR col4<>'0.00' OR col5<>'0.00'))
begin
INSERT #tabXML([TXT]) VALUES ('<Остаток>')
SELECT @val='', @str=''
SELECT @val=[COL2] FROM #tabAttr WHERE  [CODE]=888888888
if @val<>'0.00' begin set @str = @str + 'Дебет = "' + @val + '" ' END
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=888888888
if @val<>'0.00' begin set @str = @str + 'Кредит = "' + @val + '" ' END
IF @str<>'' 
begin 
INSERT #tabXML([TXT]) SELECT '<ЦелевСред '+@str+'/>'
end
SELECT @val='', @str=''
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=888888888
if @val<>'0.00' begin set @str = @str + 'Дебет = "' + @val + '" ' END
SELECT @val=[COL5] FROM #tabAttr WHERE  [CODE]=888888888
if @val<>'0.00' begin set @str = @str + 'Кредит = "' + @val + '" ' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<ОказУслуг '+@str+'/>'
end
INSERT #tabXML([TXT]) VALUES ('</Остаток>')
end
-----------------------------------------
IF EXISTS (SELECT * FROM #tabAttr WHERE [CODE]=888888888 AND (col10<>'0.00' OR col11<>'0.00' OR col12<>'0.00' OR col13<>'0.00'))
begin
INSERT #tabXML([TXT]) VALUES ('<ЗаклЗапис>')
IF EXISTS (SELECT * FROM #tabAttr WHERE [CODE]=888888888 AND (col6<>'0.00' OR col7<>'0.00' OR col8<>'0.00' OR col9<>'0.00'))
begin
SELECT @val='', @str=''
SELECT @val=[COL6] FROM #tabAttr WHERE  [CODE]=888888888
if @val<>'0.00' begin set @str = @str + 'Дебет = "' + @val + '" ' END
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=888888888
if @val<>'0.00' begin set @str = @str + 'Кредит = "' + @val + '" ' END
IF @str<>'' 
begin 
INSERT #tabXML([TXT]) SELECT '<ЦелевСред '+@str+'/>'
end
SELECT @val='', @str=''
SELECT @val=[COL8] FROM #tabAttr WHERE  [CODE]=888888888
if @val<>'0.00' begin set @str = @str + 'Дебет = "' + @val + '" ' END
SELECT @val=[COL9] FROM #tabAttr WHERE  [CODE]=888888888
if @val<>'0.00' begin set @str = @str + 'Кредит = "' + @val + '" ' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<ОказУслуг '+@str+'/>'
END
end
INSERT #tabXML([TXT]) VALUES ('<Счет>')
SELECT @val='', @str=''
SELECT @val=[COL10] FROM #tabAttr WHERE  [CODE]=888888888
if @val<>'0.00' begin set @str = @str + 'Дебет = "' + @val + '" ' END
SELECT @val=[COL11] FROM #tabAttr WHERE  [CODE]=888888888
if @val<>'0.00' begin set @str = @str + 'Кредит = "' + @val + '" ' END
IF @str<>'' 
begin 
INSERT #tabXML([TXT]) SELECT '<ЦелевСред '+@str+'/>'
end
SELECT @val='', @str=''
SELECT @val=[COL12] FROM #tabAttr WHERE  [CODE]=888888888
if @val<>'0.00' begin set @str = @str + 'Дебет = "' + @val + '" ' END
SELECT @val=[COL13] FROM #tabAttr WHERE  [CODE]=888888888
if @val<>'0.00' begin set @str = @str + 'Кредит = "' + @val + '" ' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<ОказУслуг '+@str+'/>'
END
INSERT #tabXML([TXT]) VALUES ('</Счет>')
INSERT #tabXML([TXT]) VALUES ('</ЗаклЗапис>')
end
-----------------------------------------------
DECLARE T_CURSOR CURSOR FOR      
 SELECT CODE FROM #tabAttr WHERE [CODE]<>888888888
OPEN    T_CURSOR      
 FETCH NEXT FROM T_CURSOR INTO @CODE      
 WHILE @@FETCH_STATUS = 0         
BEGIN  
INSERT #tabXML([TXT]) VALUES ('<СведСчетНом НомСчет="' + @CODE + '">')
IF EXISTS (SELECT * FROM #tabAttr WHERE [CODE]=@CODE AND (col2<>'0.00' OR col3<>'0.00' OR col4<>'0.00' OR col5<>'0.00'))
begin
INSERT #tabXML([TXT]) VALUES ('<Остаток>')
SELECT @val='', @str=''
SELECT @val=[COL2] FROM #tabAttr WHERE  [CODE]=@CODE
if @val<>'0.00' begin set @str = @str + 'Дебет = "' + @val + '" ' END
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=@CODE
if @val<>'0.00' begin set @str = @str + 'Кредит = "' + @val + '" ' END
IF @str<>'' 
begin 
INSERT #tabXML([TXT]) SELECT '<ЦелевСред '+@str+'/>'
end
SELECT @val='', @str=''
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=@CODE
if @val<>'0.00' begin set @str = @str + 'Дебет = "' + @val + '" ' END
SELECT @val=[COL5] FROM #tabAttr WHERE  [CODE]=@CODE
if @val<>'0.00' begin set @str = @str + 'Кредит = "' + @val + '" ' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<ОказУслуг '+@str+'/>'
end
INSERT #tabXML([TXT]) VALUES ('</Остаток>')
end
-----------------------------------------
IF EXISTS (SELECT * FROM #tabAttr WHERE [CODE]=@CODE AND (col10<>'0.00' OR col11<>'0.00' OR col12<>'0.00' OR col13<>'0.00'))
begin
INSERT #tabXML([TXT]) VALUES ('<ЗаклЗапис>')
IF EXISTS (SELECT * FROM #tabAttr WHERE [CODE]=@CODE AND (col6<>'0.00' OR col7<>'0.00' OR col8<>'0.00' OR col9<>'0.00'))
begin
SELECT @val='', @str=''
SELECT @val=[COL6] FROM #tabAttr WHERE  [CODE]=@CODE
if @val<>'0.00' begin set @str = @str + 'Дебет = "' + @val + '" ' END
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=@CODE
if @val<>'0.00' begin set @str = @str + 'Кредит = "' + @val + '" ' END
IF @str<>'' 
begin 
INSERT #tabXML([TXT]) SELECT '<ЦелевСред '+@str+'/>'
end
SELECT @val='', @str=''
SELECT @val=[COL8] FROM #tabAttr WHERE  [CODE]=@CODE
if @val<>'0.00' begin set @str = @str + 'Дебет = "' + @val + '" ' END
SELECT @val=[COL9] FROM #tabAttr WHERE  [CODE]=@CODE
if @val<>'0.00' begin set @str = @str + 'Кредит = "' + @val + '" ' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<ОказУслуг '+@str+'/>'
END
end
INSERT #tabXML([TXT]) VALUES ('<Счет>')
SELECT @val='', @str=''
SELECT @val=[COL10] FROM #tabAttr WHERE  [CODE]=@CODE
if @val<>'0.00' begin set @str = @str + 'Дебет = "' + @val + '" ' END
SELECT @val=[COL11] FROM #tabAttr WHERE  [CODE]=@CODE
if @val<>'0.00' begin set @str = @str + 'Кредит = "' + @val + '" ' END
IF @str<>'' 
begin 
INSERT #tabXML([TXT]) SELECT '<ЦелевСред '+@str+'/>'
end
SELECT @val='', @str=''
SELECT @val=[COL12] FROM #tabAttr WHERE  [CODE]=@CODE
if @val<>'0.00' begin set @str = @str + 'Дебет = "' + @val + '" ' END
SELECT @val=[COL13] FROM #tabAttr WHERE  [CODE]=@CODE
if @val<>'0.00' begin set @str = @str + 'Кредит = "' + @val + '" ' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<ОказУслуг '+@str+'/>'
END
INSERT #tabXML([TXT]) VALUES ('</Счет>')
INSERT #tabXML([TXT]) VALUES ('</ЗаклЗапис>')
end
INSERT #tabXML([TXT]) VALUES ('</СведСчетНом>')

FETCH NEXT FROM T_CURSOR INTO @CODE      
END      
CLOSE T_CURSOR      
DEALLOCATE T_CURSOR   
----------------------------------------
INSERT #tabXML([TXT]) VALUES ('</СведСчет>')
INSERT #tabXML([TXT]) VALUES ('</СпрЗаклСч>')
INSERT #tabXML([TXT]) VALUES ('</Документ>')
INSERT #tabXML([TXT]) VALUES ('</Файл>')
----------------------------------------
INSERT #Files ([TXT], [NAMEFILE],  [NAMEFILE_ARH],  [OrderFile],[LINK_SAVED_FORM])
SELECT         [TXT], @vcFILE_NAME,@vcFILE_NAME_XSD,[ORDERS],   @iLINK_SAVED_FORM
FROM #tabXML
DROP TABLE #tabXML  


GO


GRANT EXECUTE ON dbo.[RA_EXPORT_FORM_FNS_710] TO PUBLIC

GO




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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE dbo.SD_O_ESN_TABLE_SAVE
	@intLINK				int,
	@intORDERS			int,
	@intLINK_EMPL		int,
	@numSUMMA_BASE 	numeric(18,2)=0.0,
	@numCALC_TAX		numeric(18,2)=0.0,
	@numDED_M			numeric(18,2)=0.0,
	@numINV_M			numeric(18,2)=0.0,
	@numSUM_DED 		numeric(18,2)=0.0,
	@numSUMMA			numeric(18,2)=0.0,
	@numTOTAL_DED		numeric(18,2)=0.0,
	@numTOTAL_SUM		numeric(18,2)=0.0,
	@numTOTAL_TAX		numeric(18,2)=0.0, 
	@intLINK_PAY		int,
	@intLINK_VKR 		int,
	@LINK_EKR			INT,
	@DEL				TINYINT = 0,
	@PERC				numeric(18,2)=0.0,
	@TARIF				INT=null,	
	@SPECO				INT = null

AS
DECLARE @SQLError			tinyint,
		  @trancount	int,		
		  @strVALUE		varchar(7000),
		  @tintSTATUS	int,
		  @RowCount		int,
		  @linkFace 	int	

SET @trancount = @@TRANCOUNT

SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

SELECT @linkFace = PERS_LINK FROM dbo.EMPL WHERE LINK = @intLINK_EMPL
SELECT @tintSTATUS = dbo.IS_INVALID(@linkFace,dbo.SalaryPeriodCalcBegin())

IF @intLINK_EMPL IS NULL OR @intLINK_PAY IS NULL OR @intLINK_VKR IS NULL OR @LINK_EKR IS NULL
BEGIN
	ROLLBACK
	RETURN 8
END

IF ISNULL(@DEL,0) = 0

	IF NOT EXISTS (SELECT LINK_UP FROM DBO.SDOC_ESN_TABLE WHERE LINK_UP = @intLINK AND LINK_EMPL = @intLINK_EMPL AND LINK_PAY = @intLINK_PAY AND LINK_VKR = @intLINK_VKR AND LINK_EKR = @LINK_EKR)
		INSERT INTO SDOC_ESN_TABLE WITH (ROWLOCK) (LINK_UP,ORDERS,LINK_EMPL,SUMMA_BASE,CALC_TAX,DED_M,INV_M,SUM_DED,SUMMA, TOTAL_DED,TOTAL_SUM,TOTAL_TAX,LINK_PAY,LINK_VKR,[STATUS],LINK_EKR, PERC, TARIF, SPECO)
		VALUES (@intLINK,@intORDERS,@intLINK_EMPL,@numSUMMA_BASE,@numCALC_TAX,@numDED_M,@numINV_M,@numSUM_DED,@numSUMMA,
				@numTOTAL_DED,@numTOTAL_SUM,@numTOTAL_TAX,@intLINK_PAY,@intLINK_VKR,@tintSTATUS,@LINK_EKR, @PERC, @TARIF, @SPECO)

	ELSE
		UPDATE 
			DBO.SDOC_ESN_TABLE
		SET
			ORDERS = @intORDERS,
			SUMMA_BASE = @numSUMMA_BASE,
			CALC_TAX = @numCALC_TAX,
			DED_M = @numDED_M,
			INV_M = @numINV_M,
			SUM_DED = @numSUM_DED,
			SUMMA = @numSUMMA, 
			TOTAL_DED = @numTOTAL_DED,
			TOTAL_SUM = @numTOTAL_SUM,
			TOTAL_TAX = @numTOTAL_TAX,
			[STATUS] = @tintSTATUS,
			PERC = @PERC,
			TARIF = @TARIF,
			SPECO = @SPECO
		WHERE 
			LINK_UP = @intLINK AND LINK_EMPL = @intLINK_EMPL AND LINK_PAY = @intLINK_PAY AND LINK_VKR = @intLINK_VKR AND LINK_EKR = @LINK_EKR
ELSE
		DELETE FROM DBO.SDOC_ESN_TABLE
		WHERE LINK_UP = @intLINK AND LINK_EMPL = @intLINK_EMPL AND LINK_PAY = @intLINK_PAY AND LINK_VKR = @intLINK_VKR AND LINK_EKR = @LINK_EKR

SELECT @SQLError = @@ERROR, @intLINK = @@IDENTITY
IF @SQLError <> 0
BEGIN
	ROLLBACK
	RETURN 7
END

WHILE @@TRANCOUNT > @trancount
	COMMIT TRAN
RETURN 0



GO


GRANT EXECUTE ON dbo.[SD_O_ESN_TABLE_SAVE] TO PUBLIC

GO



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

GO
----------------------
CREATE PROCEDURE [dbo].[RA_EXPORT_FORM_FNS_725]
@iLINK_SAVED_FORM INT,                    -- Линк выгружаемой формы  
 @vcFILE_NAME     VARCHAR(100)='' OUTPUT, -- Имя текстового файла  
 @iMODE           INT=1                   -- Формат: 2-внутренний, 1-минфиновский  
AS  
  
SET NOCOUNT ON  
SET DATEFORMAT dmy  

DECLARE @iLINK_FORM		 INT,
        @iLINK_ORG       INT,
      	@iLINK_TABLE	 INT,
        @dBEGIN_DATE     DATETIME,
        @dFORM_DATE      DATETIME,
        @sYear           SMALLINT, 
        @vcOrgname       VARCHAR(1000),
        @vcKOD_ORGAN     VARCHAR(8000),
        @vcVersion       VARCHAR(8000),
        @vcProgramName   VARCHAR(100),
        @vcCRC           VARCHAR(8000),  
        @vcInn           VARCHAR(10),
        @vcKpp           VARCHAR(9),
        @vcOkpo          VARCHAR(50),
        @vcOkato         VARCHAR(11),
        @vcPPP           VARCHAR(50),
        @vcOrgname_Uchr  VARCHAR(1000),
        @iUchr_Link      INT,
        @vcInn_Uchr      VARCHAR(10),
        @vcKpp_Uchr      VARCHAR(9),
        @vcOkpo_Uchr     VARCHAR(50),
        @vcSurname       VARCHAR(60),
        @vcFirstName     VARCHAR(60),
        @vcMiddleName    VARCHAR(60),
        @vcSurname_GB    VARCHAR(60),
        @vcFirstName_GB  VARCHAR(60),
        @vcMiddleName_GB VARCHAR(60),
        @vcDateRegl      VARCHAR(10),
        @vcExec          VARCHAR(8000),  
        @vcKodCBU        VARCHAR(9), 
        @vcFO            VARCHAR(1), 
        @bCancel         BIT,
        @iReturn         INT,
        @vcNAME          VARCHAR(8000),
        @vcFORM_CODE     VARCHAR(8000),  
        @vcFILE_NAME_XSD VARCHAR(100),    
        @vcTableName     VARCHAR(8000), 
        @CODE            VARCHAR(100)
DECLARE @val             VARCHAR(8000), 
        @val2            VARCHAR(8000), 
        @str             VARCHAR(8000),
        @str1            VARCHAR(8000)
          
CREATE TABLE #tabXML ([TXT]	  VARCHAR(8000),
							 [ORDERS] INT IDENTITY(1,1))

IF OBJECT_ID('tempdb..#tabExportOutput') IS NOT NULL  
BEGIN  
   SELECT @vcVersion = [VERSION]  
   FROM #tabExportOutput   
END  
  
IF @bCancel = 1  
BEGIN  
   RETURN 0  
END  
  
SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_ORG  = [Link_Organization]         
FROM dbo.[report_saved_forms] A  
WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM   

SELECT @vcKodCBU = RTRIM(dbo.[RN_GET_ATR_VALUE](@iLINK_SAVED_FORM,'REPORTS_ATR_ACC_725'))
SELECT @vcFO     = LEFT(@vcKodCBU,1)

SET @bCancel = 0         
SET @vcNAME = 'Справка по консолидируемым расчетам учреждения'
SET @vcFORM_CODE = '0503725'  
SET @vcVersion='5.01'  
SELECT @vcProgramName = CASE WHEN CODE_TASK = 'SMETA'   THEN 'СМЕТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'KADRY'   THEN 'КАДРЫ-КС'
                             WHEN CODE_TASK = 'SALARY'  THEN 'ЗАРПЛАТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'DELO'    THEN 'ДЕЛО-КС'
                             WHEN CODE_TASK = 'ADMIN'   THEN 'АДМИНИСТРАТОР'
                             ELSE ''
                        END       
FROM [dbo].USER_INFO                                  
--Раздел
SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 1

CREATE TABLE #tabAttr ([CHECKED]         INT, 
                       [UPD]             INT, 
                       [DEL]             INT, 
                       [LINK_SAVED_FORM] INT, 
                       [LINK_ROW]        INT, 
                       [ORDERS]          INT, 
                       [CALC_ORDERS]     INT, 
                       [PRINT_NULL]      INT, 
                       [CODE]            VARCHAR(50),
                       COL1 VARCHAR(8000), COL2 VARCHAR(8000), COL3 NUMERIC(14,2), 
                       COL4 NUMERIC(14,2), COL5 VARCHAR(8000), COL6 VARCHAR(8000), COL7 VARCHAR(8000))

  SET @vcExec = 'INSERT #tabAttr
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 

  EXEC(@vcExec)
--Итоги
SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 2

CREATE TABLE #tabAttr1 ([CHECKED]         INT, 
                        [UPD]             INT, 
                        [DEL]             INT, 
                        [LINK_SAVED_FORM] INT, 
                        [LINK_ROW]        INT, 
                        [ORDERS]          INT, 
                        [CALC_ORDERS]     INT, 
                        [PRINT_NULL]      INT, 
                        [CODE]            VARCHAR(50),
                        COL1 VARCHAR(8000), COL2 VARCHAR(8000), COL3 NUMERIC(14,2), 
                        COL4 NUMERIC(14,2), COL5 VARCHAR(8000), COL6 VARCHAR(8000))

  SET @vcExec = 'INSERT #tabAttr1
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  EXEC(@vcExec)
-- Выгрузка подписей.
 SELECT   @vcOrgname = substring(dbo.[RA_XML_MASK](d.[FULL_NAME]),1,1000),
          @vcInn     = rtrim(ltrim(d.[INN])),
          @vcKpp     = rtrim(ltrim(d.[KPP])),
          @vcOkpo    = d.[OKPO],
          @vcOkato   = d.[OKATO],
          @iUchr_Link    = d.[UCHR_LINK]
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iLINK_ORG
 SELECT   @vcInn_Uchr     = isnull(d.[INN],''),
          @vcKpp_Uchr     = isnull(d.[KPP],''),
          @vcOkpo_Uchr    = isnull(d.[OKPO],''),
          @vcOrgName_Uchr = isnull(dbo.[RA_XML_MASK](d.[FULL_NAME]),'')
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iUchr_Link
 SELECT @vcKOD_ORGAN = [SONO],
        @vcPPP       = [VED]
 FROM PrintDoc_GetDepData2(@iLINK_ORG)   
 SELECT @vcSurname=ch.[FM],
        @vcFirstName=ch.[IM],
        @vcMiddleName=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Руководитель') ch
 WHERE ch.link_dep = @iLINK_ORG
 SELECT @vcSurname_GB=ch.[FM],
        @vcFirstName_GB=ch.[IM],
        @vcMiddleName_GB=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Главный бухгалтер') ch
 WHERE ch.link_dep = @iLINK_ORG
 IF (@vcSurname='' OR @vcSurname IS NULL OR LEN(@vcSurname)=0) SELECT @vcSurname='A'
 IF (@vcFirstName='' OR @vcFirstName IS NULL OR LEN(@vcFirstName)=0) SELECT @vcFirstName='A'
 IF @vcInn IS NULL SELECT @vcInn='9999999999'
 IF @vcKpp IS NULL SELECT @vcKpp='999999999'
 IF @vcKOD_ORGAN IS NULL SELECT @vcKOD_ORGAN=''
--Дата начала   
SELECT @dBEGIN_DATE = A.[Begin_Date],
       @sYear = CAST(YEAR(@dBEGIN_DATE) AS VARCHAR(4)),  
       @vcDateRegl = convert(varchar(12), @dBEGIN_DATE+1, 104) 
  FROM dbo.[report_saved_forms] A
  WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM
--Дата документа
 SELECT @dFORM_DATE=GETDATE()
  
SET @vcCRC = RTRIM(CONVERT(VARCHAR(100), NEWID()))  
--Имя файла
SELECT @vcExec =  'NO_BOUCHR3.' + @vcFO + '_' +  @vcKOD_ORGAN+ '_' +  
                  @vcKOD_ORGAN+ '_' + @vcINN + @vcKPP + '_' +  
                  CAST(YEAR(@dFORM_DATE) AS VARCHAR(4)) +   
                  RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '_' + @vcCRC,
       @vcFILE_NAME =  @vcExec + '.xml',
       @vcFILE_NAME_XSD =  @vcExec + '.xsd'
--Вставка XML
INSERT #tabXML([TXT]) VALUES ('<?xml  version ="1.0"  encoding ="windows-1251"?>')
INSERT #tabXML([TXT]) VALUES ('<Файл ИдФайл="'+@vcExec+'" '+'ВерсПрог="'+@vcProgramName+'" '+'ВерсФорм="'+@vcVersion+'">')
INSERT #tabXML([TXT]) VALUES ('  <Документ КНД="' + @vcFORM_CODE + '" ДатаДок="'+RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '.' +  
                               RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ '.' + CAST(YEAR(@dFORM_DATE) AS VARCHAR(4))+
              '" Период="34" ОтчетГод="'+CAST(@sYear AS VARCHAR(4))+'" НомКорр="0">')
INSERT #tabXML([TXT]) VALUES ('<СвНП')
IF @vcOkpo<>'' AND LEN(@vcOkpo) BETWEEN 8 AND 10 
INSERT #tabXML([TXT]) VALUES (' ОКПО="'+LTRIM(RTRIM(@vcOkpo))+'"') 
IF @vcOkato<>'' AND LEN(@vcOkato)=11
INSERT #tabXML([TXT]) VALUES (' ОКАТО="'+@vcOkato+'"')
IF @vcOkpo_Uchr<>'' AND LEN(@vcOkpo_Uchr) BETWEEN 8 AND 10 
INSERT #tabXML([TXT]) VALUES (' ОКПО_Учр="'+LTRIM(RTRIM(@vcOkpo_Uchr))+'"') 
IF @vcPPP<>'' AND LEN(@vcPPP)<4
INSERT #tabXML([TXT]) VALUES (' ГлаваБК="' + @vcPPP + '"')
INSERT #tabXML([TXT]) VALUES ('>')
INSERT #tabXML([TXT]) VALUES ('<НПЮЛ НаимОрг="'+@vcOrgname+'" ИННЮЛ="'+@vcInn+'" КПП="'+@vcKpp+'"')
IF @vcOrgName_Uchr<>'' 
INSERT #tabXML([TXT]) VALUES (' Учредит="'+@vcOrgName_Uchr+'"')
IF @vcInn_Uchr<>''
INSERT #tabXML([TXT]) VALUES (' ИННЮЛ_Учр="'+@vcInn_Uchr+'"')
IF @vcKpp_Uchr<>''
INSERT #tabXML([TXT]) VALUES (' КПП_Учр="'+@vcKpp_Uchr+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('    </СвНП>')
INSERT #tabXML([TXT]) VALUES ('<Подписант ПрПодп="3">')
INSERT #tabXML([TXT]) VALUES ('<ФИО Фамилия="'+@vcSurname+'" Имя="'+@vcFirstName+'"')
IF @vcMiddleName<>''
INSERT #tabXML([TXT]) VALUES ('           Отчество="'+@vcMiddleName+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('</Подписант>')
IF @vcSurname_GB<>'' AND @vcFirstName_GB<>''
begin
INSERT #tabXML([TXT]) VALUES ('<Подписант ПрПодп="4">')
INSERT #tabXML([TXT]) VALUES ('<ФИО Фамилия="'+@vcSurname_GB+'" Имя="'+@vcFirstName_GB+'"')
IF @vcMiddleName_GB<>''
INSERT #tabXML([TXT]) VALUES ('Отчество="'+@vcMiddleName_GB+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('</Подписант>')
end
INSERT #tabXML([TXT]) VALUES ('	   <СпрКонсРасч ДатаОтч="'+@vcDateRegl+'" ОКЕИ="383">')
--------------------------------------------------
DECLARE T_CURSOR CURSOR FOR      
 SELECT CODE FROM #tabAttr
 OPEN   T_CURSOR      
 FETCH NEXT FROM T_CURSOR INTO @CODE
 WHILE @@FETCH_STATUS = 0         
BEGIN 
 SELECT @val='', @val2='', @str='', @str1=''
 SELECT @str = '<КонтрАгент НаимКАг="'
 SELECT @str1 = [COL1] FROM #tabAttr WHERE  [CODE]=@CODE
 SET    @str = @str + @str1 + '" КодПодр="'  
 SELECT @str1 = [COL2] FROM #tabAttr WHERE  [CODE]=@CODE
 SET    @str = @str + @str1 + '" НомСчетБУч="' + @vcKodCBU + '"'  
 SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=@CODE
 if @val<>'0.00' begin set @str = @str + ' Дебет="' + @val + '"' END
 SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=@CODE
 if @val<>'0.00' begin set @str = @str + ' Кредит="' + @val + '"' END
 SELECT @str1=[COL5] FROM #tabAttr WHERE  [CODE]=@CODE
 SET    @str=@str + ' КодКорСчет="' + @str1 + '"/>'
 INSERT #tabXML([TXT]) SELECT @str
FETCH NEXT FROM T_CURSOR INTO @CODE      
END      
CLOSE T_CURSOR      
DEALLOCATE T_CURSOR
--------------------------------------------------
SELECT @val='', @val2='', @str='', @str1=''
INSERT #tabXML([TXT]) VALUES ('<СведИтого')
SELECT @val=[COL3] FROM #tabAttr1 WHERE  [CODE]='00000000000000000000000000'
if @val<>'0.00' begin set @str = @str + ' ДебетИтого="' + @val + '"' END
SELECT @val=[COL4] FROM #tabAttr1 WHERE  [CODE]='00000000000000000000000000'
if @val<>'0.00' begin set @str = @str + ' КредитИтого="' + @val + '"' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT @str+'>'
END
-------------------------------------------------
DECLARE T_CURSOR CURSOR FOR      
 SELECT CODE FROM #tabAttr1 WHERE CODE LIKE '%ИП'
 OPEN   T_CURSOR      
 FETCH NEXT FROM T_CURSOR INTO @CODE
 WHILE @@FETCH_STATUS = 0         
BEGIN 
 SELECT @val='', @val2='', @str='', @str1=''
 SELECT @str = '<СведСчет'
 SELECT @str1 = [COL1] FROM #tabAttr1 WHERE  [CODE]=@CODE
 IF @str1<>'' SET @str = @str + ' КодПодр="' + @str1 + '"' 
 SELECT @str1 = [COL2] FROM #tabAttr1 WHERE  [CODE]=@CODE
 SET    @str = @str + ' НомСчетБУч="' + @str1 + '"'  
 SELECT @val=[COL3] FROM #tabAttr1 WHERE  [CODE]=@CODE
 if @val<>'0.00' begin set @str = @str + ' ДебетСч="' + @val + '"' END
 SELECT @val=[COL4] FROM #tabAttr1 WHERE  [CODE]=@CODE
 if @val<>'0.00' begin set @str = @str + ' КредитСч="' + @val + '"' END
 SET    @str=@str + '/>'
 INSERT #tabXML([TXT]) SELECT @str
FETCH NEXT FROM T_CURSOR INTO @CODE      
END      
CLOSE T_CURSOR      
DEALLOCATE T_CURSOR
--------------------------------------------------
DECLARE T_CURSOR CURSOR FOR      
 SELECT CODE FROM #tabAttr1 WHERE CODE LIKE '%ДР'
 OPEN   T_CURSOR      
 FETCH NEXT FROM T_CURSOR INTO @CODE
 WHILE @@FETCH_STATUS = 0         
BEGIN 
 SELECT @val='', @val2='', @str='', @str1=''
 SELECT @str = '<ДенРасч'
 SELECT @str1 = [COL1] FROM #tabAttr1 WHERE  [CODE]=@CODE
 SET    @str = @str + ' КодПодр="' + @str1 + '"' 
 SELECT @str1 = [COL2] FROM #tabAttr1 WHERE  [CODE]=@CODE
 SET    @str = @str + ' НомСчетБУч="' + @str1 + '"'  
 SELECT @val=[COL3] FROM #tabAttr1 WHERE  [CODE]=@CODE
 if @val<>'0.00' begin set @str = @str + ' ДебетРасч="' + @val + '"' END
 SELECT @val=[COL4] FROM #tabAttr1 WHERE  [CODE]=@CODE
 if @val<>'0.00' begin set @str = @str + ' КредитРасч="' + @val + '"' END
 SELECT @str1 = [COL5] FROM #tabAttr1 WHERE  [CODE]=@CODE
 SET    @str = @str + ' КодКорСчет="' + @str1 + '"'  
 SET    @str=@str + '/>'
 INSERT #tabXML([TXT]) SELECT @str
FETCH NEXT FROM T_CURSOR INTO @CODE      
END      
CLOSE T_CURSOR      
DEALLOCATE T_CURSOR
--------------------------------------------------
DECLARE T_CURSOR CURSOR FOR      
 SELECT CODE FROM #tabAttr1 WHERE CODE LIKE '%НР'
 OPEN   T_CURSOR      
 FETCH NEXT FROM T_CURSOR INTO @CODE
 WHILE @@FETCH_STATUS = 0         
BEGIN 
 SELECT @val='', @val2='', @str='', @str1=''
 SELECT @str = '<НеДенРасч'
 SELECT @str1 = [COL1] FROM #tabAttr1 WHERE  [CODE]=@CODE
 SET    @str = @str + ' КодПодр="' + @str1 + '"' 
 SELECT @str1 = [COL2] FROM #tabAttr1 WHERE  [CODE]=@CODE
 SET    @str = @str + ' НомСчетБУч="' + @str1 + '"'  
 SELECT @val=[COL3] FROM #tabAttr1 WHERE  [CODE]=@CODE
 if @val<>'0.00' begin set @str = @str + ' ДебетРасч="' + @val + '"' END
 SELECT @val=[COL4] FROM #tabAttr1 WHERE  [CODE]=@CODE
 if @val<>'0.00' begin set @str = @str + ' КредитРасч="' + @val + '"' END
 SELECT @str1 = [COL5] FROM #tabAttr1 WHERE  [CODE]=@CODE
 SET    @str = @str + ' КодКорСчет="' + @str1 + '"'  
 SET    @str=@str + '/>'
 INSERT #tabXML([TXT]) SELECT @str
FETCH NEXT FROM T_CURSOR INTO @CODE      
END      
CLOSE T_CURSOR      
DEALLOCATE T_CURSOR
--------------------------------------------------
INSERT #tabXML([TXT]) VALUES ('</СведИтого>')
INSERT #tabXML([TXT]) VALUES ('</СпрКонсРасч>')
INSERT #tabXML([TXT]) VALUES ('</Документ>')
INSERT #tabXML([TXT]) VALUES ('</Файл>')
----------------------------------------
INSERT #Files ([TXT], [NAMEFILE],  [NAMEFILE_ARH],  [OrderFile],[LINK_SAVED_FORM])
SELECT         [TXT], @vcFILE_NAME,@vcFILE_NAME_XSD,[ORDERS],   @iLINK_SAVED_FORM
FROM #tabXML
DROP TABLE #tabXML  



GO


GRANT EXECUTE ON dbo.[RA_EXPORT_FORM_FNS_725] TO PUBLIC

GO




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

GO
----------------------
CREATE PROCEDURE [dbo].[RA_EXPORT_FORM_FNS_779]
@iLINK_SAVED_FORM INT,                    -- Линк выгружаемой формы  
 @vcFILE_NAME     VARCHAR(100)='' OUTPUT, -- Имя текстового файла  
 @iMODE           INT=1                   -- Формат: 2-внутренний, 1-минфиновский  
AS  
  
SET NOCOUNT ON  
SET DATEFORMAT dmy  

DECLARE @iLINK_FORM		 INT,
        @iLINK_ORG       INT,
      	@iLINK_TABLE	 INT,
        @dBEGIN_DATE     DATETIME,
        @dFORM_DATE      DATETIME,
        @sYear           SMALLINT, 
        @vcOrgname       VARCHAR(1000),
        @vcKOD_ORGAN     VARCHAR(8000),
        @vcVersion       VARCHAR(8000),
        @vcProgramName   VARCHAR(100),
        @vcCRC           VARCHAR(8000),  
        @vcInn           VARCHAR(10),
        @vcKpp           VARCHAR(9),
        @vcOkpo          VARCHAR(20),
        @vcOkato         VARCHAR(11),
        @vcPPP           VARCHAR(50),
        @iUchr_Link      INT, 
        @vcOrgname_Uchr  VARCHAR(1000),
        @vcOkpo_Uchr     VARCHAR(20),
        @vcInn_Uchr      VARCHAR(10),
        @vcKpp_Uchr      VARCHAR(9),
        @vcSurname       VARCHAR(60),
        @vcFirstName     VARCHAR(60),
        @vcMiddleName    VARCHAR(60),
        @vcSurname_GB    VARCHAR(60),
        @vcFirstName_GB  VARCHAR(60),
        @vcMiddleName_GB VARCHAR(60),
        @vcDateRegl      VARCHAR(10),
        @vcExec          VARCHAR(8000),  
        @vcKodCBU        VARCHAR(9), 
        @vcFO            VARCHAR(1), 
        @bCancel         BIT,
        @iReturn         INT,
        @vcNAME          VARCHAR(8000),
        @vcFORM_CODE     VARCHAR(8000),  
        @vcFILE_NAME_XSD VARCHAR(100),    
        @vcTableName     VARCHAR(8000), 
        @CODE            VARCHAR(100)
DECLARE @val             VARCHAR(8000), 
        @str             VARCHAR(8000)
          
CREATE TABLE #tabXML ([TXT]	  VARCHAR(8000),
							 [ORDERS] INT IDENTITY(1,1))

IF OBJECT_ID('tempdb..#tabExportOutput') IS NOT NULL  
BEGIN  
   SELECT @vcVersion = [VERSION]  
   FROM #tabExportOutput   
END  
  
SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_ORG  = [Link_Organization]         
FROM dbo.[report_saved_forms] A  
WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM   

SELECT @vcFO = CASE WHEN [dbo].[RN_GET_ATR_VALUE](@iLINK_SAVED_FORM,'REPORTS_ATR_VID_NAME_773')='деятельность с целевыми средствами'     THEN '1'
                    WHEN [dbo].[RN_GET_ATR_VALUE](@iLINK_SAVED_FORM,'REPORTS_ATR_VID_NAME_773')='деятельность по оказанию услуг (работ)' THEN '2'
                    WHEN [dbo].[RN_GET_ATR_VALUE](@iLINK_SAVED_FORM,'REPORTS_ATR_VID_NAME_773')='средства во временном распоряжении'     THEN '3'
               END     

SET @vcNAME = 'Сведения об остатках денежных средств учреждения'
SET @vcFORM_CODE = '0503779'  
SET @vcVersion='5.01' 
SELECT @vcProgramName = CASE WHEN CODE_TASK = 'SMETA'   THEN 'СМЕТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'KADRY'   THEN 'КАДРЫ-КС'
                             WHEN CODE_TASK = 'SALARY'  THEN 'ЗАРПЛАТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'DELO'    THEN 'ДЕЛО-КС'
                             WHEN CODE_TASK = 'ADMIN'   THEN 'АДМИНИСТРАТОР'
                             ELSE ''
                        END       
FROM [dbo].USER_INFO                                  
 
--Таблица Всего
SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 4

CREATE TABLE #tabAttr4 ([CHECKED] INT, 
                        [UPD]     INT, 
                        [DEL]     INT, 
                        [LINK_SAVED_FORM] INT, 
                        [LINK_ROW] INT, 
                        [ORDERS]   INT, 
                        [CALC_ORDERS] INT, 
                        [PRINT_NULL] INT, 
                        [CODE] VARCHAR(50),  
                        COL1 VARCHAR(8000), COL2 VARCHAR(8000), 
                        COL3 VARCHAR(8000), COL4 VARCHAR(8000), 
                        COL5 VARCHAR(8000), COL6 VARCHAR(8000), 
                        COL7 VARCHAR(8000), itog VARCHAR(8000))
  SET @vcExec = 'INSERT #tabAttr4
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  EXEC(@vcExec)
--Таблица Счета в кредитных организациях
SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 1

CREATE TABLE #tabAttr1 ([CHECKED] INT, 
                        [UPD]     INT, 
                        [DEL]     INT, 
                        [LINK_SAVED_FORM] INT, 
                        [LINK_ROW] INT, 
                        [ORDERS]   INT, 
                        [CALC_ORDERS] INT, 
                        [PRINT_NULL] INT, 
                        [CODE] VARCHAR(50),  
                        COL1 VARCHAR(8000), COL2 VARCHAR(8000), 
                        COL3 VARCHAR(8000), COL4 VARCHAR(8000), 
                        COL5 VARCHAR(8000), COL6 VARCHAR(8000), 
                        COL7 VARCHAR(8000))
  SET @vcExec = 'INSERT #tabAttr1
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  EXEC(@vcExec)
--Таблица Счета в финансовом органе
SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 2

CREATE TABLE #tabAttr2 ([CHECKED] INT, 
                        [UPD]     INT, 
                        [DEL]     INT, 
                        [LINK_SAVED_FORM] INT, 
                        [LINK_ROW] INT, 
                        [ORDERS]   INT, 
                        [CALC_ORDERS] INT, 
                        [PRINT_NULL] INT, 
                        [CODE] VARCHAR(50),  
                        COL1 VARCHAR(8000), COL2 VARCHAR(8000), 
                        COL3 VARCHAR(8000), COL4 VARCHAR(8000), 
                        COL5 VARCHAR(8000), COL6 VARCHAR(8000), 
                        COL7 VARCHAR(8000))
  SET @vcExec = 'INSERT #tabAttr2
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  EXEC(@vcExec)
--Таблица Счета в кассе учреждения
SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 3

CREATE TABLE #tabAttr3 ([CHECKED] INT, 
                        [UPD]     INT, 
                        [DEL]     INT, 
                        [LINK_SAVED_FORM] INT, 
                        [LINK_ROW] INT, 
                        [ORDERS]   INT, 
                        [CALC_ORDERS] INT, 
                        [PRINT_NULL] INT, 
                        [CODE] VARCHAR(50),  
                        COL1 VARCHAR(8000), COL2 VARCHAR(8000), 
                        COL3 NUMERIC(14,2), COL4 NUMERIC(14,2), 
                        COL5 NUMERIC(14,2), COL6 NUMERIC(14,2), 
                        COL7 VARCHAR(8000))
  SET @vcExec = 'INSERT #tabAttr3
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  EXEC(@vcExec)

-- Выгрузка подписей.
 SELECT   @vcOrgname = substring(dbo.[RA_XML_MASK](d.[FULL_NAME]),1,1000),
          @vcInn     = rtrim(ltrim(d.[INN])),
          @vcKpp     = rtrim(ltrim(d.[KPP])),
          @vcOkpo    = d.[OKPO],
          @vcOkato   = d.[OKATO],
          @iUchr_Link    = d.[UCHR_LINK]
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iLINK_ORG
 SELECT   @vcInn_Uchr     = isnull(d.[INN],''),
          @vcKpp_Uchr     = isnull(d.[KPP],''),
          @vcOkpo_Uchr    = isnull(d.[OKPO],''),
          @vcOrgName_Uchr = isnull(dbo.[RA_XML_MASK](d.[FULL_NAME]),'')
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iUchr_Link
 SELECT @vcKOD_ORGAN = [SONO],
        @vcPPP       = [VED]
 FROM PrintDoc_GetDepData2(@iLINK_ORG)   
 SELECT @vcSurname=ch.[FM],
        @vcFirstName=ch.[IM],
        @vcMiddleName=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Руководитель') ch
 WHERE ch.link_dep = @iLINK_ORG
 SELECT @vcSurname_GB=ch.[FM],
        @vcFirstName_GB=ch.[IM],
        @vcMiddleName_GB=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Главный бухгалтер') ch
 WHERE ch.link_dep = @iLINK_ORG
 IF (@vcSurname='' OR @vcSurname IS NULL OR LEN(@vcSurname)=0) SELECT @vcSurname='A'
 IF (@vcFirstName='' OR @vcFirstName IS NULL OR LEN(@vcFirstName)=0) SELECT @vcFirstName='A'
 IF (@vcInn IS NULL or @vcInn = '') SELECT @vcInn='9999999999'
 IF (@vcKpp IS NULL or @vcKpp = '') SELECT @vcKpp='999999999'
 IF @vcKOD_ORGAN IS NULL SELECT @vcKOD_ORGAN=''
--Дата начала   
SELECT @dBEGIN_DATE = A.[Begin_Date],
       @sYear = CAST(YEAR(@dBEGIN_DATE) AS VARCHAR(4)),  
       @vcDateRegl = convert(varchar(12), @dBEGIN_DATE+1, 104) 
  FROM dbo.[report_saved_forms] A
  WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM
--Дата документа
 SELECT @dFORM_DATE=GETDATE()
  
SET @vcCRC = RTRIM(CONVERT(VARCHAR(100), NEWID()))  
--Имя файла
SELECT @vcExec =  'NO_BOUCHR10.' + @vcFO + '_' +  @vcKOD_ORGAN+ '_' +  
                  @vcKOD_ORGAN+ '_' + @vcINN + @vcKPP + '_' +  
                  CAST(YEAR(@dFORM_DATE) AS VARCHAR(4)) + 
                  RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2) + RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '_' + @vcCRC,
       @vcFILE_NAME =  @vcExec + '.xml',
       @vcFILE_NAME_XSD =  @vcExec + '.xsd'
--Вставка XML
INSERT #tabXML([TXT]) VALUES ('<?xml  version ="1.0"  encoding ="windows-1251"?>')
INSERT #tabXML([TXT]) VALUES ('<Файл ИдФайл="'+@vcExec+'" '+'ВерсПрог="'+@vcProgramName+'" '+'ВерсФорм="'+@vcVersion+'">')
INSERT #tabXML([TXT]) VALUES ('  <Документ КНД="' + @vcFORM_CODE + '" ДатаДок="'+RIGHT('0'+CAST(DAY(@dBEGIN_DATE) AS VARCHAR(2)),2) + '.' +  
                               RIGHT('0'+CAST(MONTH(@dBEGIN_DATE) AS VARCHAR(2)),2)+ '.' + CAST(YEAR(@dBEGIN_DATE) AS VARCHAR(4))+
                               '" Период="34" ОтчетГод="'+CAST(@sYear AS VARCHAR(4))+'" НомКорр="0">')
INSERT #tabXML([TXT]) VALUES ('    <СвНП')
IF @vcOkpo<>'' AND LEN(@vcOkpo) BETWEEN 8 AND 10 
begin INSERT #tabXML([TXT]) VALUES (' ОКПО="'+LTRIM(RTRIM(@vcOkpo))+'"') end
IF @vcOkato<>'' AND LEN(@vcOkato)=11
begin INSERT #tabXML([TXT]) VALUES (' ОКАТО="'+@vcOkato+'"') END
IF @vcOkpo_Uchr<>'' AND LEN(@vcOkpo_Uchr) BETWEEN 8 AND 10 
begin INSERT #tabXML([TXT]) VALUES (' ОКПО_Учр="'+LTRIM(RTRIM(@vcOkpo_Uchr))+'"') end
IF @vcPPP<>'' AND LEN(@vcPPP)<4
INSERT #tabXML([TXT]) VALUES (' ГлаваБК="'+@vcPPP+'"')
INSERT #tabXML([TXT]) VALUES ('>')
INSERT #tabXML([TXT]) VALUES ('      <НПЮЛ НаимОрг="'+@vcOrgname+'" ИННЮЛ="'+LTRIM(RTRIM(@vcInn))+'" КПП="'+@vcKpp+'"')
IF @vcOrgName_Uchr<>'' 
begin INSERT #tabXML([TXT]) VALUES (' Учредит="'+@vcOrgName_Uchr+'"') end
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('</СвНП>')
INSERT #tabXML([TXT]) VALUES ('<Подписант ПрПодп="1">')
INSERT #tabXML([TXT]) VALUES ('<ФИО Фамилия="'+@vcSurname+'" Имя="'+@vcFirstName+'"')
IF @vcMiddleName<>''
INSERT #tabXML([TXT]) VALUES ('Отчество="'+@vcMiddleName+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
IF @vcSurname_GB<>'' AND @vcFirstName_GB<>''
begin
INSERT #tabXML([TXT]) VALUES ('<ФИОГлБух Фамилия="'+@vcSurname_GB+'" Имя="'+@vcFirstName_GB+'"')
IF @vcMiddleName_GB<>''
INSERT #tabXML([TXT]) VALUES ('Отчество="'+@vcMiddleName_GB+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
end
INSERT #tabXML([TXT]) VALUES ('</Подписант>')
INSERT #tabXML([TXT]) VALUES ('<СвОстатДС ВидДеят="' + @vcFO + '" ДатаОтч="' + @vcDateRegl + '" ОКЕИ="383"')
SELECT @val='',@str=''
SELECT @val=[COL3] FROM #tabAttr4 WHERE [CODE]='88888888888888888888888888888888888'
if @val<>'0.00' begin set @str = @str + 'ОстатокН_Вс="' + @val  + '"' end
SELECT @val=[COL4] FROM #tabAttr4 WHERE [CODE]='88888888888888888888888888888888888'
if @val<>'0.00' begin set @str = @str + ' СредПутН_Вс="' + @val  + '"' end
IF @str<>'' 
begin 
  INSERT #tabXML([TXT]) SELECT @str
end
INSERT #tabXML([TXT]) SELECT ' ОстатокК_Вс="' + COL5 + '" СредПутК_Вс="' + COL6 + '">' 
                      FROM #tabAttr4 WHERE [CODE]='88888888888888888888888888888888888'
--------------------------------------------------
INSERT #tabXML([TXT]) VALUES ('<СчетКредОрг КодСчет="020120000"')
IF EXISTS (SELECT * FROM #tabAttr1 WHERE COL2 LIKE '888888888%')                      
begin
SELECT @val='',@str=''
SELECT @val=[COL3] FROM #tabAttr1 WHERE [CODE]='88888888888888888888888888888888888'
if @val<>'0.00' begin set @str = @str + ' ОстатокН_Ит="' + @val  + '"' end
SELECT @val=[COL4] FROM #tabAttr1 WHERE [CODE]='88888888888888888888888888888888888'
if @val<>'0.00' begin set @str = @str + ' СредПутН_Ит="' + @val  + '"' end
IF @str<>'' 
begin 
  INSERT #tabXML([TXT]) SELECT @str
end
INSERT #tabXML([TXT]) SELECT ' ОстатокК_Ит="' + COL5 + '" СредПутК_Ит="' + COL6 + '">' 
                      FROM #tabAttr1 WHERE [CODE]='88888888888888888888888888888888888'
end
ELSE 
BEGIN
  INSERT #tabXML([TXT]) VALUES (' ОстатокК_Ит="0.00" СредПутК_Ит="0.00">')
END   
                         
IF EXISTS (SELECT * FROM #tabAttr1 WHERE COL2 NOT LIKE '888888888%')                      
begin
DECLARE T_CURSOR CURSOR FOR      
SELECT CODE FROM #tabAttr1 WHERE COL2 NOT LIKE '888888888%'
OPEN T_CURSOR      
FETCH NEXT FROM T_CURSOR INTO @CODE      
WHILE @@FETCH_STATUS = 0         
BEGIN  
  --Код валюты?
  INSERT #tabXML([TXT]) SELECT '<НомСчет НомСчет="' + COL1 + '" КодСчет="' + COL2 + '"' FROM #tabAttr1 WHERE [CODE]=@CODE
  SELECT @val='',@str=''
  SELECT @val=[COL3] FROM #tabAttr1 WHERE [CODE]=@CODE
  if @val<>'0.00' begin set @str = @str + ' ОстатокН="' + @val  + '"' end
  SELECT @val=[COL4] FROM #tabAttr1 WHERE [CODE]=@CODE
  if @val<>'0.00' begin set @str = @str + ' СредПутН="' + @val  + '"' end
  IF @str<>'' 
  begin 
    INSERT #tabXML([TXT]) SELECT @str
  end
  INSERT #tabXML([TXT]) SELECT ' ОстатокК="' + COL5 + '" СредПутК="' + COL6 + '"/>' 
                        FROM #tabAttr1 WHERE [CODE]=@CODE
FETCH NEXT FROM T_CURSOR INTO @CODE      
END      
CLOSE T_CURSOR      
DEALLOCATE T_CURSOR   
END
ELSE  
BEGIN
  INSERT #tabXML([TXT]) VALUES ('<НомСчет НомСчет="" КодСчет="' + @vcFO + '20120000"')
  INSERT #tabXML([TXT]) VALUES (' ОстатокК="0.00" СредПутК="0.00"/>')
END   
INSERT #tabXML([TXT]) VALUES ('</СчетКредОрг>')
--------------------------------------------------
INSERT #tabXML([TXT]) VALUES ('<СчетФинОрг КодСчет="020110000"')
IF EXISTS (SELECT * FROM #tabAttr2 WHERE COL2 LIKE '888888888%')                      
begin
SELECT @val='',@str=''
SELECT @val=[COL3] FROM #tabAttr2 WHERE [CODE]='88888888888888888888888888888888888'
if @val<>'0.00' begin set @str = @str + ' ОстатокН_Ит="' + @val  + '"' end
SELECT @val=[COL4] FROM #tabAttr2 WHERE [CODE]='88888888888888888888888888888888888'
if @val<>'0.00' begin set @str = @str + ' СредПутН_Ит="' + @val  + '"' end
IF @str<>'' 
begin 
  INSERT #tabXML([TXT]) SELECT @str
end
INSERT #tabXML([TXT]) SELECT ' ОстатокК_Ит="' + COL5 + '" СредПутК_Ит="' + COL6 + '">' 
                      FROM #tabAttr2 WHERE [CODE]='88888888888888888888888888888888888'
END
ELSE
BEGIN
  INSERT #tabXML([TXT]) VALUES (' ОстатокК_Ит="0.00" СредПутК_Ит="0.00">')
END   
                       
IF EXISTS (SELECT * FROM #tabAttr2 WHERE COL2 NOT LIKE '888888888%')                      
begin
DECLARE T_CURSOR CURSOR FOR      
SELECT CODE FROM #tabAttr2 WHERE CODE NOT LIKE '888888888%'
OPEN T_CURSOR      
FETCH NEXT FROM T_CURSOR INTO @CODE      
WHILE @@FETCH_STATUS = 0         
BEGIN  
  --Код валюты?
  INSERT #tabXML([TXT]) SELECT '<НомСчет НомСчет="' + COL1 + '" КодСчет="' + COL2 + '"' FROM #tabAttr2 WHERE [CODE]=@CODE
  SELECT @val='',@str=''
  SELECT @val=[COL3] FROM #tabAttr2 WHERE [CODE]=@CODE
  if @val<>'0.00' begin set @str = @str + ' ОстатокН="' + @val  + '"' end
  SELECT @val=[COL4] FROM #tabAttr2 WHERE [CODE]=@CODE
  if @val<>'0.00' begin set @str = @str + ' СредПутН="' + @val  + '"' end
  IF @str<>'' 
  begin 
    INSERT #tabXML([TXT]) SELECT @str
  end
  INSERT #tabXML([TXT]) SELECT ' ОстатокК="' + COL5 + '" СредПутК="' + COL6 + '"/>' 
                        FROM #tabAttr2 WHERE [CODE]=@CODE
FETCH NEXT FROM T_CURSOR INTO @CODE      
END      
CLOSE T_CURSOR      
DEALLOCATE T_CURSOR
END    
ELSE  
BEGIN
  INSERT #tabXML([TXT]) VALUES ('<НомСчет НомСчет="" КодСчет="' + @vcFO + '20110000"')
  INSERT #tabXML([TXT]) VALUES (' ОстатокК="0.00" СредПутК="0.00"/>')
END   
INSERT #tabXML([TXT]) VALUES ('</СчетФинОрг>')
--------------------------------------------------
INSERT #tabXML([TXT]) VALUES ('<СредКасУчр КодСчет="020134000"')
IF EXISTS (SELECT * FROM #tabAttr3 WHERE COL2 LIKE '888888888%')                      
begin
SELECT @val='',@str=''
SELECT @val=[COL3] FROM #tabAttr3 WHERE [CODE]='88888888888888888888888888888888888'
if @val<>'0.00' begin set @str = @str + ' ОстатокН_Ит="' + @val  + '"' end
IF @str<>'' 
begin 
  INSERT #tabXML([TXT]) SELECT @str
end
INSERT #tabXML([TXT]) SELECT ' ОстатокК_Ит="' + COL5 + '">' 
                      FROM #tabAttr3 WHERE [CODE]='88888888888888888888888888888888888'
END
ELSE 
BEGIN
  INSERT #tabXML([TXT]) VALUES (' ОстатокК_Ит="0.00">')
END   
                         
IF EXISTS (SELECT * FROM #tabAttr3 WHERE COL2 NOT LIKE '888888888%')                      
begin
DECLARE T_CURSOR CURSOR FOR      
SELECT CODE FROM #tabAttr3 WHERE COL2 NOT LIKE '888888888%'
OPEN T_CURSOR      
FETCH NEXT FROM T_CURSOR INTO @CODE      
WHILE @@FETCH_STATUS = 0         
BEGIN  
  --Код валюты?
  INSERT #tabXML([TXT]) SELECT '<НомСчет КодСчет="' + COL2 + '"' FROM #tabAttr3 WHERE [CODE]=@CODE
  SELECT @val='',@str=''
  SELECT @val=[COL3] FROM #tabAttr3 WHERE [CODE]=@CODE
  if @val<>'0.00' begin set @str = @str + ' ОстатокН="' + @val  + '"' end
  if @str<>'' 
  begin 
    INSERT #tabXML([TXT]) SELECT @str
  end
  INSERT #tabXML([TXT]) SELECT ' ОстатокК="' + COL5 + '"/>' 
                        FROM #tabAttr3 WHERE [CODE]=@CODE
FETCH NEXT FROM T_CURSOR INTO @CODE      
END      
CLOSE T_CURSOR      
DEALLOCATE T_CURSOR  
END  
ELSE  
BEGIN
  INSERT #tabXML([TXT]) VALUES ('<НомСчет НомСчет="" КодСчет="' + @vcFO + '20134000"')
  INSERT #tabXML([TXT]) VALUES (' ОстатокК="0.00"/>')
END   
INSERT #tabXML([TXT]) VALUES ('</СредКасУчр>')
---------------------------------------------------
INSERT #tabXML([TXT]) VALUES ('</СвОстатДС>')
INSERT #tabXML([TXT]) VALUES ('  </Документ>')
INSERT #tabXML([TXT]) VALUES ('</Файл>')
----------------------------------------
INSERT #Files ([TXT], [NAMEFILE],  [NAMEFILE_ARH], [OrderFile],[LINK_SAVED_FORM])
SELECT [TXT],@vcFILE_NAME,@vcFILE_NAME_XSD,[ORDERS],@iLINK_SAVED_FORM
FROM #tabXML
DROP TABLE #tabXML  


GO


GRANT EXECUTE ON dbo.[RA_EXPORT_FORM_FNS_779] 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
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE dbo.BB_PRINT_PP @cBufferID varchar(100)
AS BEGIN

	SELECT LINK_DOC = P.LINK,
		DataD = P.DATE, 
		Nom_Por = P.NUMBER, 
		Vidpl = CASE WHEN P.KIND IS NULL THEN ' ' ELSE LTRIM(RTRIM(P.KIND)) END, 
		[STATUS] = ISNULL(PA.STATUS, ''), 
		SUM_DOC = ISNULL(P.SUMMA, 0.00), 
		VID_OPL = CASE WHEN P.PAYKIND IS NULL THEN ' ' ELSE P.paykind END, 
		NAZ_PL = CASE WHEN P.REASON IS NULL THEN ' ' ELSE P.REASON END,
		SROK_PL = P.SROK, 
		OCHER = CASE WHEN P.[ORDER] IS NULL THEN ' ' ELSE P.[ORDER] END,
		
		--Плательщик
		PLATEL = dbo.BB_DEP_NAME_FOR_SHABLON(isnull(APO.SHABLON_D,APOD.SHABLON_D), default, P.S_ACC_LINK), 
		--APO.SHABLON_D,APOD.SHABLON_D, 
		INN_PL = isnull(P.S_INN, ''), 
		KPP_PL = CASE WHEN ISNULL(P.PRINT_KPP, 0) = 1 THEN P.S_KPP ELSE '' END, 
		SCH_PLAT = isnull(P.S_SCH_K,P.S_ACC_NUM), 
		BIK_PLAT = isnull(P.S_BIK, SB.BIK), 
		BANK_PLAT = case isnull(DPO.FullBank, 0) when 0 then isnull(P.S_BANK, SB.name) else isnull(P.S_FBANK, SB.FNAME) end + ' ' + case isnull(DPO.Bank_cityP, 0) when 0 then '' else isnull(P.S_BANK_CITY, SB.CITY) end,
		SCH_B_PLAT = isnull(P.S_SCH_B, SB.KS), 
			
		--Получатель
		POLUCH = dbo.BB_DEP_NAME_FOR_SHABLON(CASE WHEN DOH_CODE is not null or PA.OKATO is not null or P_REASON is not null or PA.PERIOD is not null or TREBNUM is not null or TREBDATE is not null or P_TYPE is not null or STATUS is not null THEN isnull(APO.SHABLON_N, APOD.SHABLON_N) else isnull(APO.SHABLON_S, APOD.SHABLON_S) end, default, P.D_ACC_LINK), 
		INN_POL = ISNULL(P.D_INN, ''),
		KPP_POL = CASE WHEN ISNULL(P.PRINT_KPP, 0) = 1 THEN P.D_KPP ELSE '' END, 
		SCH_POL = isnull(P.D_SCH_K,P.D_ACC_NUM), 
		BIK_POL = isnull(P.D_BIK, DB.BIK), 
		BANK_POL = rtrim(case isnull(DPO.FullBank_R, 0) when 0 then isnull(P.D_BANK, DB.name) else isnull(P.D_FBANK, DB.FNAME) end) + ' ' + case isnull(DPO.Bank_city, 0) when 0 then '' else isnull(P.D_BANK_CITY, DB.CITY) end, 
		SCH_B_POL = isnull(P.D_SCH_B, DB.KS), 
		
		--Назначение платежа
		KOMM1 = case P.BK_IN_TGT when 1 then rtrim(replace(replace(replace(replace(replace(replace(
												case isnull(ltrim(rtrim(P.BO_NUM)),'') when '' then rtrim(dbo.BB_DDELIM_DEL(isnull(APO.LS_FMT, APOD.LS_FMT),'<БО>')) else isnull(APO.LS_FMT, APOD.LS_FMT) end, 
												'<БО>', isnull(ltrim(rtrim(P.BO_NUM)),'')),
												'<Счет>', case P.S_ACC_TYPE when 1 then '' else rtrim(P.S_ACC_NUM) end),
												'<Перевод_строки>', '
)'),												'<БК>',rtrim(dbo.BB_BK_FOR_SHABLON(P.LINK, isnull(APO.SHABLON_BK, APOD.SHABLON_BK),isnull(APO.DELIM, APOD.DELIM),isnull(APO.DELIM5, APOD.DELIM5)))),
													--'<БК>',/*str(P.S_ACC_LINK) + '#' +*/ APO.SHABLON_BK /*+ '#' + APO.DELIM + '#' + APO.DELIM5*/),
												'<Руб>',rtrim(ltrim(str(floor(P.SUMMA))))),
												'<Коп>', right('00' + rtrim(ltrim(str((P.SUMMA - floor(P.SUMMA)) * 100))),2))) + ' ' 
																				 
		
				else '' end + ltrim(replace(P.TARGETTEXT,char(13),'')) + ' ' + ltrim(dbo.PrintPlatporGetNDSString(P.LINK, 1)), 
		--[Num_BO] = BO_NUM,
		--targettext = targettext,
		
		-- Налоговый платеж
		DOH_CODE = rtrim(ISNULL(replace(PA.DOH_CODE,'.',''), '')) + ISNULL(PA.SGU_CODE, ''), 
		OKATO = ISNULL(PA.OKATO, ''), 
		P_REASON = ISNULL(PA.P_REASON, ''),
		PERIOD = ISNULL(PA.PERIOD, ''),
		TREBNUM = ISNULL(PA.TREBNUM, ''),
		TREBDATE = CASE WHEN PA.ZERODATE = 1 THEN '0' ELSE ISNULL(convert(varchar(10), PA.TREBDATE,  104), '') END, 
		P_TYPE = ISNULL(PA.P_TYPE, ''),  
		STATUS = ISNULL(PA.STATUS, ''), 
		DPP_REAL = '', 
		SUMPROP = '', 
		SUMREAL = '',
		UIN_CODE,
		
		-- Настройки
		month_prop = ISNULL(DPO.MONTH, 0), 
		ShowPoint = ISNULL(DPO.POINT, 1), 
		ShowZero = ISNULL(DPO.ZERO, 0),
		ShowEqual = ISNULL(DPO.Equal, 0),
		
		DPO.SHOW_KOP,
		--DPO.SHOW_RUB,
		DPO.SUM_UCASE,
		--APO.DELIM,
		--APO.DELIM2,
		--APO.DELIM3,
		--APO.SHOW_SM,
		--APO.DELIM5,
		--APO.SUMALONE
--		[InnAlone] = 0,
		BO = '№ ' + rtrim(FC.NUMBER) + ' от ' + convert(varchar(10), FC.DATE, 104)
		
	FROM dbo.DOCUMENTS_PAY P
	inner join dbo.DOCUMENTS_PAY_ADD PA on P.LINK = PA.LINK
	inner join dbo.BufferGetTableByID(@cBufferID) B on P.LINK = B.LINK
	inner join dbo.DOCUMENTS_PAY_OPTIONS DPO on 1=1
	left join dbo.TREASURY_ACCOUNTS DTA on DTA.LINK = P.D_SCH_K_LINK 
	left join dbo.BANKS DB on DB.LINK = DTA.BANK_LINK
	left join dbo.TREASURY_ACCOUNTS STA on STA.LINK = P.S_SCH_K_LINK 
	left join dbo.BANKS SB on SB.LINK = STA.BANK_LINK
	left join dbo.BB_PAY_ACC_OPTIONS APO on APO.LINK_ACC = P.S_ACC_LINK
	left join dbo.DOCUMENTS_PAY_ACC_OPTIONS APOD on APOD.OSN = 1
	left join dbo.DEPARTMENT_ACCOUNTS DA on APOD.LINK_ACC = DA.LINK and P.S_ACC_TYPE = DA.TYPE
	left join dbo.FINANS_CONTRACT_AND_CHANGES FC on FC.LINK = P.DOG_LINK
	where P.S_ACC_TYPE = DA.TYPE
	EXEC dbo.BufferClear @cBufferID

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

GO

CREATE PROCEDURE dbo.RSA_4FSS_09022012_PREPARE
	@Res float output, @varcStr varchar(250), @vardBegin datetime = '20050101', @vardEnd datetime = '20051231', @variCol int, @variRow int, @variLSF int
AS 

EXEC dbo.BufferClear

DECLARE @OUT_VAL NUMERIC(20), @START_DATE DATETIME, @END_DATE DATETIME, @DEP_LINK INT

DECLARE --Для выравнивания погрешности
	@C3N NUMERIC(18,6), @C4N NUMERIC(18,6), @C5N NUMERIC(18,6), @C6N 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 @res = 0
SELECT @START_DATE = @vardBegin, @END_DATE = @vardEnd

DECLARE @BYearDate	datetime
SET @BYearDate = dbo.DateBeginOfYear (@START_DATE)

declare @EndYear datetime
Set @EndYear = dbo.DateEndOfYear(@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(18,6) default 0.00, DED_M numeric(18,6) default 0.00, INV_M numeric(18,6) default 0.00, SUMMA numeric(18,6) default 0.00, WAY_CALC int default 0.00, REF_PHYS_PERS int default 0, KATEG TINYINT)

Insert InTo #SPR_ESN ([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG)
Select [MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG
from dbo.SA_ESN_VIEW(@nYEAR, @nMONTH3, @DEP_LINK, 0) WHERE WAY_CALC = 2
---Суммы по договорникам
INSERT INTO #SPR_ESN 
	([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG)
SELECT 
	MONTH(G.[DATE]) AS MONTH_BASE, GT.SUMMA_BASE, 0, 0, GT.SUMMA, P.WAY_CALC, GT.PERS_LINK,
	KATEG = (CASE WHEN I.LINK IS NULL THEN (F.ENVD + 1) ELSE 3 END)
FROM 
	dbo.SDOC G
	INNER JOIN dbo.SDOC_DGH_TABLE GT ON G.LINK = GT.LINK_UP
	INNER JOIN dbo.PAYS P ON P.LINK = GT.LINK_PAY
	INNER JOIN dbo.SAL_SFIN F ON F.LINK = GT.LINK_VKR
	LEFT JOIN dbo.pers_invalid I ON GT.PERS_LINK = I.PERS_LINK 
	AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH(G.[DATE]),@nYEAR)) BETWEEN I.DATE_BEGIN AND COALESCE(I.DATE_END,'29990101')
WHERE
	G.[OBJECT] =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'DOCUMENTS_DGH')
	AND GT.[OBJECT] = 3
	AND FLAG_JC = 1
	AND P.WAY_CALC = 2
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3
	AND LINK_DEP = @DEP_LINK


/*РАЗДЕЛ 2.1*/
DECLARE @BDate datetime, @EndDate datetime, @EDate datetime, @NAvgCount int

SELECT @BDate = @START_DATE, @EndDate = @END_DATE
SET @EDate = dateadd(year,1,convert(varchar, YEAR(@BDate))+'0101')

CREATE TABLE #RES2(CODE_STR VARCHAR(10), BASE_FSS NUMERIC(18,6), CNT_FSS INT, CNT_FEM INT)

--ОСТАТКИ ПО СЧЁТУ 303.02 НА НАЧАЛО ГОДА
CREATE TABLE #REST_30302_BY ([DATE] DATETIME, 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.02%'

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @LINK_ACC
WHILE (@@fetch_status <> -1)
BEGIN

	IF (@@fetch_status <> -2)
	BEGIN

		INSERT INTO #REST_30302_BY ([DATE], REST)
		SELECT @BYearDate, REST = coalesce(sum(K_SUMMA)-sum(D_SUMMA),0) 
		FROM dbo.ARestGroupedTableByDate (@BYearDate, @LINK_ACC, DEFAULT)
		WHERE DEP_LINK = @DEP_LINK
	END

	FETCH NEXT FROM @Cur1 INTO @LINK_ACC
END

CLOSE @Cur1
DEALLOCATE @Cur1

--ОСТАТКИ ПО СЧЁТУ 303.02 НА КОНЕЦ ОТЧЕТНОГО КВАРТАЛА
DECLARE @QV_DATE DATETIME
SET @QV_DATE = @END_DATE+1

SET @Cur1 = CURSOR FORWARD_ONLY

FOR SELECT LINK FROM dbo.S_ACCOUNTS WHERE CODE LIKE '303.02%'

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @LINK_ACC
WHILE (@@fetch_status <> -1)
BEGIN

	IF (@@fetch_status <> -2)
	BEGIN

		INSERT INTO #REST_30302_BY ([DATE], REST)
		SELECT @END_DATE, REST = coalesce(sum(K_SUMMA)-sum(D_SUMMA),0) 
		FROM dbo.ARestGroupedTableByDate (@QV_DATE, @LINK_ACC, DEFAULT)
		WHERE DEP_LINK = @DEP_LINK
	END

	FETCH NEXT FROM @Cur1 INTO @LINK_ACC
END

CLOSE @Cur1
DEALLOCATE @Cur1

INSERT INTO #RES2 (CODE_STR, BASE_FSS, CNT_FSS, CNT_FEM)
SELECT '0101', SUM(REST), 0, 0 FROM #REST_30302_BY WHERE [DATE] = @BYearDate HAVING SUM(REST) > 0

INSERT INTO #RES2 (CODE_STR, BASE_FSS, CNT_FSS, CNT_FEM)
SELECT '0112', -SUM(REST), 0, 0 FROM #REST_30302_BY WHERE [DATE] = @BYearDate HAVING SUM(REST) < 0

INSERT INTO #RES2 (CODE_STR, BASE_FSS, CNT_FSS, CNT_FEM)
SELECT '0109', -SUM(REST), 0, 0 FROM #REST_30302_BY WHERE [DATE] = @END_DATE HAVING SUM(REST) < 0

INSERT INTO #RES2 (CODE_STR, BASE_FSS, CNT_FSS, CNT_FEM)
SELECT '0119', SUM(REST), 0, 0 FROM #REST_30302_BY WHERE [DATE] = @END_DATE HAVING SUM(REST) > 0
/********СРЕДНЕСПИСОЧНАЯ ЧИСЛЕННОСТЬ**********/

/* Среднесписочная численность работающих инвалидов */
Set @NAvgCount = convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 1, DEFAULT))

INSERT INTO #RES2
SELECT '3', 0, @NAvgCount, 0

/* Среднесписочная численность мужчин и женщин */
Set @NAvgCount = convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 0, DEFAULT))
INSERT INTO #RES2
SELECT '1', 0, @NAvgCount, 0

/* Среднесписочная численность женщин */
INSERT INTO #RES2
SELECT '2', 0, convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 2, 1, 0, DEFAULT)), 0

/* Среднесписочная численность работающих во вредных условиях */
INSERT INTO #RES2
SELECT '4', 0, convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 2, DEFAULT)), 0

--select SUM(SUMMA) from #SPR_ESN where MONTH_BASE = @nMONTH1
--select * from #SPR_ESN
--Р1.ТАБЛИЦА 1
--Начислено ЕСН. На НАч квартала
INSERT INTO #RES2 --код=табл. 02, строка 3_1
SELECT '0121', ISNULL(SUM(SUMMA),0), 0, 0 FROM #SPR_ESN WHERE MONTH_BASE < @nMONTH1 

--Начислено ЕСН. 1 мес
INSERT INTO #RES2 --код=табл. 02, строка 3_3
SELECT '0123', ISNULL(SUM(SUMMA),0), 0, 0 FROM #SPR_ESN WHERE MONTH_BASE = @nMONTH1

--Начислено ЕСН. 2 мес
INSERT INTO #RES2 --код=табл. 02, строка 3_4
SELECT '0124', ISNULL(SUM(SUMMA),0), 0, 0 FROM #SPR_ESN WHERE MONTH_BASE = @nMONTH2
--
--Начислено ЕСН. 3 мес
INSERT INTO #RES2 --код=табл. 02, строка 3_5
SELECT '0125', ISNULL(SUM(SUMMA),0), 0, 0 FROM #SPR_ESN WHERE MONTH_BASE = @nMONTH3

--Р1.ТАБЛИЦА 2

DECLARE 
	@P02010 INT, --Количество больничных
	@P02013 NUMERIC(18,2),  --Количество больничных дней 
	@P02014 NUMERIC(18,2), --Сумма по больничным за счет ФСС

	@P02020 INT, --Количество больничных по внешнему совместительству
	@P02023 NUMERIC(18,2),  --Количество больничных дней по внешнему совместительству
	@P02024 NUMERIC(18,2), --Сумма по больничным за счет ФСС по внешнему совместительству
	
	@P02030 INT, --Количество больничных По беременности и родам
	@P02033 NUMERIC(18,2),  --Количество По беременности и родам дней
	@P02034 NUMERIC(18,2), --Сумма По беременности и родам за счет ФСС

	@P02040 INT, -- Количество больничных по беременности и родам по внешнему совместительству
	@P02043 NUMERIC(18,2),  --Количество дней по беременности и родам по внешнему совместительству
	@P02044 NUMERIC(18,2),  --Сумма по беременности и родам за счет ФСС по внешнему совместительству

	-- Ежемесячное пособие по уходу за ребенком по основному месту работы за первым
	@P02080 INT, --количество получателей
	@P02083 NUMERIC(18,2),  -- количество произведенных выплат
	@P02084 NUMERIC(18,2), -- сумма расходов

	-- Ежемесячное пособие по уходу за ребенком по основному месту работы за вторым и последующим
	@P02090 INT, --количество получателей
	@P02093 NUMERIC(18,2),  -- количество произведенных выплат
	@P02094 NUMERIC(18,2) -- сумма расходов

---	
SELECT 
	@P02010 = COUNT(DISTINCT (CASE WHEN COALESCE(A.DEKRET,0) = 1 THEN NULL ELSE A.LINK END) ),
	@P02020 = COUNT( DISTINCT CASE WHEN STATUS_EMPL = 3 AND COALESCE(A.DEKRET,0) = 0 THEN A.LINK ELSE NULL END), 
	@P02030 = COUNT(DISTINCT (CASE WHEN COALESCE(A.DEKRET,0) = 1 THEN A.LINK ELSE NULL END) ), 
	@P02040 = COUNT( DISTINCT CASE WHEN STATUS_EMPL = 3 AND COALESCE(A.DEKRET,0) = 1 THEN A.LINK ELSE NULL END) 
FROM 
	DBO.DOCUMENTS_ADD_ARCHE A INNER JOIN dbo.SD_EMPL E ON A.REF_EMPL = E.LINK
	INNER JOIN DBO.SDOC_ADIS_TABLE1 T ON T.LINK_UP = A.LINK AND T.PAYER = 0
	inner join dbo.DIS d on d.link = a.ref_arhe 
WHERE 
	A.LINK_DEP = @DEP_LINK 
	AND A.FLAG_JC = 1 --НАЧИСЛЕННЫЕ
	AND YEAR(A.[DATE]) = YEAR(@BYearDate) --НАЧИСЛЕННЫЕ В ЗАДАННОМ ГОДУ
	AND MONTH(A.[DATE]) <= MONTH(@END_DATE) --НАЧИСЛЕННЫЕ ПО ЗАДАННЫЙ МЕСЯЦ
	and isnull(D.REF_DOC,0) = 0

---	
SELECT 
	@P02013 = SUM( (CASE WHEN COALESCE(A.DEKRET,0) = 1 THEN 0 ELSE 1 END) * ISNULL(A.FSS_DAYS,0)), --(DATEDIFF(DAY,T.DATE1,T.DATE2)+1) ),	
	@P02023 = SUM( (CASE WHEN STATUS_EMPL = 3 THEN 1 ELSE 0 END) * (CASE WHEN COALESCE(A.DEKRET,0) = 1 THEN 0 ELSE 1 END)  * ISNULL(A.FSS_DAYS,0)),--* (DATEDIFF(DAY,T.DATE1,T.DATE2)+1) ),	
	--по беременности и родам записывать все оплачиваемые дни, а не только те, которые входят в оплачиваемый период
	@P02033 = SUM(  COALESCE(A.DEKRET,0)  * ISNULL(A.FSS_DAYS,0)),--* (DATEDIFF(DAY,T.DATE1,T.DATE2)+1) ),	
	--по беременности и родам записывать все оплачиваемые дни, а не только те, которые входят в оплачиваемый период
	@P02043 = SUM( (CASE WHEN STATUS_EMPL = 3  AND COALESCE(A.DEKRET,0) = 1 THEN 1 ELSE 0 END)  * ISNULL(A.FSS_DAYS,0))--* (DATEDIFF(DAY,T.DATE1, T.DATE2)+1) )	
FROM 
	DBO.DOCUMENTS_ADD_ARCHE A INNER JOIN dbo.SD_EMPL E ON A.REF_EMPL = E.LINK 
WHERE 
	LINK_DEP = @DEP_LINK 
	AND FLAG_JC = 1 --НАЧИСЛЕННЫЕ
	AND YEAR(DATE) = YEAR(@BYearDate) --НАЧИСЛЕННЫЕ В ЗАДАННОМ ГОДУ
	AND MONTH(DATE) <= MONTH(@END_DATE) --НАЧИСЛЕННЫЕ ПО ЗАДАННЫЙ МЕСЯЦ

SELECT P.F4FSS, E.[STATUS], CNT_EMPL = COUNT(DISTINCT J.LINK_EMPL), CNT = COUNT( J.LINK_EMPL),SUMMA = SUM(SUMMA), CNT_DAYS = SUM([DAYS])
INTO #ATR_4FSS
FROM 
	dbo.ATRIBUT_F4FSS A
	INNER JOIN dbo.PAYS P ON A.LINK = P.F4FSS
	INNER JOIN dbo.CALCULATE_JURNAL J ON P.LINK = J.LINK_PAYS
	INNER JOIN DBO.SA_EMPLS_INFO(@END_DATE, DEFAULT) E ON E.EMPL_LINK = J.LINK_EMPL 	
WHERE
	Year(period_begin) = @nYEAR and Month(period_begin) <= @nMONTH3
	and J.LINK_DEP = @DEP_LINK
	and P.[OBJECT] = 1	
	and P.F4FSS > 1
	AND J.LINK_EKR = (SELECT LINK FROM KOSGU WHERE CODE = '213')	
GROUP BY 	
	P.F4FSS, E.[STATUS]

--ВЫПЛАТА ПОСОБИЙ По временной нетрудоспособности
-----Число дней на больничном
INSERT INTO #RES2 --код=табл. 02, строка 01
SELECT '0201', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 2),0), --ISNULL(@P02014,0), 
	@P02013, @P02010
	

-----Число дней на больничном по внешнему совместительству
INSERT INTO #RES2 --код=табл. 02, строка 02
SELECT '0202', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 2 AND [STATUS] = 3),0),--ISNULL(@P02024,0), 
	@P02023, @P02020

-----Число дней по берем и родам
INSERT INTO #RES2 --код=табл. 02, строка 03
SELECT '0203', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 3),0),--@P02034, 
	@P02033, @P02030


-----Число дней по берем и родам по внешнему совместительству
INSERT INTO #RES2 --код=табл. 02, строка 04
SELECT '0204', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 3 AND [STATUS] = 3),0),--@P02044, 
	@P02043, @P02040

INSERT INTO #RES2
SELECT '0205', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 4),0),
	ISNULL((SELECT SUM(CNT) FROM #ATR_4FSS WHERE F4FSS = 4),0),	
	ISNULL((SELECT SUM(CNT_EMPL) FROM #ATR_4FSS WHERE F4FSS = 4),0)	

INSERT INTO #RES2
SELECT '0206', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 5),0),
	ISNULL((SELECT SUM(CNT) FROM #ATR_4FSS WHERE F4FSS = 5),0),	
	ISNULL((SELECT SUM(CNT_EMPL) FROM #ATR_4FSS WHERE F4FSS = 5),0)	

---- Ежемесячное пособие по уходу за ребенком по основному месту работы
INSERT INTO #RES2
SELECT '0208',
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 6),0),
	ISNULL((SELECT SUM(CNT) FROM #ATR_4FSS WHERE F4FSS = 6),0),	
	ISNULL((SELECT SUM(CNT_EMPL) FROM #ATR_4FSS WHERE F4FSS = 6),0)	

INSERT INTO #RES2
SELECT '0209',
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 7),0),
	ISNULL((SELECT SUM(CNT) FROM #ATR_4FSS WHERE F4FSS = 7),0),	
	ISNULL((SELECT SUM(CNT_EMPL) FROM #ATR_4FSS WHERE F4FSS = 7),0)	

INSERT INTO #RES2
SELECT '0210', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 8),0),
	ISNULL((SELECT SUM(CNT) FROM #ATR_4FSS WHERE F4FSS = 8),0),	
	ISNULL((SELECT SUM(CNT_EMPL) FROM #ATR_4FSS WHERE F4FSS = 8),0)	

INSERT INTO #RES2
SELECT '0211', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 9),0),
	ISNULL((SELECT SUM(CNT) FROM #ATR_4FSS WHERE F4FSS = 9),0),	
	ISNULL((SELECT SUM(CNT_EMPL) FROM #ATR_4FSS WHERE F4FSS = 9),0)		

--Р1.ТАБЛИЦА 3

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 = 2)

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 GT.PERS_LINK, MONTH(G.[DATE]) AS MONTH_BASE, 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
WHERE 
	FLAG_JC = 1
	AND GT.WAY_CALC  = 2
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3 
GROUP BY GT.PERS_LINK, MONTH(G.[DATE])

CREATE TABLE #DGH_CJ (PERS_LINK INT, PERIOD_BEGIN DATETIME, SUMMA NUMERIC(18,6))
INSERT INTO #DGH_CJ (PERS_LINK, PERIOD_BEGIN, SUMMA)
SELECT PERS_LINK, PERIOD_BEGIN, SUM(SUMMA)
FROM dbo.CALCULATE_JURNAL CJ
	INNER JOIN DBO.PERSON P1 ON P1.LINK = CJ.PERS_LINK
	INNER JOIN DBO.PAYS P ON P.LINK = CJ.LINK_PAYS
WHERE
	yEAR(CJ.period_begin) = @nYEAR
	AND CJ.LINK_DEP = @DEP_LINK
	AND P.[OBJECT] = 1
GROUP BY
	PERS_LINK, PERIOD_BEGIN


---------
SELECT MON, SUMMA_ALL = SUM(SUMMA_ALL), SUMMA_NO = SUM(SUMMA_NO)
INTO #SALARY_SUM2
FROM 
(
select 
	MON = Month(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) --на которые не начисляются страховые взносы
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
	LEFT JOIN @StBase2 B ON B.LINK = cj.LINK_PAYS
where 	
	Year(CJ.period_begin) = @nYEAR and Month(CJ.period_begin) <= @nMONTH3 
	and CJ.LINK_DEP = @DEP_LINK
	and P.[OBJECT] = 1
GROUP BY
	Month(CJ.PERIOD_BEGIN)
UNION ALL	
select 
	MON = Month(CJ.PERIOD_BEGIN),
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(SUMMA - ISNULL(B.SUMMA_BASE,0)) --на которые не начисляются страховые взносы
from 
	#DGH_CJ CJ
	LEFT JOIN #DGH_FAKT_BASE B ON B.PERS_LINK = CJ.PERS_LINK AND B.MONTH_BASE = Month(CJ.PERIOD_BEGIN)
where 	
	Month(CJ.period_begin) <= @nMONTH3 
GROUP BY
	Month(CJ.PERIOD_BEGIN)
) AS T
GROUP BY 
	MON
	
--Суммы выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со ст.7 Федерального закона от 24 июля 2009 г. № 212-ФЗ
INSERT INTO #RES2 SELECT '030103', SUM(SUMMA_ALL), 0, 0 FROM #SALARY_SUM2
INSERT INTO #RES2 SELECT '030104', SUM(SUMMA_ALL), 0, 0 FROM #SALARY_SUM2 WHERE MON = @nMONTH1
INSERT INTO #RES2 SELECT '030105', SUM(SUMMA_ALL), 0, 0 FROM #SALARY_SUM2 WHERE MON = @nMONTH2
INSERT INTO #RES2 SELECT '030106', SUM(SUMMA_ALL), 0, 0 FROM #SALARY_SUM2 WHERE MON = @nMONTH3


--select * from #RES2 where CODE_STR in ('030103', '030104', '030105', '030106')
DECLARE @TMP_VAL NUMERIC(18,2)
--Суммы, не подлежащие обложению страховыми взносами в соответствии со ст.9 Федерального закона от 24 июля 2009 г. № 212-ФЗ
--INV_M теперь содержит только льготы (100 тыс инвалидам теперь нет)
SET @TMP_VAL = ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN ) ,0) + ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM2),0)
INSERT INTO #RES2 VALUES('030203', @TMP_VAL, 0, 0)

SET @TMP_VAL = ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN  WHERE MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM2 WHERE MON = @nMONTH1),0)
INSERT INTO #RES2 VALUES('030204', @TMP_VAL, 0, 0)

SET @TMP_VAL = ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN  WHERE MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM2 WHERE MON = @nMONTH2),0)
INSERT INTO #RES2 VALUES('030205', @TMP_VAL, 0, 0)

SET @TMP_VAL = ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN  WHERE MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM2 WHERE MON = @nMONTH3),0)
INSERT INTO #RES2 VALUES('030206', @TMP_VAL, 0, 0)

--select * from #RES2 where CODE_STR in ('030203', '030204', '030205', '030206')

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 = 2
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 = 2 AND DATE < @END_DATE ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0

SET @LIMIT = ISNULL(@LIMIT,0)


--  тариф, применяемый  свыше установленного предела величины базы (%)
DECLARE 
	@PERCENT1 NUMERIC(18,2),
	@PERCENT1_IN NUMERIC(18,2)
--	@PERCENT_FSS NUMERIC(18,2)

-- Рабочие 	
SELECT @PERCENT1 = 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 = 2
WHERE 
	predel = @LIMIT
	and tarif =1
	and 
	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 = 2 AND DATE < @END_DATE ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
-- нивалиды
SELECT @PERCENT1_IN = 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 = 2
WHERE 
	predel = @LIMIT
	and tarif =3
	and 
	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 = 2 AND DATE < @END_DATE ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0

SET @PERCENT1 = ISNULL(@PERCENT1,0)
SET @PERCENT1_IN = ISNULL(@PERCENT1_IN,0)


SELECT MON = 1, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1 FROM #SPR_ESN WHERE MONTH_BASE <= 1 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 2, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 2 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 3, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 3 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 4, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 4 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 5, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 5 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 6, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 6 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 7, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 7 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 8, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 8 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 9, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 9 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 10, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 10 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 11, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 11 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 12, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE 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_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

--Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную в соответствии со ст. 8 Федерального закона от 24 
INSERT INTO #RES2 SELECT '030303', SUM(SUMMA), 0, 0 FROM #SPR_ESN2 WHERE M <= @nMONTH3
INSERT INTO #RES2 SELECT '030304', SUM(SUMMA), 0, 0 FROM #SPR_ESN2 WHERE M = @nMONTH1
INSERT INTO #RES2 SELECT '030305', SUM(SUMMA), 0, 0 FROM #SPR_ESN2 WHERE M = @nMONTH2
INSERT INTO #RES2 SELECT '030306', SUM(SUMMA), 0, 0 FROM #SPR_ESN2 WHERE M = @nMONTH3

--из них: сумма выплат и иных вознаграждений физическим лицам, являющимся инвалидами I, II, III группы
SELECT MON = 1, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1KATEG3 FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 2, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 2 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 3, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 3 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 4, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 4 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 5, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 5 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 6, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 6 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 7, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 7 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 8, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 8 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 9, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 9 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 10, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 10 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 11, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 11 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 12, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 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_ESN2KATEG3
FROM 
	#SPR_ESN1KATEG3 T INNER JOIN dbo.months_ex(@BYearDate, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1KATEG3 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1KATEG3 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


SET @TMP_VAL = ISNULL( (SELECT SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M <= @nMONTH3),0)
INSERT INTO #RES2 VALUES('030503', @TMP_VAL, 0, 0)

SET @TMP_VAL = ISNULL( (SELECT SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN  WHERE KATEG = 3 AND MONTH_BASE = @nMONTH1) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH1),0)
INSERT INTO #RES2 VALUES('030504', @TMP_VAL, 0, 0)

SET @TMP_VAL = ISNULL( (SELECT SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN  WHERE KATEG = 3 AND MONTH_BASE = @nMONTH2) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH2),0)
INSERT INTO #RES2 VALUES('030505', @TMP_VAL, 0, 0)

SET @TMP_VAL = ISNULL( (SELECT SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN  WHERE KATEG = 3 AND MONTH_BASE = @nMONTH3) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH3),0)
INSERT INTO #RES2 VALUES('030506', @TMP_VAL, 0, 0)

--select * from #RES2 where code_str in ('030503','030504', '030505','030506')
--ВЫРАВНИВАНИЕ ПОГРЕШНОСТИ ПО ОСНОВНОМУ ТАРИФУ
/*
--Способ заполнения страховых взносов
Выриант №1. Сумма всзносов по организации рассчитывается  по формулам расчёта для 4-ФСС от общих сумм дохода и необлагаемых сумм. 
Выриант №2. Сумма взносов по организации рассчитывается как сумма взносов, начисленных по физлицам. 
Выриант №3. Сумма взносов по организации рассчитывается как сумма взносов, начисленных по физлицам. 
Но при этом для того, чтобы выполнялись контрольные соотношения по форме, выполняется подгон необлагаемых сумм.
*/
DECLARE @SALARY_OPTIONS_OPT5_1 INT 
SET @SALARY_OPTIONS_OPT5_1 = dbo.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPT5_1')

--select @PERCENT1 , @PERCENT1_IN

--select * from 	#RES2
--	WHERE
--		CODE_STR IN ('030104', '030204', '030304', '030504')

IF ISNULL(@PERCENT1,0) > 0
BEGIN

	--Вычисление погрешности для накопительной части	
	SELECT 
		@C3N = CONVERT(NUMERIC(18,2), 
			(
				SUM( --Стр 4 (030403)  = 
					(CASE WHEN CODE_STR = '030103' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030203' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030303' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030503' THEN BASE_FSS  ELSE 0 END) -- за минусом базы инвалидов
				) * @PERCENT1/100
				+ SUM( --Стр 4 (030403)  = 
					(CASE WHEN CODE_STR = '030503' THEN BASE_FSS  ELSE 0 END) -- база инвалидов
				) * @PERCENT1_IN/100				
				- (SELECT SUM(BASE_FSS) FROM #RES2 WHERE CODE_STR in ('0121','0123', '0124','0125'))
			) / @PERCENT1/100
		),
		@C3NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 4 (030403)  = 
					(CASE WHEN CODE_STR = '030103' THEN BASE_FSS  ELSE 0 END) 
					-(CASE WHEN CODE_STR = '030203' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030303' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030503' THEN BASE_FSS  ELSE 0 END) -- за минусом базы инвалидов
				) * @PERCENT1/100
				+
				SUM( --Стр 4 (030403)  = 
					(CASE WHEN CODE_STR = '030503' THEN BASE_FSS  ELSE 0 END) 
				) * @PERCENT1_IN/100				
			)
		),		
		@C4N = CONVERT(NUMERIC(18,2), 
			(
				SUM( --Стр 4 (030404)  = 
					(CASE WHEN CODE_STR = '030104' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030204' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030304' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030504' THEN BASE_FSS  ELSE 0 END) -- за минусом базы инвалидов
				) * @PERCENT1/100
				+ SUM( --Стр 4 (030404)  = 
					(CASE WHEN CODE_STR = '030504' THEN BASE_FSS  ELSE 0 END) -- база инвалидов
				) * @PERCENT1_IN/100				
				- (SELECT SUM(BASE_FSS) FROM #RES2 WHERE CODE_STR = '0123')
			) / @PERCENT1/100	
		),
		@C4NS = CONVERT(NUMERIC(18,2), 
			(
				SUM( --Стр 4 (030404)  = 
					(CASE WHEN CODE_STR = '030104' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030204' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030304' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030504' THEN BASE_FSS  ELSE 0 END) -- за минусом базы инвалидов			
				) * @PERCENT1/100
				+ SUM( --Стр 4 (030403)  = 
					(CASE WHEN CODE_STR = '030504' THEN BASE_FSS  ELSE 0 END) -- база инвалидов
				) * @PERCENT1_IN/100			
			)
		),		
		@C5N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 4 (030405)  = 
					(CASE WHEN CODE_STR = '030105' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030205' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030305' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030505' THEN BASE_FSS  ELSE 0 END) -- за минусом базы инвалидов
				) * @PERCENT1/100
				+ SUM( --Стр 4 (030404)  = 
					(CASE WHEN CODE_STR = '030505' THEN BASE_FSS  ELSE 0 END) -- база инвалидов
				) * @PERCENT1_IN/100
				- (SELECT SUM(BASE_FSS) FROM #RES2 WHERE CODE_STR = '0124')
			) / @PERCENT1/100			
		),
		@C5NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 4 (030405)  = 
					(CASE WHEN CODE_STR = '030105' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030205' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030305' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030505' THEN BASE_FSS  ELSE 0 END) -- за минусом базы инвалидов			
				) * @PERCENT1/100
				+ SUM( --Стр 4 (030404)  = 
					(CASE WHEN CODE_STR = '030505' THEN BASE_FSS  ELSE 0 END) -- база инвалидов
				) * @PERCENT1_IN/100				
			)
		),		
		@C6N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 4 (030405)  = 
					(CASE WHEN CODE_STR = '030106' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030206' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030306' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030506' THEN BASE_FSS  ELSE 0 END) -- за минусом базы инвалидов
				) * @PERCENT1/100
				+ SUM( --Стр 4 (030404)  = 
					(CASE WHEN CODE_STR = '030506' THEN BASE_FSS  ELSE 0 END) -- база инвалидов
				) * @PERCENT1_IN/100				
				- (SELECT SUM(BASE_FSS) FROM #RES2 WHERE CODE_STR = '0125')
			) / @PERCENT1/100							
		),
		@C6NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 4 (030405)  = 
					(CASE WHEN CODE_STR = '030106' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030206' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030306' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030506' THEN BASE_FSS  ELSE 0 END) -- за минусом базы инвалидов			
				) * @PERCENT1/100
				+ SUM( --Стр 4 (030404)  = 
					(CASE WHEN CODE_STR = '030506' THEN BASE_FSS  ELSE 0 END) -- база инвалидов
				) * @PERCENT1_IN/100				
			)
		)		
	FROM #RES2
	WHERE
		CODE_STR IN ('030103', '030203', '030303', '030503','030104', '030204', '030304', '030504','030105', '030205', '030305', '030505','030106', '030206', '030306', '030506')

	IF @SALARY_OPTIONS_OPT5_1 = 1
	BEGIN
		--Начислено ЕСН. 1 мес
		UPDATE #RES2
		SET BASE_FSS = ISNULL(@C4NS,0)			 
		WHERE 
			CODE_STR = '0123'
		
		UPDATE #RES2
		SET BASE_FSS = ISNULL(@C5NS,0)		 
		WHERE 
			CODE_STR = '0124'
			
		UPDATE #RES2
		SET BASE_FSS = ISNULL(@C6NS,0)		 
		WHERE 
			CODE_STR = '0125'
	
	END

	IF @SALARY_OPTIONS_OPT5_1 = 3
	BEGIN
	
		UPDATE #RES2
		SET BASE_FSS = BASE_FSS + ISNULL(@C3N,0)			 
		WHERE 
			CODE_STR = '030203'
		
		UPDATE #RES2
		SET BASE_FSS = BASE_FSS + ISNULL(@C4N,0)			 
		WHERE 
			CODE_STR = '030204'
			
		UPDATE #RES2
		SET BASE_FSS = BASE_FSS + ISNULL(@C5N,0)			 
		WHERE 
			CODE_STR = '030205'
			
		UPDATE #RES2
		SET BASE_FSS = BASE_FSS + ISNULL(@C6N,0)			 
		WHERE 
			CODE_STR = '030206'
	
	END

end


-- Тоже выводим по физлицу в таблицу 3.1
CREATE TABLE #RAZD31 (LINK INT, COL5 NUMERIC(18,2), COL6 NUMERIC(18,2), COL7 NUMERIC(18,2), COL8 NUMERIC(18,2))

INSERT INTO #RAZD31 (LINK, COL5, COL6, COL7, COL8)
SELECT DISTINCT 
	P.REF_PHYS_PERS,
	S5 = ISNULL(S51.SUMMA,0) - ISNULL(S52.SUMMA,0),
	S6 = ISNULL(S61.SUMMA,0) - ISNULL(S62.SUMMA,0),
	S7 = ISNULL(S71.SUMMA,0) - ISNULL(S72.SUMMA,0),
	S8 = ISNULL(S81.SUMMA,0) - ISNULL(S82.SUMMA,0)
FROM 
	#SPR_ESN P

	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3 GROUP BY REF_PHYS_PERS) S51 ON S51.REF_PHYS_PERS = P.REF_PHYS_PERS
	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M <= @nMONTH3 GROUP BY REF_PHYS_PERS) S52 ON S52.REF_PHYS_PERS = P.REF_PHYS_PERS

	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE = @nMONTH1 GROUP BY REF_PHYS_PERS) S61 ON S61.REF_PHYS_PERS = P.REF_PHYS_PERS
	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH1 GROUP BY REF_PHYS_PERS) S62 ON S62.REF_PHYS_PERS = P.REF_PHYS_PERS

	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE = @nMONTH2 GROUP BY REF_PHYS_PERS) S71 ON S71.REF_PHYS_PERS = P.REF_PHYS_PERS
	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH2 GROUP BY REF_PHYS_PERS) S72 ON S72.REF_PHYS_PERS = P.REF_PHYS_PERS

	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE = @nMONTH3 GROUP BY REF_PHYS_PERS) S81 ON S81.REF_PHYS_PERS = P.REF_PHYS_PERS
	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH3 GROUP BY REF_PHYS_PERS) S82 ON S82.REF_PHYS_PERS = P.REF_PHYS_PERS
	
WHERE KATEG = 3

DECLARE @Table_Razd31 VARCHAR(100)
EXEC dbo.X_GET_TABLE_NAME @Table_Razd31 OUTPUT
EXEC ('select * INTO ' + @Table_Razd31 + ' from #RAZD31')
EXEC dbo.BufferPush -116, @Table_Razd31

--Используется в хранимке SA_4FSS_28022011_PREPARE_INV

--Р3.ТАБЛИЦА 9

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

--Фактическая база для договорников
SELECT GT.PERS_LINK, MONTH(G.[DATE]) AS MONTH_BASE, SUMMA_BASE = sum(CASE WHEN GT.WAY_CALC  = 5 THEN GT.SUMMA_BASE ELSE 0 END)
INTO #DGH_FAKT_BASE2
FROM 
	dbo.DOCUMENTS_DGH G 
	--INNER JOIN dbo.DOCUMENTS_DGH_T1 T1 ON T1.LINK = G.LINK
	--INNER JOIN dbo.REESTR_DGH R ON R.LINK = T1.LINK_DOG  --AND FLAG_TRAVMA = 1	
	INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK --AND T1.PERS_LINK = GT.PERS_LINK 
WHERE 
	G.LINK_DEP = @DEP_LINK
	AND FLAG_JC = 1
	--AND GT.WAY_CALC  = 5
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3 
GROUP BY   GT.PERS_LINK,  MONTH(G.[DATE]) /*, GT.WAY_CALC*/


SELECT MON, SUMMA_ALL = SUM(SUMMA_ALL), SUMMA_NO = SUM(SUMMA_NO), SUMMA_ALL_I = SUM(SUMMA_ALL_I), SUMMA_NO_I = SUM(SUMMA_NO_I)
INTO #SALARY_SUM
FROM 
(
select 
	MON = Month(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 = 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),
	SUMMA_NO_I = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) AND 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
	LEFT JOIN @StBase5 B ON B.LINK = cj.LINK_PAYS
	LEFT JOIN DBO.PERS_INVALID I ON I.PERS_LINK = E.PERS_LINK 
			AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN I.DATE_BEGIN AND ISNULL(I.DATE_END,'29990101')
			--AND COALESCE(I.DATE_BEGIN,@BYearDate) <= @EndYear AND COALESCE(I.DATE_END,@EndYear) >= @BYearDate
where 	
	Year(period_begin) = @nYEAR and Month(period_begin) <= @nMONTH3 
	and CJ.LINK_DEP = @DEP_LINK
	and P.[OBJECT] = 1
GROUP BY
	Month(CJ.PERIOD_BEGIN)
UNION ALL	
select 
	MON = Month(CJ.PERIOD_BEGIN),
	SUMMA_ALL = SUM(CJ.SUMMA),
	SUMMA_NO = SUM( CJ.SUMMA - ISNULL(B.SUMMA_BASE,0)), --на которые не начисляются страховые взносы
	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),
	SUMMA_NO_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 - ISNULL(B.SUMMA_BASE,0) ELSE 0 END)
from 
	#DGH_CJ CJ
	INNER JOIN #DGH_FAKT_BASE2 B ON B.PERS_LINK = CJ.PERS_LINK AND B.MONTH_BASE = Month(CJ.PERIOD_BEGIN)
	LEFT JOIN DBO.KU_PERS_INVALID I ON I.PERS_LINK = CJ.PERS_LINK 
		AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN I.DATE_BEGIN AND ISNULL(I.DATE_END,'29990101')
		--AND COALESCE(I.DATE_BEGIN,@BYearDate) <= @EndYear AND COALESCE(I.DATE_END,@EndYear) >= @BYearDate
where 	
	Month(period_begin) <= @nMONTH3 
GROUP BY
	Month(CJ.PERIOD_BEGIN)
) AS T
GROUP BY 
	MON
------------------------

--Льготы по травматизму
DECLARE @LINK_S_OBJ INT
SET @LINK_S_OBJ = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS WHERE CODE = 'DOCUMENTS_CLOSE_MONTH')

CREATE TABLE #TRAVM_LGOTY (I TINYINT, M TINYINT, SUMMA NUMERIC(18,2))
--скидки по травматизму
INSERT INTO #TRAVM_LGOTY (I, M, SUMMA)
SELECT I = (CASE WHEN ISNULL(I.PERS_LINK,0) = 0 THEN 0 ELSE 1 END), MONTH(D.[DATE]), SUM(SUMMA)
FROM
	dbo.SDOC D
	INNER JOIN dbo.SDOC_DOT_SKIDKI S ON S.LINK_UP = D.LINK
	LEFT JOIN dbo.pers_invalid I ON S.LINK_PERS = I.PERS_LINK 
		AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH(D.[DATE]),YEAR(D.[DATE]))) BETWEEN I.DATE_BEGIN AND COALESCE(I.DATE_END,'29990101')	
WHERE
	D.[OBJECT] = @LINK_S_OBJ AND D.FLAG_JC = 1 AND D.LINK_DEP = @DEP_LINK
	AND YEAR(D.[DATE]) = @nYEAR AND MONTH(D.[DATE]) <= @nMONTH3
GROUP BY
	ISNULL(I.PERS_LINK,0), MONTH(D.[DATE])
	
----Вычеты по травматизму	
INSERT INTO #TRAVM_LGOTY (I, M, SUMMA)
SELECT I = (CASE WHEN ISNULL(I.PERS_LINK,0) = 0 THEN 0 ELSE 1 END), MONTH(D.[DATE]), SUM(SUMMA)
FROM
	dbo.SDOC D
	INNER JOIN dbo.SDOC_DOT_VYCHET S ON S.LINK_UP = D.LINK
	LEFT JOIN dbo.pers_invalid I ON S.LINK_PERS = I.PERS_LINK 
		AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH(D.[DATE]),YEAR(D.[DATE]))) BETWEEN I.DATE_BEGIN AND COALESCE(I.DATE_END,'29990101')	
WHERE
	D.[OBJECT] = @LINK_S_OBJ AND D.FLAG_JC = 1 AND D.LINK_DEP = @DEP_LINK
	AND YEAR(D.[DATE]) = @nYEAR AND MONTH(D.[DATE]) <= @nMONTH3
GROUP BY
	ISNULL(I.PERS_LINK,0), MONTH(D.[DATE])	

--Данные для таблицы 6
CREATE TABLE #TABLE6 (MON TINYINT, SUMMA3 NUMERIC(18,2), SUMMA4 NUMERIC(18,2), SUMMA5 NUMERIC(18,2) )
INSERT INTO #TABLE6 (MON, SUMMA3, SUMMA4, SUMMA5)
SELECT 
	M.NUM, 
	SUMMA3 = /*ROUND(*/ ISNULL( (SELECT SUM(SUMMA_ALL)-SUM(SUMMA_NO) FROM #SALARY_SUM WHERE MON = M.NUM) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #TRAVM_LGOTY WHERE M = M.NUM),0) /*,0)*/,
	SUMMA4 = /*ROUND(*/ ISNULL( (SELECT SUM(SUMMA_ALL_I)-SUM(SUMMA_NO_I) FROM #SALARY_SUM WHERE MON = M.NUM) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #TRAVM_LGOTY WHERE I = 1 AND M = M.NUM),0) /*,0)*/,
	SUMMA5 = /*ROUND(*/ ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM WHERE MON = M.NUM) ,0) + ISNULL((SELECT SUM(SUMMA) FROM #TRAVM_LGOTY WHERE M = M.NUM),0) /*,0)*/
FROM
	dbo.MONTHS M
	
	
INSERT INTO #RES2 SELECT '060103', ISNULL( (SELECT SUM(SUMMA3) FROM #TABLE6) ,0) , 0, 0
INSERT INTO #RES2 SELECT '060104', ISNULL( (SELECT SUM(SUMMA4) FROM #TABLE6) ,0), 0, 0
INSERT INTO #RES2 SELECT '060105', ISNULL( (SELECT SUM(SUMMA5) FROM #TABLE6) ,0), 0, 0
---
INSERT INTO #RES2 SELECT '060303', ISNULL( (SELECT SUM(SUMMA3) FROM #TABLE6 WHERE MON = @nMONTH1) ,0) , 0, 0
INSERT INTO #RES2 SELECT '060304', ISNULL( (SELECT SUM(SUMMA4) FROM #TABLE6 WHERE MON = @nMONTH1) ,0), 0, 0
INSERT INTO #RES2 SELECT '060305', ISNULL( (SELECT SUM(SUMMA5) FROM #TABLE6 WHERE MON = @nMONTH1) ,0), 0, 0
---
INSERT INTO #RES2 SELECT '060403', ISNULL( (SELECT SUM(SUMMA3) FROM #TABLE6 WHERE MON = @nMONTH2) ,0) , 0, 0
INSERT INTO #RES2 SELECT '060404', ISNULL( (SELECT SUM(SUMMA4) FROM #TABLE6 WHERE MON = @nMONTH2) ,0), 0, 0
INSERT INTO #RES2 SELECT '060405', ISNULL( (SELECT SUM(SUMMA5) FROM #TABLE6 WHERE MON = @nMONTH2) ,0), 0, 0
---
INSERT INTO #RES2 SELECT '060503', ISNULL( (SELECT SUM(SUMMA3) FROM #TABLE6 WHERE MON = @nMONTH3) ,0) , 0, 0
INSERT INTO #RES2 SELECT '060504', ISNULL( (SELECT SUM(SUMMA4) FROM #TABLE6 WHERE MON = @nMONTH3) ,0), 0, 0
INSERT INTO #RES2 SELECT '060505', ISNULL( (SELECT SUM(SUMMA5) FROM #TABLE6 WHERE MON = @nMONTH3) ,0), 0, 0

--Р3.ТАБЛИЦА 10
select 
	MON = Month(CJ.PERIOD_BEGIN),
	SUMMA = SUM(SUMMA)
INTO 
	#SALARY_SUM1
from 
	dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
where 	
	Year(period_begin) = @nYEAR and Month(period_begin) <= @nMONTH3 
	and CJ.LINK_DEP = @DEP_LINK
	and CJ.LINK_PAYS = (select top 1 link from pays where object = 3 and way_calc = 5)
GROUP BY
	Month(CJ.PERIOD_BEGIN)

INSERT INTO #RES2 SELECT '1021', SUM(SUMMA), 0, 0 FROM #SALARY_SUM1 WHERE MON < @nMONTH1
INSERT INTO #RES2 SELECT '1023', SUM(SUMMA), 0, 0 FROM #SALARY_SUM1 WHERE MON = @nMONTH1
INSERT INTO #RES2 SELECT '1024', SUM(SUMMA), 0, 0 FROM #SALARY_SUM1 WHERE MON = @nMONTH2
INSERT INTO #RES2 SELECT '1025', SUM(SUMMA), 0, 0 FROM #SALARY_SUM1 WHERE MON = @nMONTH3

INSERT INTO #RES2
SELECT '1101', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 10),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 10),0),	
	0

INSERT INTO #RES2
SELECT '1102', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 10 AND [STATUS] = 3),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 10 AND [STATUS] = 3),0),	
	0	
	
INSERT INTO #RES2
SELECT '1104', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 11),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 11),0),	
	0

INSERT INTO #RES2
SELECT '1105', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 11 AND [STATUS] = 3),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 11 AND [STATUS] = 3),0),	
	0		

INSERT INTO #RES2
SELECT '1107', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 12),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 12),0),	
	0

DECLARE  @SPO4 INT
SELECT @SPO4 = (SELECT distinct LINK FROM dbo.SA_SZV4_SPR WHERE code = 'О4' AND spr_code = 'SPO_USL_TRUDA' )




----- Таблица результатов по спецоценке
--Р2.ТАБЛИЦА 10
select [KOL_ALL] = SUM(S.NUM_STAKE),
		[KOL_SPO_ALL] = SUM(CASE WHEN S.COD_SPO_USL_TRUD IS NOT NULL THEN S.NUM_STAKE ELSE 0 END ),
		[KOL_SPO_3] =  SUM(CASE WHEN (ISNULL(S.COD_SPO_USL_TRUD, 0) <> 0 
							AND S.COD_SPO_USL_TRUD = @SPO4 
							)  
					   THEN  S.NUM_STAKE 
					   ELSE 0 END) ,	   
		[KOL_SPO_4] = SUM(CASE WHEN (ISNULL(S.COD_SPO_USL_TRUD, 0) <> 0 
							AND S.COD_SPO_USL_TRUD <> @SPO4 
							)  
					   THEN  S.NUM_STAKE 
					   ELSE 0 END) 	  
	
INTO 
	#STAF_ALL
from 
	dbo.staff s inner join dbo.staff_head sh on s.link_up = sh.LINK
where 	
	sh.DEP_LINK = @DEP_LINK
	and @vardEnd between s.date_begin and s.date_end 




INSERT INTO #RES2 SELECT '100103', KOL_ALL, 0, 0 FROM #STAF_ALL 
INSERT INTO #RES2 SELECT '100104', KOL_SPO_ALL, 0, 0 FROM #STAF_ALL 
INSERT INTO #RES2 SELECT '100105', KOL_SPO_3, 0, 0 FROM #STAF_ALL 
INSERT INTO #RES2 SELECT '100106', KOL_SPO_4, 0, 0 FROM #STAF_ALL 


/* Завершаем - списываем значения во временную таблицу */
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.BufferPush -115, @Table_Razd1


DROP TABLE #RES2
DROP TABLE #SPR_ESN
DROP TABLE #ATR_4FSS
DROP TABLE #DGH_FAKT_BASE
DROP TABLE #SALARY_SUM2
DROP TABLE #SPR_ESN1
DROP TABLE #SPR_ESN2
DROP TABLE #SPR_ESN1KATEG3
DROP TABLE #SPR_ESN2KATEG3
DROP TABLE #RAZD31
DROP TABLE #DGH_FAKT_BASE2
DROP TABLE #SALARY_SUM
DROP TABLE #SALARY_SUM1
DROP TABLE #TRAVM_LGOTY
DROP TABLE #TABLE6




GO


GRANT EXECUTE ON dbo.[RSA_4FSS_09022012_PREPARE] TO PUBLIC

GO



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

GO
----------------------
CREATE PROCEDURE [dbo].[RA_EXPORT_FORM_FNS_730]
@iLINK_SAVED_FORM INT,                   -- Линк выгружаемой формы  
 @vcFILE_NAME     VARCHAR(100)='' OUTPUT,  -- Имя текстового файла  
 @iMODE            INT=1                   -- Формат: 2-внутренний, 1-минфиновский   
 AS
SET NOCOUNT ON  
SET DATEFORMAT dmy  

DECLARE @iLINK_FORM		 INT,
      	@iLINK_TABLE	 INT,
        @iLINK_ORG       INT, 
        @dBEGIN_DATE     DATETIME,
        @dFORM_DATE      DATETIME,
        @sYear           SMALLINT, 
        @vcOrgname       VARCHAR(1000),
        @vcKOD_ORGAN     VARCHAR(8000),
        @vcVersion       VARCHAR(8000),
        @vcProgramName   VARCHAR(100),
        @vcCRC           VARCHAR(8000),  
        @vcInn           VARCHAR(50),
        @vcKpp           VARCHAR(9),
        @vcOkpo          VARCHAR(20),
        @vcOkato         VARCHAR(11),
        @vcPPP           VARCHAR(50),
        @iUchr_Link      INT,
        @vcOrgname_Uchr  VARCHAR(1000),
        @vcInn_Uchr      VARCHAR(50),
        @vcKpp_Uchr      VARCHAR(9),
        @vcOkpo_Uchr     VARCHAR(20),
        @vcSurname       VARCHAR(60),
        @vcFirstName     VARCHAR(60),
        @vcMiddleName    VARCHAR(60),
        @vcSurname_GB    VARCHAR(60),
        @vcFirstName_GB  VARCHAR(60),
        @vcMiddleName_GB VARCHAR(60),
        @vcDateRegl      VARCHAR(10),
        @vcExec          VARCHAR(8000),  
        @bCancel         BIT,
        @iReturn         INT,
        @vcNAME          VARCHAR(8000),
        @vcFORM_CODE     VARCHAR(8000),  
        @vcFILE_NAME_XSD VARCHAR(100),    
        @vcTableName     VARCHAR(8000), 
        @CODE            VARCHAR(100),
        @v_code          VARCHAR(100),
        @C_CODE          VARCHAR(100),
        @vc_code         VARCHAR(100),
        @vcAcc           VARCHAR(5)
DECLARE @val             VARCHAR(8000), 
        @val2            VARCHAR(8000), 
        @str             VARCHAR(8000), 
        @str1            VARCHAR(8000)
          
CREATE TABLE #tabXML ([TXT]	  VARCHAR(8000),
							 [ORDERS] INT IDENTITY(1,1))

IF OBJECT_ID('tempdb..#tabExportOutput') IS NOT NULL 
BEGIN  
   SELECT @vcVersion = [VERSION]  
   FROM #tabExportOutput   
END  
  
--IF @iMODE = 2  
--BEGIN  
-- EXEC @iReturn = dbo.[RN_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,  
--                 @vcFILE_NAME OUTPUT,  
--                 @iMODE  
-- RETURN @iReturn  
--END  
  
IF @bCancel = 1  
BEGIN  
   RETURN 0  
END  
  
SET @bCancel = 0         
SET @vcNAME = 'Баланс государственного (муниципального) учреждения'  
SET @vcFORM_CODE = '0503730'  
SET @vcVersion = '5.02'
SELECT @vcProgramName = CASE WHEN CODE_TASK = 'SMETA'   THEN 'СМЕТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'KADRY'   THEN 'КАДРЫ-КС'
                             WHEN CODE_TASK = 'SALARY'  THEN 'ЗАРПЛАТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'DELO'    THEN 'ДЕЛО-КС'
                             WHEN CODE_TASK = 'ADMIN'   THEN 'АДМИНИСТРАТОР'
                             ELSE ''
                        END       
FROM [dbo].USER_INFO                                  

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_ORG  = [Link_Organization]         
FROM dbo.[report_saved_forms] A  
WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM   
  
--Таблица
SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 1

CREATE TABLE #tabAttr ([CHECKED] INT, 
                       [UPD]     INT, 
                       [DEL]     INT, 
                       [LINK_SAVED_FORM] INT, 
                       [LINK_ROW] INT, 
                       [ORDERS]   INT, 
                       [CALC_ORDERS] INT, 
                       [PRINT_NULL] INT, 
        [CODE] VARCHAR(50), COL1 VARCHAR(8000), 
                       COL2 VARCHAR(8000), COL3 VARCHAR(8000), COL4 VARCHAR(8000), 
                       COL5 VARCHAR(8000), COL6 VARCHAR(8000), COL7 VARCHAR(8000), 
                       COL8 VARCHAR(8000), COL9 VARCHAR(8000), COL10 VARCHAR(8000), 
                       COL11 VARCHAR(8000), itog VARCHAR(8000))
  SET @vcExec = 'INSERT #tabAttr
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  EXEC(@vcExec)

--Справка
SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 2

CREATE TABLE #tabAttr1 ([CHECKED] INT, 
                       [UPD]     INT, 
                       [DEL]     INT, 
                       [LINK_SAVED_FORM] INT, 
                       [LINK_ROW] INT, 
                       [ORDERS]   INT, 
                       [CALC_ORDERS] INT, 
                       [PRINT_NULL] INT, 
                       [CODE] VARCHAR(50), COL1 VARCHAR(8000), 
                       COL2 VARCHAR(8000), COL3 VARCHAR(8000), COL4 VARCHAR(8000), 
                       COL5 VARCHAR(8000), COL6 VARCHAR(8000), COL7 VARCHAR(8000), 
                       COL8 VARCHAR(8000), COL9 VARCHAR(8000), itog VARCHAR(8000))
  SET @vcExec = 'INSERT #tabAttr1
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  EXEC(@vcExec)

-- Выгрузка подписей.
 SELECT   @vcOrgname = substring(dbo.[RA_XML_MASK](d.[FULL_NAME]),1,1000),
          @vcInn     = rtrim(ltrim(d.[INN])),
          @vcKpp     = rtrim(ltrim(d.[KPP])),
          @vcOkpo    = d.[OKPO],
          @vcOkato   = d.[OKATO],
          @iUchr_Link    = d.[UCHR_LINK]
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iLINK_ORG
 SELECT   @vcInn_Uchr     = isnull(d.[INN],''),
          @vcKpp_Uchr     = isnull(d.[KPP],''),
          @vcOkpo_Uchr    = isnull(d.[OKPO],''),
          @vcOrgName_Uchr = isnull(dbo.[RA_XML_MASK](d.[FULL_NAME]),'')
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iUchr_Link
 SELECT @vcKOD_ORGAN = [SONO],
        @vcPPP       = [VED]
 FROM PrintDoc_GetDepData2(@iLINK_ORG)   
 SELECT @vcSurname=ch.[FM],
        @vcFirstName=ch.[IM],
        @vcMiddleName=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Руководитель') ch
 WHERE ch.link_dep = @iLINK_ORG
 SELECT @vcSurname_GB=ch.[FM],
        @vcFirstName_GB=ch.[IM],
        @vcMiddleName_GB=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Главный бухгалтер') ch
 WHERE ch.link_dep = @iLINK_ORG
 IF (@vcSurname='' OR @vcSurname IS NULL OR LEN(@vcSurname)=0) SELECT @vcSurname='A'
 IF (@vcFirstName='' OR @vcFirstName IS NULL OR LEN(@vcFirstName)=0) SELECT @vcFirstName='A'
 IF (@vcInn = '' or @vcInn is null) SELECT @vcInn='9999999999'
 IF (@vcKpp = '' or @vcKpp is null) SELECT @vcKpp='999999999'
 IF @vcKOD_ORGAN IS NULL SELECT @vcKOD_ORGAN=''
--Дата начала   
SELECT @dBEGIN_DATE = A.[Begin_Date],
       @sYear = CAST(YEAR(@dBEGIN_DATE) AS VARCHAR(4)),  
       @vcDateRegl = convert(varchar(12), @dBEGIN_DATE+1, 104) 
  FROM dbo.[report_saved_forms] A
  WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM
--Дата документа
 SELECT @dFORM_DATE=GETDATE()
  
SET @vcCRC = RTRIM(CONVERT(VARCHAR(100), NEWID()))  
--Имя файла
SELECT @vcExec =  'NO_BOUCHR1_' +  @vcKOD_ORGAN+ '_' +  
                  @vcKOD_ORGAN+ '_' + @vcINN + @vcKPP + '_' +  
                  CAST(YEAR(@dFORM_DATE) AS VARCHAR(4)) + 
                  RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '_' + @vcCRC,
       @vcFILE_NAME =  @vcExec + '.xml'
--Вставка XML
INSERT #tabXML([TXT]) VALUES ('<?xml  version ="1.0"  encoding ="windows-1251"?>')
INSERT #tabXML([TXT]) VALUES ('<Файл ИдФайл="'+@vcExec+'" '+'ВерсПрог="'+@vcProgramName+'" '+'ВерсФорм="'+@vcVersion+'">')
INSERT #tabXML([TXT]) VALUES ('  <Документ КНД="'+@vcFORM_CODE+'" ДатаДок="'+RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '.' +  
                               RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ '.' + CAST(YEAR(@dFORM_DATE) AS VARCHAR(4))+
                               '" Период="34" ОтчетГод="'+CAST(@sYear AS VARCHAR(4))+'" НомКорр="0" ОКЕИ="383" >')
INSERT #tabXML([TXT]) VALUES ('    <СвНП')
IF @vcOkpo<>'' AND LEN(@vcOkpo) BETWEEN 8 AND 10 
INSERT #tabXML([TXT]) VALUES (' ОКПО="'+LTRIM(RTRIM(@vcOkpo))+'"') 
IF @vcOkato<>'' AND LEN(@vcOkato)=11
INSERT #tabXML([TXT]) VALUES (' ОКАТО="'+@vcOkato+'"')
IF @vcOkpo_Uchr<>'' AND LEN(@vcOkpo_Uchr) BETWEEN 8 AND 10 
INSERT #tabXML([TXT]) VALUES (' ОКПО_Учр="'+LTRIM(RTRIM(@vcOkpo_Uchr))+'"') 
IF @vcPPP<>'' AND LEN(@vcPPP)<4
INSERT #tabXML([TXT]) VALUES (' ГлаваБК="' + @vcPPP + '"')
INSERT #tabXML([TXT]) VALUES ('>')
INSERT #tabXML([TXT]) VALUES ('      <НПЮЛ НаимОрг="'+@vcOrgname+'" ИННЮЛ="'+@vcInn+'" КПП="'+@vcKpp+'"')
IF @vcOrgName_Uchr<>'' 
INSERT #tabXML([TXT]) VALUES (' Учредит="'+@vcOrgName_Uchr+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('</СвНП>')
INSERT #tabXML([TXT]) VALUES ('<Подписант ПрПодп="1">')
INSERT #tabXML([TXT]) VALUES ('<ФИО Фамилия="'+@vcSurname+'" Имя="'+@vcFirstName+'"')
IF @vcMiddleName<>''
INSERT #tabXML([TXT]) VALUES ('Отчество="'+@vcMiddleName+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
IF @vcSurname_GB<>'' AND @vcFirstName_GB<>''
begin
INSERT #tabXML([TXT]) VALUES ('<ФИОГлБух Фамилия="'+@vcSurname_GB+'" Имя="'+@vcFirstName_GB+'"')
IF @vcMiddleName_GB<>''
INSERT #tabXML([TXT]) VALUES ('Отчество="'+@vcMiddleName_GB+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
end
INSERT #tabXML([TXT]) VALUES ('</Подписант>')
INSERT #tabXML([TXT]) VALUES ('<Баланс ДатаОтч="'+@vcDateRegl+'" >')
INSERT #tabXML([TXT]) VALUES ('<Актив>')
INSERT #tabXML([TXT]) VALUES ('<НефинАктив>')
-----------------------------------------------
DECLARE B_CURSOR CURSOR FOR      
SELECT CODE FROM #tabAttr 
  WHERE CODE LIKE '__0' AND CODE<=150 ORDER BY [CODE] ASC
OPEN B_CURSOR      
FETCH NEXT FROM B_CURSOR INTO @CODE      
WHILE @@FETCH_STATUS = 0         
BEGIN  
  SELECT @str1='',@v_code=''
  IF      @CODE='010' SELECT @str1='<БалансОС>'    ,@v_code=@CODE
  ELSE IF @CODE='020' SELECT @str1='<АмортОС>'     ,@v_code=@CODE
  ELSE IF @CODE='030' SELECT @str1='<ОстатОС>'     ,@v_code=@CODE
  ELSE IF @code='040' SELECT @str1='<НеМатАктБС>'  ,@v_code=@CODE
  ELSE IF @code='050' SELECT @str1='<АмортНмА>'    ,@v_code=@CODE
  ELSE IF @code='060' SELECT @str1='<НеМатАктОС>'  ,@v_code=@CODE
  ELSE IF @code='070' SELECT @str1='<НеПроизвАкт>' ,@v_code=@CODE
  ELSE IF @code='080' SELECT @str1='<МатЗапас>'    ,@v_code=@CODE
  ELSE IF @code='090' SELECT @str1='<ВложНеФинАкт>',@v_code=@CODE
  ELSE IF @code='100' SELECT @str1='<НеФинАктП>'   ,@v_code=@CODE
  ELSE IF @code='140' SELECT @str1='<ИзгГотовПрод>',@v_code=@CODE
  ELSE IF @code='150' SELECT @str1='<Итого>'       ,@v_code=@CODE
  ELSE                SELECT @str1=''            ,@v_code=''
  INSERT #tabXML([TXT]) SELECT @str1
 DECLARE C_CURSOR CURSOR FOR      
 SELECT [CODE] FROM #tabAttr WHERE [CODE] LIKE SUBSTRING(@v_code,1,2)+'_' ORDER BY [CODE] ASC
 OPEN C_CURSOR      
 FETCH NEXT FROM C_CURSOR INTO @C_CODE      
 WHILE @@FETCH_STATUS = 0         
 BEGIN
SELECT @str1='',@vc_code=''
IF      @c_code IN ('070','140','150')       SELECT @vc_code=@c_code      
ELSE IF @c_code in ('010','020','030','040','050','060','080','090','100')                   
                                             SELECT @str1='<Всего>', @vc_code=@c_code
ELSE IF @c_code in ('011','021','031')       SELECT @str1='<НедИмущУчр>', @vc_code=@c_code
ELSE IF @c_code in ('012','022','032','092') SELECT @str1='<ОЦДИмущУчр>', @vc_code=@c_code
ELSE IF @c_code in ('013','023','033','093') SELECT @str1='<ИнДИмущУчр>' , @vc_code=@c_code
ELSE IF @c_code in ('014','024','034','094') SELECT @str1='<ПрЛизинг>' , @vc_code=@c_code
ELSE IF @c_code in ('041','051','081')       SELECT @str1='<ОЦДИмущУчр>', @vc_code=@c_code
ELSE IF @c_code in ('042','052','062')       SELECT @str1='<ИнДИмущУчр>', @vc_code=@c_code
ELSE IF @c_code in ('043','053','063')       SELECT @str1='<ПрЛизинг>' , @vc_code=@c_code
ELSE IF @c_code='061'                        SELECT @str1='<ОЦИмущУчр>', @vc_code=@c_code
ELSE IF @c_code='091'                        SELECT @str1='<НеДИмущУчр>', @vc_code=@c_code
ELSE IF @c_code='101'                        SELECT @str1='<НеДИмущУчрП>', @vc_code=@c_code
ELSE IF @c_code='102'                        SELECT @str1='<ОЦДИмущУчрП>', @vc_code=@c_code
ELSE IF @c_code='103'                        SELECT @str1='<ИнДИмущУчрП>', @vc_code=@c_code
ELSE IF @c_code='104'                        SELECT @str1='<ПрЛизингП>', @vc_code=@c_code
ELSE SELECT @str1='', @vc_code='' 
INSERT #tabXML([TXT]) SELECT @str1
SELECT @val='', @val2='', @str=''
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val  + '"'END
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val  + '"'END
SELECT @val=[COL5] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val  + '"'END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL6]+'"/>' FROM #tabAttr WHERE [CODE]	=@vc_code
end
SELECT @val='', @val2='', @str=''
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val  + '"'END
SELECT @val=[COL8] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val  + '"'END
SELECT @val=[COL9] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val  + '"'END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL10]+'"/>' FROM #tabAttr WHERE [CODE]=@vc_code
SELECT @str1=''
IF @c_code in ('010','020','030','040','050','060','080','090','100')                   
                                             SELECT @str1='</Всего>'
ELSE IF @c_code in ('011','021','031')       SELECT @str1='</НедИмущУчр>'
ELSE IF @c_code in ('012','022','032','092') SELECT @str1='</ОЦДИмущУчр>'
ELSE IF @c_code in ('013','023','033','093') SELECT @str1='</ИнДИмущУчр>' 
ELSE IF @c_code in ('014','024','034','094') SELECT @str1='</ПрЛизинг>' 
ELSE IF @c_code in ('041','051','081')       SELECT @str1='</ОЦДИмущУчр>'
ELSE IF @c_code in ('042','052','062')       SELECT @str1='</ИнДИмущУчр>'
ELSE IF @c_code in ('043','053','063')       SELECT @str1='</ПрЛизинг>' 
ELSE IF @c_code='061'                        SELECT @str1='</ОЦИмущУчр>'
ELSE IF @c_code='091'                        SELECT @str1='</НеДИмущУчр>'
ELSE IF @c_code='101'                        SELECT @str1='</НеДИмущУчрП>'
ELSE IF @c_code='102'                        SELECT @str1='</ОЦДИмущУчрП>'
ELSE IF @c_code='103'                        SELECT @str1='</ИнДИмущУчрП>'
ELSE IF @c_code='104'                        SELECT @str1='</ПрЛизингП>'
ELSE SELECT @str1=''
INSERT #tabXML([TXT]) SELECT @str1

FETCH NEXT FROM C_CURSOR INTO @C_CODE      
END      
CLOSE C_CURSOR      
DEALLOCATE C_CURSOR   
  SELECT @str1=''
  IF      @CODE='010' SELECT @str1='</БалансОС>'    
  ELSE IF @CODE='020' SELECT @str1='</АмортОС>'     
  ELSE IF @CODE='030' SELECT @str1='</ОстатОС>'     
  ELSE IF @code='040' SELECT @str1='</НеМатАктБС>'  
  ELSE IF @code='050' SELECT @str1='</АмортНмА>'    
  ELSE IF @code='060' SELECT @str1='</НеМатАктОС>'  
  ELSE IF @code='070' SELECT @str1='</НеПроизвАкт>' 
  ELSE IF @code='080' SELECT @str1='</МатЗапас>'    
  ELSE IF @code='090' SELECT @str1='</ВложНеФинАкт>'
  ELSE IF @code='100' SELECT @str1='</НеФинАктП>'   
  ELSE IF @code='140' SELECT @str1='</ИзгГотовПрод>'
  ELSE IF @code='150' SELECT @str1='</Итого>'       
  ELSE                SELECT @str1=''
  INSERT #tabXML([TXT]) SELECT @str1

FETCH NEXT FROM B_CURSOR INTO @CODE      
END      
CLOSE B_CURSOR      
DEALLOCATE B_CURSOR
------------------------------------------------
INSERT #tabXML([TXT]) VALUES('</НефинАктив>')
INSERT #tabXML([TXT]) VALUES('<ФинАктив>')
------------------------------------------------
DECLARE B_CURSOR CURSOR FOR      
SELECT CODE FROM #tabAttr WHERE CODE LIKE '__0' AND CODE BETWEEN 170 AND 400  ORDER BY [CODE] ASC
OPEN B_CURSOR      
FETCH NEXT FROM B_CURSOR INTO @CODE      
WHILE @@FETCH_STATUS = 0         
BEGIN  
  SELECT @str1='',@v_code=''
  IF @code='170' SELECT @str1='<ДенСрУчр>'          ,@v_code=@CODE
  ELSE IF @CODE='210' SELECT @str1='<ФинВлож>'      ,@v_code=@CODE
  ELSE IF @CODE='230' SELECT @str1='<РасчДоход>'    ,@v_code=@CODE
  ELSE IF @code='260' SELECT @str1='<РасчВыдАванс>' ,@v_code=@CODE
  ELSE IF @code='290' SELECT @str1='<РасчКредит>'   ,@v_code=@CODE
  ELSE IF @code='310' SELECT @str1='<РасчПОтчЛиц>'  ,@v_code=@CODE
  ELSE IF @code='320' SELECT @str1='<РасчУщербИмущ>',@v_code=@CODE
  ELSE IF @code='330' SELECT @str1='<ПрочРасчДеб>'  ,@v_code=@CODE
  ELSE IF @code='370' SELECT @str1='<ВложФинАкт>'   ,@v_code=@CODE
  ELSE IF @code='400' SELECT @str1='<Итого>'        ,@v_code=@CODE
  ELSE SELECT @str1='',@v_code=''
  INSERT #tabXML([TXT]) SELECT @str1

DECLARE C_CURSOR CURSOR FOR      
SELECT [CODE] FROM #tabAttr WHERE [CODE] LIKE SUBSTRING(@v_code,1,2)+'_'  ORDER BY [CODE] ASC
OPEN C_CURSOR      
FETCH NEXT FROM C_CURSOR INTO @C_CODE      
WHILE @@FETCH_STATUS = 0         
BEGIN  
  SELECT @str1='',@vc_code=''
  IF @c_code IN ('230','260','310','320','400') 
                             SELECT @vc_code=@c_code
  ELSE IF @c_code in ('170','210','290','330','370')  
                             SELECT @str1='<Всего>', @vc_code=@c_code
  ELSE IF @c_code='171'      SELECT @str1='<ЛицСчОргКазн>', @vc_code=@c_code
  ELSE IF @c_code='172'      SELECT @str1='<ОргКазнПут>', @vc_code=@c_code
  ELSE IF @c_code='173'      SELECT @str1='<СчетКО>', @vc_code=@c_code
  ELSE IF @c_code='174'      SELECT @str1='<КОПут>', @vc_code=@c_code
  ELSE IF @c_code='175'      SELECT @str1='<АккрСчетКО>', @vc_code=@c_code
  ELSE IF @c_code='176'      SELECT @str1='<ИнВалСчКО>' , @vc_code=@c_code
  ELSE IF @c_code='177'      SELECT @str1='<Касса>', @vc_code=@c_code
  ELSE IF @c_code='178'      SELECT @str1='<ДенДокум>', @vc_code=@c_code
  ELSE IF @c_code='179'      SELECT @str1='<РазмДепКО>', @vc_code=@c_code
  ELSE IF @c_code IN ('211','371') SELECT @str1='<ЦенБумКрАкц>', @vc_code=@c_code
  ELSE IF @c_code IN ('212','372') SELECT @str1='<АкцИнКапит>', @vc_code=@c_code
  ELSE IF @c_code IN ('213','373') SELECT @str1='<ИнФинАктив>', @vc_code=@c_code
  ELSE IF @c_code='291'      SELECT @str1='<ПредстКредит>', @vc_code=@c_code
  ELSE IF @c_code='292'      SELECT @str1='<ЦелИнКредит>', @vc_code=@c_code
  ELSE IF @c_code='331'      SELECT @str1='<РасчНДС>', @vc_code=@c_code
  ELSE IF @c_code='333'      SELECT @str1='<РасчФОДен>', @vc_code=@c_code
  ELSE IF @c_code='335'      SELECT @str1='<РасчПрДеб>', @vc_code=@c_code
  ELSE IF @c_code='336'      SELECT @str1='<РасчУчред>', @vc_code=@c_code
  ELSE IF @c_code='337'      SELECT @str1='<УмБалСтОЦИ>', @vc_code=@c_code
  ELSE IF @c_code='338'      SELECT @str1='<ЧистСтОЦИ>', @vc_code=@c_code
  ELSE SELECT @str1='', @vc_code='' 
  INSERT #tabXML([TXT]) SELECT @str1
SELECT @val='', @val2='', @str=''
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' AND @vc_code NOT IN ('336','337','338') begin set @str = @str + ' ДеятЦелСр = "' + @val  + '"'END
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val  + '"'END
SELECT @val=[COL5] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' AND @vc_code NOT IN ('336','337','338') begin set @str = @str + ' СрВремРасп = "' + @val  + '"'END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL6]+'"/>' FROM #tabAttr WHERE [CODE]	=@vc_code
end
SELECT @val='', @val2='', @str=''
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' AND @vc_code NOT IN ('336','337','338') begin set @str = @str + ' ДеятЦелСр = "' + @val  + '"'END
SELECT @val=[COL8] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val  + '"'END
SELECT @val=[COL9] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' AND @vc_code NOT IN ('336','337','338') begin set @str = @str + ' СрВремРасп = "' + @val  + '"'END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL10]+'"/>' FROM #tabAttr WHERE [CODE]=@vc_code

  SELECT @str1=''
  IF @c_code in ('170','210','290','330','370') 
                        SELECT @str1='</Всего>'
  ELSE IF @c_code='171'      SELECT @str1='</ЛицСчОргКазн>'
  ELSE IF @c_code='172'      SELECT @str1='</ОргКазнПут>'
  ELSE IF @c_code='173'      SELECT @str1='</СчетКО>'
  ELSE IF @c_code='174'      SELECT @str1='</КОПут>'
  ELSE IF @c_code='175'      SELECT @str1='</АккрСчетКО>'
  ELSE IF @c_code='176'      SELECT @str1='</ИнВалСчКО>' 
  ELSE IF @c_code='177'      SELECT @str1='</Касса>'
  ELSE IF @c_code='178'      SELECT @str1='</ДенДокум>'
  ELSE IF @c_code='179'      SELECT @str1='</РазмДепКО>'
  ELSE IF @c_code IN ('211','371') SELECT @str1='</ЦенБумКрАкц>'
  ELSE IF @c_code IN ('212','372') SELECT @str1='</АкцИнКапит>'
  ELSE IF @c_code IN ('213','373') SELECT @str1='</ИнФинАктив>'
  ELSE IF @c_code='291'      SELECT @str1='</ПредстКредит>'
  ELSE IF @c_code='292'      SELECT @str1='</ЦелИнКредит>'
  ELSE IF @c_code='331'      SELECT @str1='</РасчНДС>'
  ELSE IF @c_code='333'      SELECT @str1='</РасчФОДен>'
  ELSE IF @c_code='335'      SELECT @str1='</РасчПрДеб>'
  ELSE IF @c_code='336'      SELECT @str1='</РасчУчред>'
  ELSE IF @c_code='337'      SELECT @str1='</УмБалСтОЦИ>'
  ELSE IF @c_code='338'      SELECT @str1='</ЧистСтОЦИ>'
  ELSE SELECT @str1='' 
  INSERT #tabXML([TXT]) SELECT @str1

FETCH NEXT FROM C_CURSOR INTO @C_CODE      
END      
CLOSE C_CURSOR      
DEALLOCATE C_CURSOR   
SELECT @str1=''
IF @code='170' SELECT @str1='</ДенСрУчр>'
ELSE IF @CODE='210' SELECT @str1='</ФинВлож>'
ELSE IF @CODE='230' SELECT @str1='</РасчДоход>'
ELSE IF @code='260' SELECT @str1='</РасчВыдАванс>'
ELSE IF @code='290' SELECT @str1='</РасчКредит>'
ELSE IF @code='310' SELECT @str1='</РасчПОтчЛиц>'
ELSE IF @code='320' SELECT @str1='</РасчУщербИмущ>'
ELSE IF @code='330' SELECT @str1='</ПрочРасчДеб>'
ELSE IF @code='370' SELECT @str1='</ВложФинАкт>'
ELSE IF @code='400' SELECT @str1='</Итого>'
ELSE SELECT @str1=''
INSERT #tabXML([TXT]) SELECT @str1

FETCH NEXT FROM B_CURSOR INTO @CODE      
END      
CLOSE B_CURSOR      
DEALLOCATE B_CURSOR
---------------------------------------------
INSERT #tabXML([TXT]) VALUES('</ФинАктив>')
INSERT INTO #tabXML([TXT]) VALUES('<Баланс>')
SELECT @val='', @val2='', @str='',@str1=''
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=410
if @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val + '"' END
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=410
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val + '"' END
SELECT @val=[COL5] FROM #tabAttr WHERE  [CODE]=410
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val + '"' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL6]+'"/>' FROM #tabAttr WHERE [CODE]	=410
end
SELECT @val='', @val2='', @str=''
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=410
if @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val + '"' END
SELECT @val=[COL8] FROM #tabAttr WHERE  [CODE]=410
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val + '"' END
SELECT @val=[COL9] FROM #tabAttr WHERE  [CODE]=410
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val + '"' END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL10]+'"/>' FROM #tabAttr WHERE [CODE]	=410
INSERT INTO #tabXML([TXT]) VALUES('</Баланс>')
----------------------------------------------
INSERT #tabXML([TXT]) VALUES ('</Актив>')
INSERT #tabXML([TXT]) VALUES ('<Пассив>')
INSERT #tabXML([TXT]) VALUES ('<Обязат>')
----------------------------------------------
DECLARE B_CURSOR CURSOR FOR      
SELECT CODE FROM #tabAttr WHERE CODE LIKE '__0' AND CODE BETWEEN 470 AND 600  ORDER BY [CODE] ASC
OPEN B_CURSOR      
FETCH NEXT FROM B_CURSOR INTO @CODE      
WHILE @@FETCH_STATUS = 0         
BEGIN  
  SELECT @str1='',@v_code=''
  IF @code='470' SELECT @str1='<РасчКДолгОбяз>'    ,@v_code=@code
  ELSE IF @CODE='490' SELECT @str1='<РасчПрОбяз>'  ,@v_code=@code
  ELSE IF @CODE='510' SELECT @str1='<РасчПлатБюдж>',@v_code=@code
  ELSE IF @code='530' SELECT @str1='<ПрРасчКредит>',@v_code=@code
  ELSE IF @code='600' SELECT @str1='<Итого>'       ,@v_code=@code
  ELSE SELECT @str1='',@v_code='' 
  INSERT #tabXML([TXT]) SELECT @str1

DECLARE C_CURSOR CURSOR FOR      
SELECT [CODE] FROM #tabAttr WHERE [CODE] LIKE SUBSTRING(@v_code,1,2)+'_'  ORDER BY [CODE] ASC
OPEN C_CURSOR      
FETCH NEXT FROM C_CURSOR INTO @C_CODE      
WHILE @@FETCH_STATUS = 0         
BEGIN
  SELECT @str1='',@vc_code=''
  IF @c_code IN ('490','600') SELECT @vc_code=@c_code
  ELSE IF @c_code in ('470','510','530') SELECT @str1='<Всего>', @vc_code=@c_code
  ELSE IF @c_code='471' SELECT @str1='<ДолгОбязРуб>', @vc_code=@c_code
  ELSE IF @c_code='472' SELECT @str1='<ДолгОбязИнКр>', @vc_code=@c_code
  ELSE IF @c_code='474' SELECT @str1='<ДолгОбязВал>', @vc_code=@c_code
  ELSE IF @c_code='511' SELECT @str1='<РасчНДФЛ>', @vc_code=@c_code
  ELSE IF @c_code='512' SELECT @str1='<РасчВзнОСС>', @vc_code=@c_code
  ELSE IF @c_code='513' SELECT @str1='<РасчПриб>', @vc_code=@c_code
  ELSE IF @c_code='514' SELECT @str1='<РасчНДС>', @vc_code=@c_code
  ELSE IF @c_code='515' SELECT @str1='<РасчИнПлат>', @vc_code=@c_code
  ELSE IF @c_code='516' SELECT @str1='<РасчВзнМПС>', @vc_code=@c_code
  ELSE IF @c_code='531' SELECT @str1='<РасчВремСр>', @vc_code=@c_code
  ELSE IF @c_code='532' SELECT @str1='<РасчДепонент>', @vc_code=@c_code
  ELSE IF @c_code='533' SELECT @str1='<РасчУдержОТ>', @vc_code=@c_code
  ELSE IF @c_code='534' SELECT @str1='<РасчВнВедоств>', @vc_code=@c_code
  ELSE IF @c_code='536' SELECT @str1='<РасчПрочКред>', @vc_code=@c_code
  ELSE SELECT @str1='', @vc_code='' 
  INSERT #tabXML([TXT]) SELECT @str1
SELECT @val='', @val2='', @str=''
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val  + '"'END
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val  + '"'END
SELECT @val=[COL5] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val  + '"'END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL6]+'"/>' FROM #tabAttr WHERE [CODE]	= @vc_code
end
SELECT @val='', @val2='', @str=''
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val  + '"'END
SELECT @val=[COL8] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val  + '"'END
SELECT @val=[COL9] FROM #tabAttr WHERE  [CODE]=@vc_code
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val  + '"'END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL10]+'"/>' FROM #tabAttr WHERE [CODE] = @vc_code

  SELECT @str1=''
  IF @c_code in ('470','510','530') SELECT @str1='</Всего>'
  ELSE IF @c_code='471' SELECT @str1='</ДолгОбязРуб>'
  ELSE IF @c_code='472' SELECT @str1='</ДолгОбязИнКр>'
  ELSE IF @c_code='474' SELECT @str1='</ДолгОбязВал>'
  ELSE IF @c_code='511' SELECT @str1='</РасчНДФЛ>'
  ELSE IF @c_code='512' SELECT @str1='</РасчВзнОСС>'
  ELSE IF @c_code='513' SELECT @str1='</РасчПриб>'
  ELSE IF @c_code='514' SELECT @str1='</РасчНДС>'
  ELSE IF @c_code='515' SELECT @str1='</РасчИнПлат>'
  ELSE IF @c_code='516' SELECT @str1='</РасчВзнМПС>'
  ELSE IF @c_code='531' SELECT @str1='</РасчВремСр>'
  ELSE IF @c_code='532' SELECT @str1='</РасчДепонент>'
  ELSE IF @c_code='533' SELECT @str1='</РасчУдержОТ>'
  ELSE IF @c_code='534' SELECT @str1='</РасчВнВедоств>'
  ELSE IF @c_code='536' SELECT @str1='</РасчПрочКред>'
  ELSE SELECT @str1='' 
  INSERT #tabXML([TXT]) SELECT @str1
  
FETCH NEXT FROM C_CURSOR INTO @C_CODE      
END      
CLOSE C_CURSOR      
DEALLOCATE C_CURSOR   
  SELECT @str1=''
  IF @code='470' SELECT @str1='</РасчКДолгОбяз>'
  else IF @CODE='490' SELECT @str1='</РасчПрОбяз>'
  else IF @CODE='510' SELECT @str1='</РасчПлатБюдж>'
  else IF @code='530' SELECT @str1='</ПрРасчКредит>'
  else IF @code='600' SELECT @str1='</Итого>'
  ELSE SELECT @str1='' 
  INSERT #tabXML([TXT]) SELECT @str1

FETCH NEXT FROM B_CURSOR INTO @CODE      
END      
CLOSE B_CURSOR      
DEALLOCATE B_CURSOR
---------------------------------------------  
INSERT #tabXML([TXT]) VALUES ('</Обязат>')
INSERT #tabXML([TXT]) VALUES ('<ФинРезул>')
-----------------------------------------
INSERT INTO #tabXML([TXT]) VALUES('<ФинРезХозСуб>')
DECLARE FA_CURSOR CURSOR FOR      
 SELECT CODE      
 FROM #tabAttr      WHERE [CODE] LIKE '62%'  ORDER BY [CODE] ASC
 OPEN FA_CURSOR      
 FETCH NEXT FROM FA_CURSOR INTO @CODE      
 WHILE @@FETCH_STATUS = 0         
 BEGIN  
SELECT @val=[COL10] FROM #tabAttr WHERE  [CODE]=@CODE
 
begin 
SELECT @str1='',@v_code=''
IF      @code='620'  SELECT @str1='<Всего>',@v_code=@code
else IF @code='623'  SELECT @str1='<ФинРезПрОПер>',@v_code=@code
else IF @code='6231' SELECT @str1='<ФинРезНАмОЦИ>',@v_code=@code
else IF @code='624'  SELECT @str1='<ДохБудПер>',@v_code=@code
else IF @code='625'  SELECT @str1='<РасхБудПер>',@v_code=@code
ELSE SELECT @str1='',@v_code=''  
INSERT INTO #tabXML([TXT]) SELECT @str1
end
SELECT @val='', @val2='', @str=''
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=@v_CODE
if @val<>'0.00'  AND @v_code NOT IN ('6231') begin set @str = @str + ' ДеятЦелСр = "' + @val + '"' END
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=@v_CODE
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val + '"' END
SELECT @val=[COL5] FROM #tabAttr WHERE  [CODE]=@v_CODE
if @val<>'0.00'  AND @v_code NOT IN ('6231') begin set @str = @str + ' СрВремРасп = "' + @val + '"' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL6]+'"/>' FROM #tabAttr WHERE [CODE]	=@v_CODE
end
SELECT @val='', @val2='', @str=''
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=@v_CODE
if @val<>'0.00'  AND @v_code NOT IN ('6231') begin set @str = @str + ' ДеятЦелСр = "' + @val + '"' END
SELECT @val=[COL8] FROM #tabAttr WHERE  [CODE]=@v_CODE
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val + '"' END
SELECT @val=[COL9] FROM #tabAttr WHERE  [CODE]=@v_CODE
if @val<>'0.00' AND @v_code NOT IN ('6231') begin set @str = @str + ' СрВремРасп = "' + @val + '"' END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL10]+'"/>' FROM #tabAttr WHERE [CODE]	=@v_CODE

SELECT @val='', @val2='', @str=''
SELECT @val=[COL10] FROM #tabAttr WHERE  [CODE]=@v_CODE
 
begin 
SELECT @str1=''   
IF      @code='620'  SELECT @str1='</Всего>'
ELSE IF @code='623'  SELECT @str1='</ФинРезПрОПер>'
ELSE IF @code='6231' SELECT @str1='</ФинРезНАмОЦИ>'
ELSE IF @code='624'  SELECT @str1='</ДохБудПер>'
ELSE IF @code='625'  SELECT @str1='</РасхБудПер>'
ELSE SELECT @str1='' 
INSERT INTO #tabXML([TXT]) SELECT @str1
end

FETCH NEXT FROM FA_CURSOR INTO @CODE      
END      
CLOSE FA_CURSOR      
DEALLOCATE FA_CURSOR   

INSERT INTO #tabXML([TXT]) VALUES('</ФинРезХозСуб>')
-------------------------------------------------
INSERT #tabXML([TXT]) VALUES ('</ФинРезул>')
INSERT INTO #tabXML([TXT]) VALUES('<Баланс>')
SELECT @val='', @val2='', @str='',@str1=''
SELECT @val=[COL3] FROM #tabAttr WHERE  [CODE]=900
if @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val + '"' END
SELECT @val=[COL4] FROM #tabAttr WHERE  [CODE]=900
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val + '"' END
SELECT @val=[COL5] FROM #tabAttr WHERE  [CODE]=900
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val + '"' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL6]+'"/>' FROM #tabAttr WHERE [CODE]	=900
end
SELECT @val='', @val2='', @str=''
SELECT @val=[COL7] FROM #tabAttr WHERE  [CODE]=900
if @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val + '"' END
SELECT @val=[COL8] FROM #tabAttr WHERE  [CODE]=900
if @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val + '"' END
SELECT @val=[COL9] FROM #tabAttr WHERE  [CODE]=900
if @val<>'0.00' begin set @str = @str + ' СрВремРасп = "' + @val + '"' END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL10]+'"/>' FROM #tabAttr WHERE [CODE]	=900
INSERT INTO #tabXML([TXT]) VALUES('</Баланс>')
---------------------------------------------------
INSERT #tabXML([TXT]) VALUES ('</Пассив>')
INSERT #tabXML([TXT]) VALUES ('<СпрИмущОбЗС>')
----------------------------------------------------
DECLARE B_CURSOR CURSOR FOR      
 SELECT CODE      
 FROM #tabAttr1 WHERE [CODE] LIKE '__0'  ORDER BY [CODE] ASC
 OPEN B_CURSOR      
 FETCH NEXT FROM B_CURSOR INTO @CODE      
 WHILE @@FETCH_STATUS = 0         
 BEGIN
SELECT @vcAcc = COL1 FROM #tabAttr1 WHERE [CODE]=@CODE
SELECT @str1='',@v_code=''
IF      @code='010' SELECT @str1='<ИмущПолПольз НомСчетЗаб = "'      + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='020' SELECT @str1= '<МатЦенХран НомСчетЗаб = "'       + @vcAcc + '">', @v_code=@CODE
ELSE IF @code='030' SELECT @str1='<БланкСтрОтч НомСчетЗаб = "'       + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='040' SELECT @str1='<ДолгНД НомСчетЗаб = "'            + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='050' SELECT @str1='<МатЦенОплЦС НомСчетЗаб = "'       + @vcAcc + '">',  @v_code=@CODE                 
ELSE IF @code='060' SELECT @str1='<ДолгНеМатЦен НомСчетЗаб = "'      + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='070' SELECT @str1='<НагрПриз НомСчетЗаб = "'          + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='080' SELECT @str1='<ПутевНеОпл НомСчетЗаб = "'        + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='090' SELECT @str1='<ЗапЧастТС НомСчетЗаб = "'         + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='100' SELECT @str1='<ИспОбяз НомСчетЗаб = "'           + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='120' SELECT @str1='<СпецНИРДог НомСчетЗаб = "'        + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='130' SELECT @str1='<ЭксперУстр НомСчетЗаб = "'        + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='150' SELECT @str1='<РасчДокНеОпл НомСчетЗаб = "'      + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='160' SELECT @str1='<ПерепПенсНеЗак НомСчетЗаб = "'    + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='170' SELECT @str1='<ПостДССчетУчр НомСчетЗаб = "'     + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='180' SELECT @str1='<ВыбДССчетУчр НомСчетЗаб = "'      + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='200' SELECT @str1='<ДолгНеКред НомСчетЗаб = "'        + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='210' SELECT @str1='<ОснСр3000Экспл НомСчетЗаб = "'    + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='220' SELECT @str1='<МатЦенЦСнаб НомСчетЗаб = "'       + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='230' SELECT @str1='<ПериодИзд НомСчетЗаб = "'         + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='240' SELECT @str1='<ИмущДовУпр НомСчетЗаб = "'        + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='250' SELECT @str1='<ИмущВозмПольз НомСчетЗаб = "'     + @vcAcc + '">',  @v_code=@CODE
ELSE IF @code='260' SELECT @str1='<ИмущБВозмПольз НомСчетЗаб = "'    + @vcAcc + '">',  @v_code=@CODE
ELSE                SELECT @str1='', @v_code=''
                
INSERT INTO #tabXML([TXT]) VALUES(@str1)

 DECLARE C_CURSOR CURSOR FOR      
 SELECT [CODE] FROM #tabAttr1 WHERE [CODE] LIKE SUBSTRING(@v_code,1,2)+'_'  ORDER BY [CODE] ASC
 OPEN C_CURSOR      
 FETCH NEXT FROM C_CURSOR INTO @C_CODE      
 WHILE @@FETCH_STATUS = 0         
 BEGIN  
 SELECT @str1=''
IF      @c_code IN ('060','080','090','130','150','160') 
                           SELECT @vc_code=@c_code      
ELSE IF @c_code in ('010','020','030','040','050','070','100','120','170','180','200','210','220','230','240','250','260') 
                           SELECT @str1='<Всего>', @vc_code=@c_code
ELSE IF @c_code='011'      SELECT @str1='<Недвиж>', @vc_code=@c_code
ELSE IF @c_code='012'      SELECT @str1='<НедвижНепр>', @vc_code=@c_code
ELSE IF @c_code='015'      SELECT @str1='<Движ>', @vc_code=@c_code
ELSE IF @c_code='052'      SELECT @str1='<ЦенДвИмущОС>', @vc_code=@c_code
ELSE IF @c_code='054'      SELECT @str1='<МатЗапас>', @vc_code=@c_code
ELSE IF @c_code='055'      SELECT @str1='<ЦенДвИмущМЗ>', @vc_code=@c_code
ELSE IF @c_code='071'      SELECT @str1='<УсловОцен>', @vc_code=@c_code
ELSE IF @c_code='072'      SELECT @str1='<СтоимПриобр>', @vc_code=@c_code
ELSE IF @c_code='101'      SELECT @str1='<Задаток>', @vc_code=@c_code
ELSE IF @c_code='102'      SELECT @str1='<Залог>', @vc_code=@c_code
ELSE IF @c_code='103'      SELECT @str1='<БанкГарант>', @vc_code=@c_code
ELSE IF @c_code='104'      SELECT @str1='<Поручит>', @vc_code=@c_code
ELSE IF @c_code='105'      SELECT @str1='<ИнОбеспеч>', @vc_code=@c_code
ELSE IF @c_code='171'      SELECT @str1='<Доходы>', @vc_code=@c_code
ELSE IF @c_code IN ('172','181')      SELECT @str1='<Расходы>', @vc_code=@c_code
ELSE IF @c_code IN ('173','182')      SELECT @str1='<ИстФинДефСр>', @vc_code=@c_code
ELSE IF @c_code='211'      SELECT @str1='<ОсЦенДИмущ>', @vc_code=@c_code
ELSE IF @c_code='212'      SELECT @str1='<ИнДИмущ>', @vc_code=@c_code
ELSE IF @c_code IN ('051','221','241','251','261') SELECT @str1='<ОснСредств>', @vc_code=@c_code
ELSE IF @c_code IN (            '242','252','262') SELECT @str1='<НедвижИмущОС>', @vc_code=@c_code
ELSE IF @c_code IN (      '222','243','253','263') SELECT @str1='<ОсЦенДИмущОС>', @vc_code=@c_code
ELSE IF @c_code IN (            '244','254','264') SELECT @str1='<НематАктив>', @vc_code=@c_code
ELSE IF @c_code IN (            '245','255','265') SELECT @str1='<ОсЦенДИмущНА>', @vc_code=@c_code
ELSE IF @c_code IN (      '224','246','256','266') SELECT @str1='<МатЗапас>', @vc_code=@c_code
ELSE IF @c_code IN (      '225','247','257','267') SELECT @str1='<ОсЦенДИмущМЗ>', @vc_code=@c_code
ELSE SELECT @str1='', @vc_code='' 
INSERT INTO #tabXML([TXT]) SELECT @str1
SELECT @val='', @val2='', @str=''
SELECT @val=[COL4] FROM #tabAttr1 WHERE  [CODE] = @vc_code
IF @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val + '"' END
SELECT @val=[COL5] FROM #tabAttr1 WHERE  [CODE] = @vc_code
IF @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val + '"' END
IF @str<>'' 
begin
INSERT #tabXML([TXT]) SELECT '<НачГод '+@str+' Итого="'+[COL6]+'"/>' FROM #tabAttr1 WHERE [CODE] = @vc_code
end
SELECT @val='', @val2='', @str=''
SELECT @val=[COL7] FROM #tabAttr1 WHERE  [CODE] = @vc_code
IF @val<>'0.00' begin set @str = @str + ' ДеятЦелСр = "' + @val + '"' END
SELECT @val=[COL8] FROM #tabAttr1 WHERE  [CODE] = @vc_code
IF @val<>'0.00' begin set @str = @str + ' ДеятОказУсл = "' + @val + '"' END
INSERT #tabXML([TXT]) SELECT '<КонПер '+@str+' Итого="'+[COL9]+'"/>' FROM #tabAttr1 WHERE [CODE] = @vc_code
SELECT @str1=''
IF @c_code in ('010','020','030','040','050','070','100','120','170','180','200','210','220','230','240','250','260') 
                           SELECT @str1='</Всего>'
ELSE IF @c_code='011'      SELECT @str1='</Недвиж>'
ELSE IF @c_code='012'      SELECT @str1='</НедвижНепр>'
ELSE IF @c_code='015'      SELECT @str1='</Движ>'
ELSE IF @c_code='052'      SELECT @str1='</ЦенДвИмущОС>'
ELSE IF @c_code='054'      SELECT @str1='</МатЗапас>'
ELSE IF @c_code='055'      SELECT @str1='</ЦенДвИмущМЗ>'
ELSE IF @c_code='071'      SELECT @str1='</УсловОцен>'
ELSE IF @c_code='072'      SELECT @str1='</СтоимПриобр>'
ELSE IF @c_code='101'      SELECT @str1='</Задаток>'
ELSE IF @c_code='102'      SELECT @str1='</Залог>'
ELSE IF @c_code='103'      SELECT @str1='</БанкГарант>'
ELSE IF @c_code='104'      SELECT @str1='</Поручит>'
ELSE IF @c_code='105'      SELECT @str1='</ИнОбеспеч>'
ELSE IF @c_code='171'      SELECT @str1='</Доходы>'
ELSE IF @c_code IN ('172','181')      SELECT @str1='</Расходы>'
ELSE IF @c_code IN ('173','182')      SELECT @str1='</ИстФинДефСр>'
ELSE IF @c_code='211'      SELECT @str1='</ОсЦенДИмущ>'
ELSE IF @c_code='212'      SELECT @str1='</ИнДИмущ>'
ELSE IF @c_code IN ('051','221','241','251','261') SELECT @str1='</ОснСредств>'
ELSE IF @c_code IN (            '242','252','262') SELECT @str1='</НедвижИмущОС>'
ELSE IF @c_code IN (      '222','243','253','263') SELECT @str1='</ОсЦенДИмущОС>'
ELSE IF @c_code IN (            '244','254','264') SELECT @str1='</НематАктив>'
ELSE IF @c_code IN (            '245','255','265') SELECT @str1='</ОсЦенДИмущНА>'
ELSE IF @c_code IN (      '224','246','256','266') SELECT @str1='</МатЗапас>'
ELSE IF @c_code IN (      '225','247','257','267') SELECT @str1='</ОсЦенДИмущМЗ>'
ELSE SELECT @str1='' 
INSERT INTO #tabXML([TXT]) SELECT @str1

FETCH NEXT FROM C_CURSOR INTO @C_CODE      
END      
CLOSE C_CURSOR      
DEALLOCATE C_CURSOR   
SELECT @str1='',@v_code=''
IF      @code='010' SELECT @str1='</ИмущПолПольз>'
ELSE IF @code='020' SELECT @str1='</МатЦенХран>'
ELSE IF @code='030' SELECT @str1='</БланкСтрОтч>'
ELSE IF @code='040' SELECT @str1='</ДолгНД>'
ELSE IF @code='050' SELECT @str1='</МатЦенОплЦС>'                 
ELSE IF @code='060' SELECT @str1='</ДолгНеМатЦен>'
ELSE IF @code='070' SELECT @str1='</НагрПриз>'
ELSE IF @code='080' SELECT @str1='</ПутевНеОпл>'
ELSE IF @code='090' SELECT @str1='</ЗапЧастТС>'
ELSE IF @code='100' SELECT @str1='</ИспОбяз>'
ELSE IF @code='120' SELECT @str1='</СпецНИРДог>'
ELSE IF @code='130' SELECT @str1='</ЭксперУстр>'
ELSE IF @code='150' SELECT @str1='</РасчДокНеОпл>'
ELSE IF @code='160' SELECT @str1='</ПерепПенсНеЗак>'
ELSE IF @code='170' SELECT @str1='</ПостДССчетУчр>'
ELSE IF @code='180' SELECT @str1='</ВыбДССчетУчр>'
ELSE IF @code='200' SELECT @str1='</ДолгНеКред>'
ELSE IF @code='210' SELECT @str1='</ОснСр3000Экспл>'
ELSE IF @code='220' SELECT @str1='</МатЦенЦСнаб>'
ELSE IF @code='230' SELECT @str1='</ПериодИзд>'
ELSE IF @code='240' SELECT @str1='</ИмущДовУпр>'
ELSE IF @code='250' SELECT @str1='</ИмущВозмПольз>'
ELSE IF @code='260' SELECT @str1='</ИмущБВозмПольз>'
ELSE                SELECT @str1=''
                
INSERT INTO #tabXML([TXT]) VALUES(@str1)

FETCH NEXT FROM B_CURSOR INTO @CODE      
END      
CLOSE B_CURSOR      
DEALLOCATE B_CURSOR
-----------------------------------------------------
INSERT #tabXML([TXT]) VALUES ('</СпрИмущОбЗС>')
INSERT #tabXML([TXT]) VALUES ('</Баланс>')
INSERT #tabXML([TXT]) VALUES ('</Документ>')
INSERT #tabXML([TXT]) VALUES ('</Файл>')
-----------------------------------------------------
INSERT #Files ([TXT], [NAMEFILE],  [NAMEFILE_ARH],  [OrderFile],[LINK_SAVED_FORM])
SELECT         [TXT], @vcFILE_NAME,@vcFILE_NAME_XSD,[ORDERS],   @iLINK_SAVED_FORM
FROM #tabXML
DROP TABLE #tabXML  



GO


GRANT EXECUTE ON dbo.[RA_EXPORT_FORM_FNS_730] 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, '', '20130101', '20130331', 1, 0, 41964
 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)
INSERT INTO #CALCULATE_JURNAL (LINK_PAYS, PERIOD_BEGIN, LINK_DOC, PERS_LINK, LINK_VKR, LINK_EKR, LINK_EMPL, SUMMA,way_calc )
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 
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


------	у кого была инвалидность в заданном периоде
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 CJ.LINK_EMPL = ED.link and DOP =1 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 CJ.LINK_EMPL = ED.link and DOP =2  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 (@BYearDate, @LINK_ACC, DEFAULT)
		GROUP BY KAU

	END

	FETCH NEXT FROM @Cur1 INTO @LINK_ACC
END

CLOSE @Cur1
DEALLOCATE @Cur1

--ОСТАТОК НА НАЧАЛО ГОДА ПО КАУ ДЛЯ ВЗНОСОВ ПО ДОПТАРИФУ №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', 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),
	0

--Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соот-ветствии со ст. 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))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END))
 			 
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))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END))
 			 
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))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END))
 			 
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))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END))
 			 
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))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END))
 			 
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))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END))
 			 
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))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END))
 			 
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_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.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))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END))
 			 
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))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END))
 			 
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))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END))
 			 
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))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END))
 			 
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))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END))
 			 
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_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.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)


---------------
/********СРЕДНЕСПИСОЧНАЯ ЧИСЛЕННОСТЬ**********/

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


/* Среднесписочная численность всего */
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.[RA_EXPORT_FORM_FNS_769]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RA_EXPORT_FORM_FNS_769]

GO
----------------------
CREATE PROCEDURE [dbo].[RA_EXPORT_FORM_FNS_769]
 @iLINK_SAVED_FORM INT,                    -- Линк выгружаемой формы  
 @vcFILE_NAME      VARCHAR(100)='' OUTPUT,  -- Имя текстового файла  
 @iMODE            INT=1                   -- Формат: 2-внутренний, 1-минфиновский    
 AS
SET NOCOUNT ON  
SET DATEFORMAT dmy  

DECLARE @iLINK_FORM		 INT,
      	@iLINK_TABLE	 INT,
        @iLINK_ORG       INT, 
        @vcCODE          VARCHAR(50),
        @vcDebt          VARCHAR(1),
        @vcFO            VARCHAR(1),
        @dBEGIN_DATE     DATETIME,
        @dFORM_DATE      DATETIME,  
        @sYear           SMALLINT, 
        @vcOrgname       VARCHAR(1000),
        @vcKOD_ORGAN     VARCHAR(8000),
        @vcVersion       VARCHAR(8000),
        @vcProgramName   VARCHAR(100),
        @vcCRC           VARCHAR(8000),  
        @vcInn           VARCHAR(50),
        @vcKpp           VARCHAR(9),
        @vcOkpo          VARCHAR(20),
        @vcOkato         VARCHAR(11),
        @vcPPP           VARCHAR(50),
        @iUchr_Link      INT,
        @vcOrgname_Uchr  VARCHAR(1000),
        @vcInn_Uchr      VARCHAR(50),
        @vcKpp_Uchr      VARCHAR(9),
        @vcOkpo_Uchr     VARCHAR(20),
        @vcSurname       VARCHAR(60),
        @vcFirstName     VARCHAR(60),
        @vcMiddleName    VARCHAR(60),
        @vcSurname_GB    VARCHAR(60),
        @vcFirstName_GB  VARCHAR(60),
        @vcMiddleName_GB VARCHAR(60),
        @vcDateRegl      VARCHAR(10),
        @vcExec          VARCHAR(8000),  
        @bCancel         BIT,
        @iReturn         INT,
        @vcNAME          VARCHAR(8000),
        @vcFORM_CODE     VARCHAR(8000),  
        @vcFILE_NAME_XSD VARCHAR(100),    
        @vcTableName     VARCHAR(8000), 
        @ORDER           VARCHAR(100),
        @CODE            VARCHAR(100),
        @CODE_ACC        VARCHAR(100),--Код счета
        @COL1            VARCHAR(100) --Номер счета
DECLARE @val             VARCHAR(8000), 
        @val2            VARCHAR(8000), 
        @str             VARCHAR(8000),
        @strbin          VARbinary(max)
          
CREATE TABLE #tabXML ([TXT]	  VARCHAR(8000),
							 [ORDERS] INT IDENTITY(1,1))

IF OBJECT_ID('tempdb..#tabExportOutput') IS NOT NULL  
BEGIN  
   SELECT @vcVersion = [VERSION]  
   FROM #tabExportOutput   
END  
  
IF @bCancel = 1  
BEGIN  
   RETURN 0  
END  
  
SET @bCancel = 0         
SET @vcNAME = 'Сведения по дебиторской/кредиторской задолженности учреждения'  
SET @vcFORM_CODE = '0503769'  
SET @vcVersion='5.01' 
SELECT @vcProgramName = CASE WHEN CODE_TASK = 'SMETA'   THEN 'СМЕТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'KADRY'   THEN 'КАДРЫ-КС'
                             WHEN CODE_TASK = 'SALARY'  THEN 'ЗАРПЛАТА-КС'
                             WHEN CODE_TASK = 'OUTPUTS' THEN 'СВОД-КС'
                             WHEN CODE_TASK = 'DELO'    THEN 'ДЕЛО-КС'
                             WHEN CODE_TASK = 'ADMIN'   THEN 'АДМИНИСТРАТОР'
                             ELSE ''
                        END       
FROM [dbo].USER_INFO                                  

SELECT @iLINK_FORM = b.[LINK_FORM],
       @iLINK_ORG  = [Link_Organization],
       @vcCODE     = b.[Code]         
FROM dbo.[report_saved_forms] A  
INNER JOIN dbo.[REPORT_FORMS] B ON B.[Link_Form] = A.[Link_Form]
WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM   

SELECT @vcDebt = CASE WHEN @vcCODE LIKE '%D' THEN '1'
                      WHEN @vcCODE LIKE '%K' THEN '2'
                      ELSE ''
                END  
SELECT @vcFO = dbo.[RN_GET_ATR_VALUE](@iLINK_SAVED_FORM,'REPORTS_ATR_VID')
--Таблица 1
SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 1

CREATE TABLE #tabAttr1 ([CHECKED] INT, 
                        [UPD]     INT, 
    [DEL]     INT, 
                        [LINK_SAVED_FORM] INT, 
                        [LINK_ROW] INT, 
                        [CALC_ORDERS] INT, 
                        [PRINT_NULL] INT, 
                        [ORDER] VARCHAR(10),
                        [CODE] VARCHAR(50),  
                        COL1 VARCHAR(8000), 
                        COL2 VARCHAR(100), COL3 VARCHAR(100), 
                        COL4 VARCHAR(100), COL5 VARCHAR(100))
  SET @vcExec = 'INSERT #tabAttr1
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  EXEC(@vcExec)
--Таблица 2
SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 2

CREATE TABLE #tabAttr2 ([CHECKED] INT, 
                        [UPD]     INT, 
                        [DEL]     INT, 
                        [LINK_SAVED_FORM] INT, 
                        [LINK_ROW] INT, 
                        [CALC_ORDERS] INT, 
                        [PRINT_NULL] INT, 
                        [ORDER] VARCHAR(10),
                        [CODE] VARCHAR(50),  
                        COL1 VARCHAR(8000), 
                        COL2 VARCHAR(100), COL3 VARCHAR(100), 
                        COL4 VARCHAR(100), COL5 VARCHAR(100))
  SET @vcExec = 'INSERT #tabAttr2
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  EXEC(@vcExec)
--Таблица 3
SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 3

CREATE TABLE #tabAttr3 ([CHECKED] INT, 
                        [UPD]     INT, 
                        [DEL]     INT, 
                        [LINK_SAVED_FORM] INT, 
                        [LINK_ROW] INT, 
                        [CALC_ORDERS] INT, 
                        [PRINT_NULL] INT, 
                        [ORDER] VARCHAR(10),
                        [CODE] VARCHAR(50),  
                        COL1 VARCHAR(8000), 
                        COL2 VARCHAR(100), COL3 VARCHAR(100), 
                        COL4 VARCHAR(100), COL5 VARCHAR(100))
  SET @vcExec = 'INSERT #tabAttr3
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  EXEC(@vcExec)
--Таблица 4
SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
	  [ORDERS] = 4

CREATE TABLE #tabAttr4 ([CHECKED] INT, 
                        [UPD]     INT, 
                        [DEL]     INT, 
                        [LINK_SAVED_FORM] INT, 
                        [LINK_ROW] INT, 
                        [CALC_ORDERS] INT, 
                        [PRINT_NULL] INT, 
                        [ORDER] VARCHAR(10),
                        [CODE] VARCHAR(50),  
                        COL1 VARCHAR(8000), 
                        COL2 VARCHAR(100), COL3 VARCHAR(100), 
                        COL4 VARCHAR(100), COL5 VARCHAR(100),
                        COL6 VARCHAR(100), COL7 VARCHAR(100))
  SET @vcExec = 'INSERT #tabAttr4
                 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 
  EXEC(@vcExec)

-- Выгрузка подписей.
 SELECT   @vcOrgname = substring(dbo.[RA_XML_MASK](d.[FULL_NAME]),1,1000),
          @vcInn     = rtrim(ltrim(d.[INN])),
          @vcKpp     = rtrim(ltrim(d.[KPP])),
          @vcOkpo    = d.[OKPO],
          @vcOkato   = d.[OKATO],
          @iUchr_Link    = d.[UCHR_LINK]
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iLINK_ORG
 SELECT   @vcInn_Uchr     = isnull(d.[INN],''),
          @vcKpp_Uchr     = isnull(d.[KPP],''),
          @vcOkpo_Uchr    = isnull(d.[OKPO],''),
          @vcOrgName_Uchr = isnull(dbo.[RA_XML_MASK](d.[FULL_NAME]),'')
    FROM dbo.[DEPARTMENTS] d 
    WHERE d.[link] = @iUchr_Link
 SELECT @vcKOD_ORGAN = [SONO],
        @vcPPP       = [VED]
 FROM PrintDoc_GetDepData2(@iLINK_ORG)   
 SELECT @vcSurname=ch.[FM],
        @vcFirstName=ch.[IM],
        @vcMiddleName=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Руководитель') ch
 WHERE ch.link_dep = @iLINK_ORG
 SELECT @vcSurname_GB=ch.[FM],
        @vcFirstName_GB=ch.[IM],
        @vcMiddleName_GB=ch.[OT]
 FROM dbo.GetOtvFaceData(@iLINK_ORG, 'Главный бухгалтер') ch
 WHERE ch.link_dep = @iLINK_ORG
 IF (@vcSurname='' OR @vcSurname IS NULL OR LEN(@vcSurname)=0) SELECT @vcSurname='A'
 IF (@vcFirstName='' OR @vcFirstName IS NULL OR LEN(@vcFirstName)=0) SELECT @vcFirstName='A'
 IF (@vcInn IS NULL or @vcInn = '') SELECT @vcInn='9999999999'
 IF (@vcKpp IS NULL or @vcKpp = '') SELECT @vcKpp='999999999'
 IF @vcKOD_ORGAN IS NULL SELECT @vcKOD_ORGAN=''
--Дата начала   
SELECT @dBEGIN_DATE = A.[Begin_Date],
       @sYear = CAST(YEAR(@dBEGIN_DATE) AS VARCHAR(4)),  
       @vcDateRegl = convert(varchar(12), @dBEGIN_DATE+1, 104) 
  FROM dbo.[report_saved_forms] A
  WHERE A.[LINK_SAVED_FORM] = @iLINK_SAVED_FORM
--Дата документа
 SELECT @dFORM_DATE=GETDATE()
  
SET @vcCRC = RTRIM(CONVERT(VARCHAR(100), NEWID()))  
--Имя файла
SELECT @vcExec =  'NO_BOUCHR9.'+@vcFO+'.'+@vcDebt+'_' +  @vcKOD_ORGAN+ '_' +  
                  @vcKOD_ORGAN+ '_' + @vcINN + @vcKPP + '_' +  
                  CAST(YEAR(@dFORM_DATE) AS VARCHAR(4)) + 
                  RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '_' + @vcCRC,
       @vcFILE_NAME =  @vcExec + '.xml',
       @vcFILE_NAME_XSD =  @vcExec + '.xsd'
--Вставка XML
INSERT #tabXML([TXT]) VALUES ('<?xml  version ="1.0"  encoding ="windows-1251"?>')
INSERT #tabXML([TXT]) VALUES ('<Файл ИдФайл="'+@vcExec+'" '+'ВерсПрог="'+@vcProgramName+'" '+'ВерсФорм="'+@vcVersion+'">')
INSERT #tabXML([TXT]) VALUES ('  <Документ КНД="' + @vcFORM_CODE + '" ДатаДок="'+RIGHT('0'+CAST(DAY(@dFORM_DATE) AS VARCHAR(2)),2) + '.' +  
                               RIGHT('0'+CAST(MONTH(@dFORM_DATE) AS VARCHAR(2)),2)+ '.' + CAST(YEAR(@dFORM_DATE) AS VARCHAR(4))+
                               '" Период="34" ОтчетГод="'+CAST(@sYear AS VARCHAR(4))+'" НомКорр="0">')
INSERT #tabXML([TXT]) VALUES ('    <СвНП')
IF @vcOkpo<>'' AND LEN(@vcOkpo) BETWEEN 8 AND 10 
begin INSERT #tabXML([TXT]) VALUES (' ОКПО="'+LTRIM(RTRIM(@vcOkpo))+'"') end
IF @vcOkato<>'' AND LEN(@vcOkato)=11
begin INSERT #tabXML([TXT]) VALUES (' ОКАТО="'+@vcOkato+'"') END
IF @vcOkpo_Uchr<>'' AND LEN(@vcOkpo_Uchr) BETWEEN 8 AND 10 
INSERT #tabXML([TXT]) VALUES (' ОКПО_Учр="'+LTRIM(RTRIM(@vcOkpo_Uchr))+'"') 
IF @vcPPP<>'' AND LEN(@vcPPP)<4
INSERT #tabXML([TXT]) VALUES (' ГлаваБК="' + @vcPPP + '"')
INSERT #tabXML([TXT]) VALUES ('>')
INSERT #tabXML([TXT]) VALUES ('      <НПЮЛ НаимОрг="'+@vcOrgname+'" ИННЮЛ="'+@vcInn+'" КПП="'+@vcKpp+'"')
IF @vcOrgName_Uchr<>'' 
begin INSERT #tabXML([TXT]) VALUES (' Учредит="'+@vcOrgName_Uchr+'"') end
INSERT #tabXML([TXT]) VALUES ('/>')
INSERT #tabXML([TXT]) VALUES ('</СвНП>')
INSERT #tabXML([TXT]) VALUES ('<Подписант ПрПодп="1">')
INSERT #tabXML([TXT]) VALUES ('<ФИО Фамилия="'+@vcSurname+'" Имя="'+@vcFirstName+'"')
IF @vcMiddleName<>''
INSERT #tabXML([TXT]) VALUES ('Отчество="'+@vcMiddleName+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
IF @vcSurname_GB<>'' AND @vcFirstName_GB<>''
begin
INSERT #tabXML([TXT]) VALUES ('<ФИОГлБух Фамилия="'+@vcSurname_GB+'" Имя="'+@vcFirstName_GB+'"')
IF @vcMiddleName_GB<>''
INSERT #tabXML([TXT]) VALUES ('Отчество="'+@vcMiddleName_GB+'"')
INSERT #tabXML([TXT]) VALUES ('/>')
end
INSERT #tabXML([TXT]) VALUES ('</Подписант>')
INSERT #tabXML([TXT]) VALUES ('<СвЗадолжУчр ВидДеят="'+@vcFO+'"'+' ВидЗдлж="'+@vcDebt+'"'+' ДатаОтч="'+@vcDateRegl+'" ОКЕИ="383">')
----------------------------------------
IF EXISTS (SELECT * FROM #tabAttr1)
begin
INSERT #tabXML([TXT]) VALUES ('<СвЗадолж>')
 DECLARE F_CURSOR CURSOR FOR      
 SELECT distinct COL1 FROM #tabAttr1 
 WHERE COL1 IN ('30200000','30300000','30402000','30403000','30404000','20500000','20600000','20800000','20900000','21001000')
 OPEN F_CURSOR      
 FETCH NEXT FROM F_CURSOR INTO @CODE_ACC
 WHILE @@FETCH_STATUS = 0         
 BEGIN
   INSERT #tabXML([TXT]) SELECT '<ЗдлжКодСчет КодСчет="'+ @vcFO+@CODE_ACC+'">'
 --Сумма задолженности по номеру счета бухгалтерского учета
   DECLARE T_CURSOR CURSOR FOR    
   SELECT COL1 FROM #tabAttr1 
   WHERE ((LEFT(COL1,3)=LEFT(@CODE_ACC,3) AND @CODE_ACC IN ('30200000','30300000','20500000','20600000','20800000','20900000') AND COL1 NOT LIKE '%00000') 
       OR (LEFT(COL1,5)=LEFT(@CODE_ACC,5) AND @CODE_ACC IN ('30402000','30403000','30404000','21001000')))
   OPEN T_CURSOR
   FETCH NEXT FROM T_CURSOR INTO @COL1
   WHILE @@FETCH_STATUS = 0         
   BEGIN
     SELECT @val='', @val2='', @str=''
     SELECT @str='<НомСчетБУ НомСчетБУч="'+@vcFO+COL1+'">' FROM #tabAttr1 WHERE COL1=@COL1
     SELECT @str=@str+'<СумЗдлж'
     SELECT @val=COL2 FROM #tabAttr1 WHERE COL1=@COL1
     if @val<>'' begin set @str = @str + ' СумВсегоН="' + @val  + '"'END
     SELECT @val=COL3 FROM #tabAttr1 WHERE COL1=@COL1
     if @val<>'' begin set @str = @str + ' НеВзыскН="' + @val  + '"'END
     SELECT @val=COL4 FROM #tabAttr1 WHERE COL1=@COL1
     if @val<>'' begin set @str = @str + ' СумВсегоК="' + @val  + '"'END
     SELECT @val=COL5 FROM #tabAttr1 WHERE COL1=@COL1
     if @val<>'' begin set @str = @str + ' НеВзыскК="' + @val  + '"'END
     INSERT #tabXML([TXT]) SELECT @str+'/></НомСчетБУ>'
   FETCH NEXT FROM T_CURSOR INTO @COL1
   END      
   CLOSE T_CURSOR
   DEALLOCATE T_CURSOR
 --Итого
   INSERT #tabXML([TXT]) SELECT '<Итого СумВсегоН="'+COL2+'" НеВзыскН="'+COL3+'" СумВсегоК="'+COL4+'" НеВзыскК="'+COL5+'"/>' 
                         FROM #tabAttr1 WHERE COL1=@CODE_ACC
 --Итого крупные сделки
   IF EXISTS (SELECT * FROM #tabAttr2 WHERE COL1=@CODE_ACC)
   begin
   SELECT @val='', @val2='', @str=''
   SET @str='<КрупСделИт'
   SELECT @val=COL2 FROM #tabAttr2 WHERE COL1=@CODE_ACC
   IF @val<>'' begin set @str = @str + ' СумВсегоН="' + @val  + '"' end
   SELECT @val=COL3 FROM #tabAttr2 WHERE COL1=@CODE_ACC
   if @val<>'' begin set @str = @str + ' НеВзыскН="' + @val  + '"' end
   SELECT @val=COL4 FROM #tabAttr2 WHERE COL1=@CODE_ACC
   if @val<>'' begin set @str = @str + ' СумВсегоК="' + @val  + '"' end
   SELECT @val=COL5 FROM #tabAttr2 WHERE COL1=@CODE_ACC
   if @val<>'' begin set @str = @str + ' НеВзыскК="' + @val  + '"' end
   if @str<>'<КрупСделИт' INSERT #tabXML([TXT]) SELECT @str+'/>'
   end
 --Итого сделки с заинтересованностью
   IF EXISTS (SELECT * FROM #tabAttr3 WHERE COL1=@CODE_ACC)
   begin
   SELECT @val='', @val2='', @str=''
   SET @str='<СделИнтересИт'
   SELECT @val=COL2 FROM #tabAttr3 WHERE COL1=@CODE_ACC
   if @val<>'' begin set @str = @str + ' СумВсегоН="' + @val  + '"' end
   SELECT @val=COL3 FROM #tabAttr3 WHERE COL1=@CODE_ACC
   if @val<>'' begin set @str = @str + ' НеВзыскН="' + @val  + '"' end
   SELECT @val=COL4 FROM #tabAttr3 WHERE COL1=@CODE_ACC
   if @val<>'' begin set @str = @str + ' СумВсегоК="' + @val  + '"' end
   SELECT @val=COL5 FROM #tabAttr3 WHERE COL1=@CODE_ACC
   if @val<>'' begin set @str = @str + ' НеВзыскК="' + @val  + '"' end
   if @str<>'<СделИнтересИт' INSERT #tabXML([TXT]) SELECT @str+'/>'
   end
   INSERT #tabXML([TXT]) VALUES ('</ЗдлжКодСчет>')                      
 FETCH NEXT FROM F_CURSOR INTO @CODE_ACC
 END      
 CLOSE F_CURSOR      
 DEALLOCATE F_CURSOR   
------------------------------------------
INSERT #tabXML([TXT]) VALUES ('<Всего>')
 --Всего
   INSERT #tabXML([TXT]) SELECT '<Всего СумВсегоН="'+COL2+'" НеВзыскН="'+COL3+'" СумВсегоК="'+COL4+'" НеВзыскК="'+COL5+'"/>' 
                         FROM #tabAttr1 WHERE COL1 LIKE '%88888'
 --Всего крупные сделки
   IF EXISTS (SELECT * FROM #tabAttr2 WHERE COL1 LIKE '%88888')
   begin
   SELECT @val='', @val2='', @str=''
   SET @str='<КрупСделВс'
   SELECT @val=COL2 FROM #tabAttr2 WHERE COL1 LIKE '%88888'
   if @val<>'' set @str = @str + ' СумВсегоН="' + @val  + '"'
   SELECT @val=COL3 FROM #tabAttr2 WHERE COL1 LIKE '%88888'
   if @val<>'' set @str = @str + ' НеВзыскН="' + @val  + '"'
   SELECT @val=COL4 FROM #tabAttr2 WHERE COL1 LIKE '%88888'
   if @val<>'' set @str = @str + ' СумВсегоК="' + @val  + '"'
   SELECT @val=COL5 FROM #tabAttr2 WHERE COL1 LIKE '%88888'
   if @val<>'' set @str = @str + ' НеВзыскК="' + @val  + '"'
   INSERT #tabXML([TXT]) SELECT @str+'/>'
   end
 --Всего сделки с заинтересованностью
   IF EXISTS (SELECT * FROM #tabAttr3 WHERE COL1 LIKE '%88888')
   begin
   SELECT @val='', @val2='', @str=''
   SET @str='<СделИнтересВс'
   SELECT @val=COL2 FROM #tabAttr3 WHERE COL1 LIKE '%88888'
   if @val<>'' set @str = @str + ' СумВсегоН="' + @val  + '"'
   SELECT @val=COL3 FROM #tabAttr3 WHERE COL1 LIKE '%88888'
   if @val<>'' set @str = @str + ' НеВзыскН="' + @val  + '"'
   SELECT @val=COL4 FROM #tabAttr3 WHERE COL1 LIKE '%88888'
   if @val<>'' set @str = @str + ' СумВсегоК="' + @val  + '"'
   SELECT @val=COL5 FROM #tabAttr3 WHERE COL1 LIKE '%88888'
   if @val<>'' set @str = @str + ' НеВзыскК="' + @val  + '"'
   INSERT #tabXML([TXT]) SELECT @str+'/>'
   end
 INSERT #tabXML([TXT]) VALUES ('</Всего>')
------------------------------------------
INSERT #tabXML([TXT]) VALUES ('</СвЗадолж>')
end
----------------------------------------
--Талица 4
IF EXISTS (SELECT * FROM #tabAttr4)
begin
INSERT #tabXML([TXT]) VALUES ('<ИнфНеВз>')
 DECLARE B_CURSOR CURSOR FOR      
 SELECT CODE FROM #tabAttr4
 OPEN B_CURSOR      
 FETCH NEXT FROM B_CURSOR INTO @CODE
 WHILE @@FETCH_STATUS = 0         
 BEGIN
 INSERT #tabXML([TXT]) SELECT '<ИнфНеВзСч НомСчетБУч="'+@vcFO+COL1+'" Сумма="'+COL2+'"' FROM #tabAttr4 WHERE CODE=@CODE
 SELECT @str=COL3 FROM #tabAttr4 WHERE CODE=@CODE
 IF @str<>''
 INSERT #tabXML([TXT]) VALUES (' ГодВозник="'+@str+'"')
 INSERT #tabXML([TXT]) VALUES ('>')
 INSERT #tabXML([TXT]) SELECT '<СвКредЮЛ ИННЮЛ="'+COL4+'" НаимОрг="'+COL5+'"' FROM #tabAttr4 WHERE CODE=@CODE
 INSERT #tabXML([TXT]) VALUES ('/>')
 SELECT @str=''
 SELECT @str=COL6 FROM #tabAttr4 WHERE CODE=@CODE
 IF @str<>''
 begin
 SELECT @strbin = CAST(COL6 as VARBINARY(MAX)) FROM #tabAttr4 WHERE CODE=@CODE
 SELECT @val    = CAST(N'' as xml).value('xs:base64Binary(sql:variable("@strbin"))', 'varchar(max)')
 INSERT #tabXML([TXT]) VALUES ('<ПричОбразов><![CDATA['+@val+']]></ПричОбразов>')
 end
 INSERT #tabXML([TXT]) VALUES ('</ИнфНеВзСч>')
 FETCH NEXT FROM B_CURSOR INTO @CODE
 END      
 CLOSE B_CURSOR      
 DEALLOCATE B_CURSOR   
INSERT #tabXML([TXT]) VALUES ('</ИнфНеВз>')
end
----------------------------------------
INSERT #tabXML([TXT]) VALUES ('</СвЗадолжУчр>')
INSERT #tabXML([TXT]) VALUES ('</Документ>')
INSERT #tabXML([TXT]) VALUES ('</Файл>')
----------------------------------------
INSERT #Files ([TXT], [NAMEFILE],  [NAMEFILE_ARH], [OrderFile],[LINK_SAVED_FORM])
SELECT [TXT],@vcFILE_NAME,@vcFILE_NAME_XSD,[ORDERS],@iLINK_SAVED_FORM
FROM #tabXML
DROP TABLE #tabXML  


GO


GRANT EXECUTE ON dbo.[RA_EXPORT_FORM_FNS_769] 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


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.5"?>'
  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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 11, 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, 12, 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, 12, 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, 12, 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, 12, 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, 12, 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, 12, 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, 12, 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, 12, 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, 12, 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, 12, 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, 12, 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, 12, 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, 12, 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, 12, 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, 12, 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, 12, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 13, 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, 14, 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, 14, 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, 14, 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, 14, 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, 14, 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, 14, 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, 14, 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, 14, 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, 14, 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, 14, 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, 14, 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, 14, 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, 14, 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, 14, 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, 14, 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, 14, 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, 14, 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, 15, 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, 16, 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, 16, 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, 16, 1, 5) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' ATT_CL4="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 16, 1, 6) 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, 16, 2, 7) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' MED_C2="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 16, 2, 8) WHERE SUMMA <> 0
		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(0) + ' >'

		/*Раздел I Платежное поручение*/
		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 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, 13, 25, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 25, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 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, 13, 26, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 26, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 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, 13, 27, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 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.[KU_VACATION_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KU_VACATION_SAVE]

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

CREATE PROCEDURE [dbo].KU_VACATION_SAVE
	@varKSparLINK	int	OUTPUT,
	@varKSparNumber  varchar(30),
	@varKSparDate   datetime,
	@varKSparTYPE_LINK	INT,
	@varKSparPERIOD_BEGIN     DATETIME = null,
	@varKSparPERIOD_END       DATETIME = null,
	@varKSparDATE_BEGIN     DATETIME = null,
	@varKSparDATE_END       DATETIME = null,
	@varKSparREASON_link	INT = NULL,	
	@varKSparREASON            VARCHAR(254) = null,
	@varKSparREASON_DOP        VARCHAR(500) = null,
	@varKSparEMPL_LINK      INT = null,
	@varKSparORDER_LINK INT = null,
	@varKSparVAC_GRAPH_LINK int = 0,
	@varKSparDEP_LINK int = null,
	@varKSparVAC_LINK int = null,
	@varKSparORDER_STATUS int = 0

AS
DECLARE @varKSERROR tinyint, @varKStrancount int, @varKSSQLError int, @varKSRowCount int, @varKScomment varchar(254), @varKSparMOVED int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	
	IF @varKSparDATE_BEGIN IS NULL OR @varKSparDATE_END is null or @varKSparTYPE_LINK is null
	BEGIN
		ROLLBACK
		RETURN 5
	END

	IF @varKSparVAC_LINK is not null SET @varKSparMOVED = 1 ELSE SET @varKSparMOVED = 0

	IF @varKSparDATE_BEGIN > @varKSparDATE_END
		BEGIN
			ROLLBACK
			RETURN 107
		END

	IF @varKSparPERIOD_BEGIN > @varKSparPERIOD_END
		BEGIN
			ROLLBACK
			RETURN 110
		END

	IF (@varKSparPERIOD_BEGIN is null and @varKSparPERIOD_END is not null) or (@varKSparPERIOD_BEGIN is not null and @varKSparPERIOD_END is null)
		BEGIN
			ROLLBACK
			RETURN 111
		END

	
	SELECT @varKSparORDER_LINK = link FROM ORDERS WITH (UPDLOCK) WHERE LINK = @varKSparORDER_LINK
	SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
	IF @varKSSQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END


	IF @varKSRowCount = 0
	BEGIN
		SET @varKScomment='О предоставлении отпуска '+dbo.ku_GetEmplFIO(@varKSparEMPL_LINK)
		EXECUTE @varKSERROR = KU_ORDER_SAVE @varKSparORDER_LINK OUTPUT, 4, @varKSparNumber, @varKSparDate, @varKScomment, 0, @varKSparDEP_LINK

		IF @varKSERROR <> 0
			RETURN @varKSERROR
	END

	
	IF @varKSparLINK is null OR @varKSparLINK = 0
	BEGIN
		INSERT INTO item_vacation WITH (ROWLOCK) (type_link, period_begin, period_end, date_begin, date_end,reason_link, reason, reason_dop, empl_link, order_link, moved, vac_link)
			VALUES (@varKSparTYPE_LINK, @varKSparPERIOD_BEGIN, @varKSparPERIOD_END, @varKSparDATE_BEGIN, 
				@varKSparDATE_END,@varKSparREASON_link, @varKSparREASON,@varKSparREASON_dop, @varKSparEMPL_LINK, @varKSparORDER_LINK, @varKSparMOVED, @varKSparVAC_LINK)
		SELECT @varKSSQLError = @@ERROR, @varKSparLINK = @@IDENTITY
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	
	ELSE
	BEGIN
		UPDATE item_vacation SET type_link=@varKSparTYPE_LINK, period_begin=@varKSparPERIOD_BEGIN,
				period_end=@varKSparPERIOD_END, date_begin=@varKSparDATE_BEGIN, date_end=@varKSparDATE_END, reason_link=@varKSparREASON_link, reason=@varKSparREASON, reason_dop=@varKSparREASON_dop, empl_link=@varKSparEMPL_LINK, 
				order_link=@varKSparORDER_LINK, moved=@varKSparMOVED, vac_link=@varKSparVAC_LINK
		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

	UPDATE	dbo.VACATION_GRAPHICS_TABLE
	SET	SFORMIROVAN = @varKSparLINK
	WHERE	LINK = @varKSparVAC_GRAPH_LINK
	SELECT @varKSSQLError = @@ERROR
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	IF @varKSparORDER_STATUS=1
		UPDATE orders SET status = 1 WHERE link=@varKSparORDER_LINK

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0



GO


GRANT EXECUTE ON dbo.[KU_VACATION_SAVE] TO PUBLIC

GO




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

GO

CREATE PROCEDURE [dbo].KJ_FORM_T6
	@ORDER_LINK	int
AS
	-- ТИП ПРИКАЗА (ОДИНОЧНЫЙ/ГРУППОВОЙ)
	DECLARE	@nCHECK	int
	SET	@nCHECK = CASE
			    WHEN(SELECT COUNT(*) FROM (SELECT DISTINCT EMPL_LINK FROM ITEM_VACATION WHERE ORDER_LINK = @ORDER_LINK) T) > 1 THEN 1
			    ELSE 0
			  END
	
	SELECT	T.*
	INTO	#VACATION_TEMP
	FROM	(
		SELECT
			[LINK]		= V.LINK,			-- ССЫЛКА НА ПУНКТ ПРИКАЗА
			[VAC_OSN]	= CASE				-- ОСНОВНОЙ ОТПУК ИЛИ НЕТ (1-ОСНОВНОЙ, 0-ДОПОЛНИТЕЛЬНЫЙ)
							WHEN (SELECT CODE FROM VACATION_VID WHERE LINK = V.TYPE_LINK) = '01' THEN 1
							ELSE 0
						END,
			[DATE_BEGIN]	= V.DATE_BEGIN,			-- ДАТА НАЧАЛА
			[DATE_END]	= V.DATE_END,			-- ДАТА ОКОНЧАНИЯ
			[DURATION]	= CASE				-- ПРОДОЛЖИТЕЛЬНОСТЬ
						WHEN V.HOLIDAY = 1 THEN DATEDIFF(DAY,V.DATE_BEGIN,V.DATE_END) - DBO.SA_HOLIDAY_COUNT_FN(V.DATE_BEGIN,V.DATE_END) + 1
						ELSE DATEDIFF(DAY,V.DATE_BEGIN,V.DATE_END) + 1
					  END,
			[PERIOD_BEGIN]	= V.PERIOD_BEGIN,		-- НАЧАЛО ПЕРИОДА
			[PERIOD_END]	= V.PERIOD_END,			-- КОНЕЦ ПЕРИОДА
			[REASON]	= V.REASON,			-- ОСНОВАНИЕ
			[REASON_DOP] = v.reason_dop,	-- Дополнение к основанию
			[DOC_NUM]	= V.NUMBER,			-- НОМЕР ПРИКАЗА
			[DOC_DATE]	= V.DATE,			-- ДАТА ПРИКАЗА
			[FIO]		= V.FIO,			-- ФИО
			[TN]		= V.TAB_NUM,			-- ТАБЕЛЬНЫЙ НОМЕР
			[SUBDIV]	= rtrim(V.SUBDIV),		-- ПОДРАЗДЕЛЕНИЕ
			[POST]		= rtrim(V.POST),		-- ДОЛЖНОСТЬ
			[VAC_TYPE]	= V.TYPE_NAME,			-- НАИМЕНОВАНИЕ ОТПУСКА
			[FIO_SHORT]	= LEFT(RTRIM(P.IM), 1) + '.' +  LEFT(RTRIM(P.OT), 1) + '.' + RTRIM(P.FM)
		FROM	VACATION V LEFT JOIN 
				EMPL E ON V.EMPL_LINK = E.LINK LEFT JOIN 
				PERSON P ON P.LINK = E.PERS_LINK	
		WHERE	V.ORDER_LINK = @ORDER_LINK
		) T
	ORDER	BY T.PERIOD_BEGIN, T.VAC_OSN DESC, T.PERIOD_END, T.DATE_BEGIN,  T.DATE_END
	--
	SELECT * INTO #VACATION_TABLE FROM #VACATION_TEMP
	
	DECLARE @LINK INT, @PERIOD_BEGIN DATETIME, @PERIOD_END DATETIME,@VAC_OSN INT
	WHILE EXISTS(SELECT * FROM #VACATION_TEMP) BEGIN
		SELECT	TOP 1 @LINK = LINK, @PERIOD_BEGIN = PERIOD_BEGIN, @PERIOD_END = PERIOD_END, @VAC_OSN = VAC_OSN FROM #VACATION_TEMP
		UPDATE	#VACATION_TABLE
		SET	VAC_OSN = CASE	WHEN @VAC_OSN = 1 THEN @VAC_OSN
					ELSE (SELECT MIN(VAC_OSN) - 1 FROM #VACATION_TABLE WHERE ISNULL(PERIOD_BEGIN,1) = ISNULL(@PERIOD_BEGIN,1) AND ISNULL(PERIOD_END,1) = ISNULL(@PERIOD_END,1))
				  END
		WHERE	LINK = @LINK
		DELETE	FROM #VACATION_TEMP WHERE LINK = @LINK
	END
	DROP TABLE #VACATION_TEMP
	-- РЕЗУЛЬТИРУЮЩАЯ ТАБЛИЦА ДЛЯ ОДИНОЧНОЙ ФОРМЫ ПРИКАЗА
	CREATE	TABLE #RESULT_1(ORD INT,FIO VARCHAR(300),TN VARCHAR(50),SUBDIV VARCHAR(300),POST VARCHAR(300),
				DOC_NUM VARCHAR(50),DOC_DATE DATETIME,PERIOD_B DATETIME,PERIOD_E DATETIME,
				OSN_BEGIN DATETIME,OSN_END DATETIME,OSN_DUR INT,
				DOP1_BEGIN DATETIME,DOP1_END DATETIME,DOP1_DUR INT,DOP1_TYPE VARCHAR(300),
				DOP2_BEGIN DATETIME,DOP2_END DATETIME,DOP2_DUR INT,DOP2_TYPE VARCHAR(300),
				DOP3_BEGIN DATETIME,DOP3_END DATETIME,DOP3_DUR INT,DOP3_TYPE VARCHAR(300),
				DOP4_BEGIN DATETIME,DOP4_END DATETIME,DOP4_DUR INT,DOP4_TYPE VARCHAR(300),
				FIO_SHORT VARCHAR(50), CLASS_CHIN VARCHAR(254))
	-- РЕЗУЛЬТИРУЮЩАЯ ТАБЛИЦА ДЛЯ ГРУППОВОЙ ФОРМЫ ПРИКАЗА
	CREATE	TABLE #RESULT_2(FIO VARCHAR(300),TN VARCHAR(50),SUBDIV VARCHAR(300),POST VARCHAR(300),
				DOC_NUM VARCHAR(50),DOC_DATE DATETIME,PERIOD_B DATETIME,PERIOD_E DATETIME,
				DATE_BEGIN DATETIME,DATE_END DATETIME,DUR_OSN INT,DUR_DOP INT,DUR INT,
				VAC_TYPE VARCHAR(300), FIO_SHORT VARCHAR(50))
	
	DECLARE @ORD INT,@DATE_BEGIN DATETIME,@DATE_END DATETIME,@DURATION INT,@REASON_LINK int,@REASON VARCHAR(200),@REASON_DOP VARCHAR(500),@SUBDIV VARCHAR(150),@TN VARCHAR(20),
		@FIO VARCHAR(150),@DOC_NUM VARCHAR(20),@DOC_DATE DATETIME,@VAC_TYPE VARCHAR(150),@POST VARCHAR(150), @FIO_SHORT VARCHAR(50), @CLASS_CHIN VARCHAR(254)

---------------------]
SET	@CLASS_CHIN = (
			SELECT TOP 1 CH.CHIN_NAME 
			FROM ORDERS			ORD1	LEFT JOIN 
				 VACATION		V	ON ORD1.LINK = V.ORDER_LINK  LEFT JOIN
				 KU_EMPL_CHIN	CH		ON CH.EMPL_LINK = V.EMPL_LINK
			WHERE V.ORDER_LINK = @ORDER_LINK
			ORDER BY CH.DATE DESC)
---------------------------
	DECLARE @DEP_LINK INT
	DECLARE @CHIEF VARCHAR(50), @CHIEF_POST VARCHAR(150), @CHIEF_LINK INT, @LONGNAME VARCHAR(150), @OKPO VARCHAR(50)
	SET @DEP_LINK = (SELECT DEP_LINK FROM USER_DEP)
	SELECT @CHIEF = FACE_NAME, @CHIEF_LINK = FACE_LINK FROM DICTIONARY_OTV_FACE WHERE DEP_LINK = @DEP_LINK AND NAME = 'Руководитель'
	SELECT @LONGNAME = FULL_NAME, @OKPO = OKPO FROM DEPARTMENTS WHERE LINK = @DEP_LINK
	SELECT @CHIEF_POST = POST_NAME FROM KU_EMPL_PLACING WHERE LINK = @CHIEF_LINK

	-- ПРОВЕРКА НА ТИП ПРИКАЗА (ОДИНОЧНЫЙ/ГРУППОВОЙ)
	IF @nCHECK != 1 BEGIN
		SET @REASON = (SELECT TOP 1 REASON FROM #VACATION_TABLE WHERE LEN(RTRIM(LTRIM(REASON))) != 0)
		SET @REASON_DOP = (SELECT TOP 1 REASON_DOP FROM #VACATION_TABLE WHERE LEN(RTRIM(LTRIM(REASON_DOP))) != 0)
		SET @ORD = 0
	 	WHILE EXISTS(SELECT * FROM #VACATION_TABLE) BEGIN		
	 		SELECT	TOP 1 @LINK = LINK, @VAC_OSN = VAC_OSN, @DATE_BEGIN = DATE_BEGIN, @DATE_END = DATE_END, @DURATION = DURATION,
			@PERIOD_BEGIN = PERIOD_BEGIN, @PERIOD_END = PERIOD_END, @DOC_NUM = DOC_NUM,  @DOC_DATE = DOC_DATE,
					@FIO = FIO, @TN = TN, @SUBDIV = SUBDIV, @POST = POST, @VAC_TYPE = VAC_TYPE, @FIO_SHORT = FIO_SHORT
			FROM	#VACATION_TABLE
			IF NOT EXISTS(SELECT * FROM #RESULT_1 WHERE PERIOD_B = @PERIOD_BEGIN AND @PERIOD_END = PERIOD_E) SET @ORD = @ORD + 1
			IF @VAC_OSN = 1 BEGIN
				INSERT	INTO #RESULT_1
				VALUES	(@ORD, @FIO, @TN, @SUBDIV, @POST, @DOC_NUM, @DOC_DATE, @PERIOD_BEGIN, @PERIOD_END,
					 @DATE_BEGIN, @DATE_END, @DURATION, NULL, NULL, 0,'', NULL, NULL, 0,'', NULL, NULL, 0,'', NULL, NULL, 0, '', @FIO_SHORT, @CLASS_CHIN)
			END
			ELSE BEGIN
				IF NOT EXISTS(SELECT * FROM #RESULT_1 WHERE ORD = @ORD) BEGIN
					INSERT	INTO #RESULT_1
					VALUES	(@ORD, @FIO, @TN, @SUBDIV, @POST, @DOC_NUM, @DOC_DATE, @PERIOD_BEGIN, @PERIOD_END,
						 NULL, NULL, 0, NULL, NULL, 0,'', NULL, NULL, 0,'', NULL, NULL, 0,'', NULL, NULL, 0, '', @FIO_SHORT,@CLASS_CHIN)
				END
				IF @VAC_OSN = -1
					UPDATE	#RESULT_1
					SET	DOP1_BEGIN = @DATE_BEGIN, DOP1_END = @DATE_END, DOP1_DUR = @DURATION, DOP1_TYPE = @VAC_TYPE
					WHERE	ORD = @ORD
				IF @VAC_OSN = -2
					UPDATE	#RESULT_1
					SET	DOP2_BEGIN = @DATE_BEGIN, DOP2_END = @DATE_END, DOP2_DUR = @DURATION, DOP2_TYPE = @VAC_TYPE
					WHERE	ORD = @ORD
				IF @VAC_OSN = -3
					UPDATE	#RESULT_1
					SET	DOP3_BEGIN = @DATE_BEGIN, DOP3_END = @DATE_END, DOP3_DUR = @DURATION, DOP3_TYPE = @VAC_TYPE
					WHERE	ORD = @ORD
				IF @VAC_OSN = -4
					UPDATE	#RESULT_1
					SET	DOP4_BEGIN = @DATE_BEGIN, DOP4_END = @DATE_END, DOP4_DUR = @DURATION, DOP4_TYPE = @VAC_TYPE
					WHERE	ORD = @ORD
			END
	 		DELETE FROM #VACATION_TABLE WHERE LINK = @LINK
	 	END
	
		DECLARE @DUR INT, @DATE_B DATETIME, @DATE_E DATETIME
		SET @DUR = (SELECT SUM(OSN_DUR) + SUM(DOP1_DUR) + SUM(DOP2_DUR) + SUM(DOP3_DUR) + SUM(DOP4_DUR) FROM #RESULT_1)
			
		CREATE	TABLE #DATE_TEMP (VALUE DATETIME)
		INSERT	INTO #DATE_TEMP
		SELECT	MIN(OSN_BEGIN) FROM #RESULT_1
		UNION ALL
		SELECT	MIN(DOP1_BEGIN) FROM #RESULT_1
		UNION ALL
		SELECT	MIN(DOP2_BEGIN) FROM #RESULT_1
		UNION ALL
		SELECT	MIN(DOP3_BEGIN) FROM #RESULT_1
		UNION ALL
		SELECT	MIN(DOP4_BEGIN) FROM #RESULT_1
		SET @DATE_B = (SELECT MIN(VALUE) FROM #DATE_TEMP)
	
		DELETE FROM #DATE_TEMP
		INSERT	INTO #DATE_TEMP
		SELECT	MAX(OSN_END) FROM #RESULT_1
		UNION ALL
		SELECT	MAX(DOP1_END) FROM #RESULT_1
		UNION ALL
		SELECT	MAX(DOP2_END) FROM #RESULT_1
		UNION ALL
		SELECT	MAX(DOP3_END) FROM #RESULT_1
		UNION ALL
		SELECT	MAX(DOP4_END) FROM #RESULT_1
		SET @DATE_E = (SELECT MAX(VALUE) FROM #DATE_TEMP)
		DROP TABLE #DATE_TEMP
		
 		SELECT	T.*,
			[LONGNAME] = @LONGNAME,
			[CHIEF] = @CHIEF,
			[CHIEF_POST] = @CHIEF_POST,
			[OKPO] = @OKPO,
			[DUR] = @DUR,
			[DATE_B] = @DATE_B,
			[DATE_E] = @DATE_E,
			[REASON] = @REASON,
			[REASON_DOP] = @REASON_DOP
 		FROM	#RESULT_1 T
	END ELSE BEGIN
		INSERT	INTO #RESULT_2
		SELECT	FIO,TN,SUBDIV,POST,DOC_NUM,DOC_DATE,PERIOD_BEGIN,PERIOD_END,DATE_BEGIN,DATE_END,
			CASE WHEN VAC_OSN = 1 THEN DURATION
			     ELSE 0
			END,
			CASE WHEN VAC_OSN != 1 THEN DURATION
			     ELSE 0
			END,
			DURATION,
			CASE WHEN VAC_OSN = 1 THEN ''
			     ELSE VAC_TYPE
			END, FIO_SHORT
		FROM	#VACATION_TABLE

		SELECT	T.*,
			[LONGNAME] = @LONGNAME,
			[CHIEF] = @CHIEF,
			[CHIEF_POST] = @CHIEF_POST,
			[OKPO] = @OKPO
		FROM	#RESULT_2 T
		ORDER	BY FIO, DATE_BEGIN
	END
	--
	DROP TABLE #VACATION_TABLE
	DROP TABLE #RESULT_1
	DROP TABLE #RESULT_2




GO


GRANT EXECUTE ON dbo.[KJ_FORM_T6] TO PUBLIC

GO



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

GO
CREATE PROCEDURE dbo.BK_EXPORT_F1152026_503 (@iLINK_FORM INT)
AS
BEGIN
--перенос формы из архивной базы
	exec dbo.RN_MOVE_FORM_FROM_ARH @iLINK_FORM

	DECLARE @FNAME VARCHAR (254),
		@FNAME_ID VARCHAR (254),

		@PART_NAME_NNN VARCHAR (100),

		@DEP_LINK	INT,
		@INN	VARCHAR (12),
		@KPP VARCHAR (9),
		@IMNS VARCHAR (4),
		@OKVED VARCHAR (8),
		@TLF_GL_BUH	VARCHAR (10),
		@DEP_NAME VARCHAR (254),

		@C_PLACE	VARCHAR (3),
		@C_TYPE		VARCHAR (1),

		@NAME_RUK	VARCHAR (60),
		@FAM_RUK	VARCHAR (60),
		@OT_RUK		VARCHAR (60),

		@dDATE_FORM	DATETIME,
		@PERIOD_TYPE	INT,
		@PERIOD_NUM	INT,
		@cPERIOD_NUM	VARCHAR (2),

		@iLINK_TABLE	INT,
		@PROC_NAME	VARCHAR (254),

		--- Раздел 1 ---
		@KBK		VARCHAR (20),
		@OKTMO		VARCHAR (15),
		@OKTMO_DEP	VARCHAR (15),
		@SUMMA		NUMERIC (15,0),

		--- Раздел 2 ---
		@ST_IMUSH	NUMERIC (15,0),
		@CODE_NL	VARCHAR (20),
		@ST_IMUSH_NO NUMERIC (15,0),
		@Dol_ST	VARCHAR (21),
		@CODE_LG_PNS VARCHAR (7),
		@NAL_STAV	NUMERIC (3,2),
		@NAL_BASE	NUMERIC (15,0),
		@SUM_NAL_PER	NUMERIC (15,0),
		@OST_SUM_ALL	NUMERIC (15,0),

		@SumAV	NUMERIC (15),
		@CODE_LG_UM	VARCHAR (7),
		@SUM_LG_UM NUMERIC (15),

		@SUM_NAL_PRED	NUMERIC (15),

		@strNUM_COR	VARCHAR (3),

		@strEXEC	VARCHAR (8000),

		@cREORG_CODE	VARCHAR (1),
		@cREORG_INN	VARCHAR (12),
		@cREORG_KPP	VARCHAR (12)

	--- ---
	SELECT @DEP_LINK = LINK_ORGANIZATION,
			@dDATE_FORM	= BEGIN_DATE,
			@PERIOD_TYPE = PERIOD_TYPE,
			@PERIOD_NUM	= PERIOD_NUMBER
	FROM dbo.REPORT_SAVED_FORMS RSF
	WHERE link_saved_form = @iLINK_FORM

	EXEC dbo.GetRandStr 36, @PART_NAME_NNN OUTPUT

	SELECT @INN	= CONVERT (VARCHAR (10), INN_LONG),
			@KPP = CONVERT (VARCHAR (9), KPP),
			@IMNS = CONVERT (VARCHAR (4), IMNS),
			@OKVED = CONVERT (VARCHAR (8), OKVED),
			@DEP_NAME = [NAME],
			@OKTMO_DEP = CONVERT (VARCHAR (11), REPLACE (OKTMO, ' ', ''))
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @DEP_LINK

	SELECT @TLF_GL_BUH = PHONE
	FROM dbo.DICTIONARY_OTV_FACE
	WHERE DEP_LINK = @DEP_LINK
		AND [NAME] = 'Главный бухгалтер'

	SELECT @NAME_RUK = IM,
			@FAM_RUK = FM,
			@OT_RUK = OT
	FROM dbo.KU_EMPL_PLACING 
	WHERE LINK = (SELECT FACE_LINK FROM dbo.DICTIONARY_OTV_FACE
					WHERE DEP_LINK = @DEP_LINK
						AND [NAME] = 'Руководитель')

	--- !!!РАСЧЕТ!!! ---
	-- Данные раздела 1 --
	SELECT
		@iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 1
		)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R1
		(CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (50),
		COL2 VARCHAR(254),	-- КБК
		FCOL2 VARCHAR (254),
		COL3 VARCHAR (100), 	-- ОКТМО
		FCOL3 VARCHAR (254),
		COL4 VARCHAR(100), 	-- Сумма к уплате
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Сумма к уменьшению
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- По месту нахождения
		FCOL6 VARCHAR (254),
		COL7 VARCHAR(100), 	-- Вид имущества
		FCOL7 VARCHAR (254),
		COL8 VARCHAR(100), 	-- Код налогового периода
		FCOL8 VARCHAR (254),
		COL9 VARCHAR(100), 	-- Форма реорганизации
		FCOL9 VARCHAR (254),
		COL10 VARCHAR(100), 	-- INN реорганизации
		FCOL10 VARCHAR (254),
		COL11 VARCHAR(100), 	-- KPP реорганизации
		FCOL11 VARCHAR (254),
		COL12 VARCHAR(100), 	-- Номер корректировки
		FCOL12 VARCHAR (254),
		ITOG NUMERIC (20)) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R1 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, FCOL2, COL3, FCOL3,
		COL4, FCOL4, COL5, FCOL5,
		COL6, FCOL6, COL7, FCOL7,
		COL8, FCOL8, COL9, FCOL9,
		COL10, FCOL10, COL11, FCOL11, COL12, FCOL12, ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

	SELECT
		@KBK = ISNULL (COL2, ''),
		@OKTMO = ISNULL (COL3, ''),
		@SUMMA = CONVERT (NUMERIC (15), COL4) - ISNULL (CONVERT (NUMERIC (15), COL5), 0),
		@C_PLACE = ISNULL (COL6, ''),
		@cPERIOD_NUM = ISNULL (COL8, ''),

		@cREORG_CODE = ISNULL (COL9, ''),
		@cREORG_INN = ISNULL (COL10, ''),
		@cREORG_KPP = ISNULL (COL11, ''),

		@strNUM_COR = ISNULL (COL12, ''),
		@C_TYPE = ISNULL (COL7, '')
	FROM #TAB_R1

	-- ДАННЫЕ РАЗДЕЛА 2 --
	-- Данные раздела 2.1 --
	--- Остаточная стоимость имущества по месяцам ---
	SELECT 
		@iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 2
		)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R21
		(CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (254),
		COL2 VARCHAR(254),	
		COL3 NUMERIC (20), 	-- Сумма
		FCOL3 VARCHAR (254),
		COL4 NUMERIC (20), 	-- Налоговая ставка
		FCOL4 VARCHAR (254),
		ITOG NUMERIC (20)) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R21 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, COL3, FCOL3,
		COL4, FCOL4, ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

-- SELECT * FROM #TAB_R21

	-- Данные раздела 2.2 --
	-- !!!Расчет!!! --
	SELECT @iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 3)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R22
		(CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (254),
		COL2 VARCHAR(254),	
		COL3 NUMERIC (20), 	-- Сумма
		FCOL3 VARCHAR (254),
		COL4 NUMERIC (20, 2), 	-- Налоговая ставка
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Код налоговой льготы 1
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- Код налоговой льготы 2
		FCOL6 VARCHAR (254),
		ITOG NUMERIC (20)) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R22 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, COL3, FCOL3,
		COL4, FCOL4, COL5, FCOL5,
		COL6, FCOL6, 
		ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

-- SELECT * FROM #TAB_R22

	SELECT @ST_IMUSH = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '150'

	SELECT @CODE_NL = CONVERT (VARCHAR (7), COL5)
		+ CASE
			WHEN LEN (COL6) = 0 THEN ''
			ELSE '/' + CONVERT (VARCHAR (12), COL6)
		END
	FROM #TAB_R22
	WHERE CODE = '160'

	SELECT @ST_IMUSH_NO = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '170'

	SELECT @Dol_ST = CONVERT (VARCHAR (22), COL5)
	FROM #TAB_R22
	WHERE CODE = '180'

	SELECT @NAL_BASE = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '190'

	SELECT @CODE_LG_PNS = CONVERT (VARCHAR (7), COL5)
		+ CASE
			WHEN LEN (COL6) = 0 THEN ''
			ELSE '/' + CONVERT (VARCHAR (12), COL6)
		END
	FROM #TAB_R22
	WHERE CODE = '200'

	SELECT @NAL_STAV = CONVERT (NUMERIC (4,2), COL4)
	FROM #TAB_R22
	WHERE CODE = '210'

	SELECT @SUM_NAL_PER = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '220'

	SELECT @SumAV = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '230'

	SELECT @CODE_LG_UM = CONVERT (VARCHAR (7), COL5)
		+ CASE
			WHEN LEN (COL6) = 0 THEN ''
			ELSE '/' + CONVERT (VARCHAR (12), COL6)
		END
	FROM #TAB_R22
	WHERE CODE = '240'

	SELECT @SUM_LG_UM = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '250'

	SELECT @SUM_NAL_PRED = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '260'

	SELECT
		@OST_SUM_ALL = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '270'

	-- Данные раздела 3 --
	-- !!!Расчет!!! --
	SELECT 
		@iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 4
		)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R3
		(
		CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (254),
		COL2 VARCHAR(254),	
		COL3 NUMERIC (20), 	-- Сумма
		FCOL3 VARCHAR (254),
		COL4 NUMERIC (20, 2), 	-- Налоговая ставка
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Код налоговой льготы 1
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- Код налоговой льготы 2
		FCOL6 VARCHAR (254),
		COL7 VARCHAR (100), 	-- Кадастровый номер
		FCOL7 VARCHAR (254),
		ITOG NUMERIC (20)
		) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R3 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, COL3, FCOL3,
		COL4, FCOL4, COL5, FCOL5,
		COL6, FCOL6, COL7, FCOL7, 
		ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

-- SELECT * FROM #TAB_R3

	--- Формирование XML ---
	SELECT @FNAME_ID = 'NO_IMUD_' + ISNULL (RTRIM (@IMNS), '0000') + '_' + ISNULL (RTRIM (@IMNS), '0000') + '_'
		+ ISNULL (RTRIM (@INN), '0000000000') + ISNULL (RTRIM (@KPP), '000000000')
		+ '_' + CONVERT (VARCHAR (10), GETDATE (), 112) + '_'
		+ SUBSTRING (@PART_NAME_NNN, LEN (@PART_NAME_NNN) - 36, 36) 

	SELECT @FNAME = RTRIM (@FNAME_ID) + '.XML'

	DECLARE @OUTPUT TABLE (ID int identity(1,1), F_NAME VARCHAR(254) DEFAULT (''),
			OUT_TEXT TEXT DEFAULT (''))

	--Строка заголовка
	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 = 'SMETA'

	SET @NAME_PROG = RTRIM (@NAME_PROG) + ' ' + @VERS_PROG

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'OEM')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<?xml version="1.0" encoding="windows-1251" ?>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Файл xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИдФайл="' + RTRIM (@FNAME_ID) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсПрог="' + RTRIM (LEFT (@NAME_PROG, 40)) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсФорм="5.03">')

-- Документ

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Документ КНД="1152026"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ДатаДок="' + CONVERT (VARCHAR (10), GETDATE (), 104) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Период="' + @cPERIOD_NUM + '"')	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ОтчетГод="' + LTRIM (STR (YEAR (@dDATE_FORM))) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КодНО="' + ISNULL (@IMNS, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НомКорр="' + ISNULL (@strNUM_COR, '0') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ПоМесту="' + ISNULL (@C_PLACE, '') + '">')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СвНП ОКВЭД="' + ISNULL (@OKVED, '') + '"')
	IF ISNULL (@TLF_GL_BUH, '') <> ''
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Тлф="' + RTRIM (ISNULL (@TLF_GL_BUH, '')) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НПЮЛ НаимОрг="'
			 + RTRIM (ISNULL (REPLACE (@DEP_NAME, '"', '&quot;'), '')) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИННЮЛ="' + ISNULL (@INN, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КПП="' + ISNULL (@KPP, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '>')

	-- Сведения о реорганизованной (ликвидированной) организации (СвРеоргЮЛ)
	IF LEN (@cREORG_CODE) > 0	
	BEGIN
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СвРеоргЮЛ ФормРеорг="'
			+ ISNULL (@cREORG_CODE, '') + '"')

		IF @cREORG_CODE LIKE '[1-3, 5-6]'
		BEGIN
			INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИННЮЛ="' + @cREORG_INN + '"')
			INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КПП="' + @cREORG_KPP + '"')
		END	
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '/>')
	END

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</НПЮЛ>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СвНП>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Подписант ПрПодп="1">')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ФИО Фамилия="' + RTRIM (ISNULL (@FAM_RUK, '')) 
					+ '" Имя="' + RTRIM (@NAME_RUK) + '"'
					+ CASE WHEN ISNULL (@OT_RUK, '') <> '' THEN ' Отчество="' + RTRIM (ISNULL (@OT_RUK, '')) + '"'
							ELSE '' END
					+ '/>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Подписант>')

	-- Данные налога на имущество --
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ИмущНД>')

   	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СумНалПУ КБК="' + ISNULL (@KBK, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ОКТМО="'
										+ CASE
											WHEN ISNULL (@OKTMO, '') = '' THEN ISNULL (@OKTMO_DEP, '')
											ELSE @OKTMO
										END + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалПУ="' + LTRIM (STR (ISNULL (@SUMMA, 0))) + '">')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОбДеятРФ>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОб ВидИмущ="' + ISNULL (@C_TYPE, '') + '">')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ДанРас СтИмущ="' + LTRIM (STR (ISNULL (@ST_IMUSH, 0))) + '"'
			+	CASE WHEN ISNULL (@CODE_NL, '') = '' THEN ''
					ELSE ' КодНалЛьг="' + @CODE_NL + '"'
				END
			+	CASE WHEN ISNULL (@ST_IMUSH_NO, 0) = 0 THEN ''
					ELSE ' СтИмущНеобл="' + LTRIM (STR (ISNULL (@ST_IMUSH_NO, 0))) + '"'
				END
			+	CASE WHEN ISNULL (@Dol_ST, '') = '' THEN ''
					ELSE ' ДолСт="' + @Dol_ST + '"'
				END
			+	CASE WHEN ISNULL (@CODE_LG_PNS, '') = '' THEN ''
					ELSE ' КодЛгПНС="' + @CODE_LG_PNS + '"'
				END
			+	' НалСтав="' + LTRIM (STR (ISNULL (@NAL_STAV, 0.0), 4, 2)) + '"'
			+ '>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СтоимМес>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) 
	SELECT @FNAME,
		CASE
			WHEN CODE = '141' THEN '<ВтчНедИм'
			ELSE '<ОстСтом' + REPLACE (RTRIM (COL1), '.', '')
		END
		+ CASE WHEN ISNULL (COL3, 0) = 0 THEN ''
				ELSE ' СтОстОН="' + LTRIM (STR (COL3)) +'"'
			END
		+ CASE WHEN ISNULL (COL4, 0) = 0 THEN ''
				ELSE ' СтЛьгИмущ="' + LTRIM (STR (COL4)) +'"'
			END
		+ '/>'
	FROM #TAB_R21
	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СтОстВс>' + LTRIM (STR (ISNULL (@OST_SUM_ALL, 0))) + '</СтОстВс>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СтоимМес>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ДанРас>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НалПер НалБаза="' + LTRIM (STR (ISNULL (@NAL_BASE, 0))) + '"'
			+ ' СумНалИсчисл="' + LTRIM (STR (ISNULL (@SUM_NAL_PER, 0))) + '"'
			+ CASE WHEN ISNULL (@SumAV, 0) = 0 THEN ''
					ELSE ' СумАвИсчисл="' + LTRIM (STR (ISNULL (@SumAV, 0))) + '"'
				END
			+ CASE WHEN ISNULL (@CODE_LG_UM, '') = '' THEN ''
					ELSE ' КодЛгУмен="' + RTRIM (@CODE_LG_UM) + '"'
			END
			+ CASE WHEN ISNULL (@SUM_LG_UM, 0) = 0 THEN ''
					ELSE ' СумЛгУмен="' + LTRIM (STR (ISNULL (@SUM_LG_UM, 0))) + '"'
			END
			+ CASE WHEN ISNULL (@SUM_NAL_PRED, 0) = 0 THEN ''
					ELSE ' СумНалПред="' + LTRIM (STR (ISNULL (@SUM_NAL_PRED, 0))) + '"'
			END
			+ '/>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОб>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОбДеятРФ>')
	
	-- Выгрузка 3 раздела --
	IF EXISTS (SELECT 1 FROM #TAB_R3 WHERE (CODE = '014' OR CODE = '015') AND ISNULL (COL7, '') <> '')
	BEGIN
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОБНедИО>')

		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОб>')
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ДанРас>')
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) 
		SELECT
			@FNAME,
			CASE
				WHEN CODE = '014' THEN '<НомКадЗдан>' + LTRIM (ISNULL (COL7, '')) + '</НомКадЗдан>'
				WHEN CODE = '015' AND (ISNULL (COL7, '')) <> '' THEN '<НомКадПом>' + LTRIM (COL7) + '</НомКадПом>'
				WHEN CODE = '040' AND (ISNULL (COL5, '')) <> '' THEN '<КодНалЛьг>' + LTRIM (COL5)
						+
						CASE
							WHEN ISNULL (COL6, '') = '' THEN ''
							ELSE '/' + LTRIM (COL6)
						END
						+ '</КодНалЛьг>'
				WHEN CODE = '050' AND (ISNULL (COL5, '')) <> '' THEN '<ДолСт>' + LTRIM (COL5) + '</ДолСт>'		
				WHEN CODE = '070' AND (ISNULL (COL5, '')) <> '' THEN '<КодЛгПНС>' + LTRIM (COL5)
						+
						CASE
							WHEN ISNULL (COL6, '') = '' THEN ''
							ELSE '/' + LTRIM (COL6)
						END
						+ '</КодЛгПНС>'
				WHEN CODE = '080' THEN '<НалСтав>' + CONVERT (VARCHAR (10), ISNULL (COL4, 0)) + '</НалСтав>'		
				WHEN CODE = '090' AND (ISNULL (COL5, '')) <> '' THEN '<КоэфК>' + LTRIM (COL5)
						+
						CASE
							WHEN ISNULL (COL6, '') = '' THEN ''
							ELSE '/' + LTRIM (COL6)
						END
						+ '</КоэфК>'
				ELSE ''
			END
		FROM #TAB_R3
		WHERE CODE = '014'
			OR CODE = '015' 
			OR CODE = '040'
			OR CODE = '050'
			OR CODE = '070'
			OR CODE = '080'
			OR CODE = '090'
		ORDER BY CODE	

		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СведСтКад>')
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) 
		SELECT
			@FNAME,
			CASE 
				WHEN CODE = '020' THEN '<СтИмущК>' + CONVERT (VARCHAR (20), ISNULL (COL3, 0)) + '</СтИмущК>'
				WHEN CODE = '025' AND ISNULL (COL3, 0) <> 0 THEN '<СтИмущНеоблК>' + CONVERT (VARCHAR (20), COL3) + '</СтИмущНеоблК>'
				ELSE ''
			END
		FROM #TAB_R3
		WHERE
			CODE = '020'
			OR CODE = '025' 
		ORDER BY CODE	
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СведСтКад>')

		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СведСтИнв>')
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) 
		SELECT
			@FNAME,
			CASE 
				WHEN CODE = '030' THEN '<СтИмущИ>' + CONVERT (VARCHAR (20), ISNULL (COL3, 0)) + '</СтИмущИ>'
				WHEN CODE = '035' AND ISNULL (COL3, 0) <> 0 THEN '<СтИмущНеоблИ>' + CONVERT (VARCHAR (20), COL3) + '</СтИмущНеоблИ>'
				ELSE ''
			END
		FROM #TAB_R3
		WHERE
			CODE = '030'
			OR CODE = '035' 
		ORDER BY CODE	
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СведСтИнв>')

		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ДанРас>')
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НалПер>')
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT)
		SELECT
			@FNAME,
			CASE 
				WHEN CODE = '060' THEN '<НалБаза>' + CONVERT (VARCHAR (20), ISNULL (COL3, 0)) + '</НалБаза>'
				WHEN CODE = '100' THEN '<СумНалИсчисл>' + CONVERT (VARCHAR (20), ISNULL (COL3, 0)) + '</СумНалИсчисл>'
				WHEN CODE = '110' AND ISNULL (COL3, 0) <> 0 THEN '<СумАвИсчисл>' + CONVERT (VARCHAR (20), COL3) + '</СумАвИсчисл>'
				WHEN CODE = '120' AND (ISNULL (COL5, '')) <> '' THEN '<КодЛгУмен>' + LTRIM (COL5)
						+
						CASE
							WHEN ISNULL (COL6, '') = '' THEN ''
							ELSE '/' + LTRIM (COL6)
						END
						+ '</КодЛгУмен>'
				WHEN CODE = '130' AND ISNULL (COL3, 0) <> 0 THEN '<СумЛгУмен>' + CONVERT (VARCHAR (20), COL3) + '</СумЛгУмен>'
				ELSE ''
			END
		FROM #TAB_R3
		WHERE
			CODE = '060' 
			OR CODE = '100' 
			OR CODE = '110' 
			OR CODE = '120' 
			OR CODE = '130' 
		ORDER BY CODE	
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</НалПер>')

		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОб>')
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОБНедИО>')
	END	-- Выгрузка 3 раздела --

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СумНалПУ>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ИмущНД>')

	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Документ>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Файл>')

	SELECT * FROM @OUTPUT ORDER BY ID

	DROP TABLE #TAB_R1
	DROP TABLE #TAB_R21
	DROP TABLE #TAB_R22
	DROP TABLE #TAB_R3
	DROP TABLE #TASK_PROP
END 

GO

GRANT EXECUTE ON dbo.[BK_EXPORT_F1152026_503] 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
	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

---
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	
--SELECT @INDEX_OPT2, * FROM @INDEX

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

--
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
	
END -- IF @RECALC = 0


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.4)
	
	--- Время за расчетный период
	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 @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.[BK_EXPORT_F1152028_503]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_EXPORT_F1152028_503]

GO
CREATE PROCEDURE dbo.BK_EXPORT_F1152028_503
	(@iLINK_FORM INT)
AS
BEGIN
--перенос формы из архивной базы
	exec dbo.RN_MOVE_FORM_FROM_ARH @iLINK_FORM

	DECLARE
		@FNAME VARCHAR (254),
		@FNAME_ID VARCHAR (254),

		@PART_NAME_NNN VARCHAR (100),

		@DEP_LINK	INT,
		@INN	VARCHAR (12),
		@KPP VARCHAR (9),
		@IMNS VARCHAR (4),
		@OKVED VARCHAR (8),
		@TLF_GL_BUH	VARCHAR (10),
		@DEP_NAME VARCHAR (254),

		@C_PLACE	VARCHAR (3),
		@C_TYPE		VARCHAR (1),

		@NAME_RUK	VARCHAR (60),
		@FAM_RUK	VARCHAR (60),
		@OT_RUK		VARCHAR (60),

		@dDATE_FORM	DATETIME,
		@PERIOD_TYPE	INT,
		@PERIOD_NUM	INT,
		@cPERIOD_NUM	VARCHAR (2),

		@iLINK_TABLE	INT,
		@PROC_NAME	VARCHAR (254),

		--- Раздел 1 ---
		@KBK VARCHAR (20),
		@OKTMO VARCHAR (15),
		@OKTMO_DIC VARCHAR (15),
		@SUMMA	NUMERIC (15,0),

		--- Раздел 2 ---
		@ST_IMUSH	NUMERIC (15,0),
		@CODE_NL	VARCHAR (20),
		@ST_IMUSH_NO NUMERIC (15,0),
		@Dol_ST	VARCHAR (21),
		@CODE_LG_PNS VARCHAR (7),
		@NAL_STAV	NUMERIC (3,2),
		@NAL_BASE	NUMERIC (15,0),
		@SUM_NAL_PER	NUMERIC (15,0),

		@SumAV	NUMERIC (15),
		@CODE_LG_UM	VARCHAR (7),
		@SUM_LG_UM NUMERIC (15),

		@SUM_NAL_PRED	NUMERIC (15),
		@OST_SUM_ALL	NUMERIC (15,0),

		@strNUM_COR	VARCHAR (3),

		@strEXEC	VARCHAR (8000),

		@cREORG_CODE	VARCHAR (1),
		@cREORG_INN	VARCHAR (12),
		@cREORG_KPP	VARCHAR (12)

	--- ---
	SELECT
		@DEP_LINK = LINK_ORGANIZATION,
		@dDATE_FORM	= BEGIN_DATE,
		@PERIOD_TYPE = PERIOD_TYPE,
		@PERIOD_NUM	= PERIOD_NUMBER
	FROM dbo.REPORT_SAVED_FORMS RSF
	WHERE link_saved_form = @iLINK_FORM

	EXEC dbo.GetRandStr 36, @PART_NAME_NNN OUTPUT

	SELECT
		@INN	= CONVERT (VARCHAR (10), INN_LONG),
		@KPP = CONVERT (VARCHAR (9), KPP),
		@IMNS = CONVERT (VARCHAR (4), IMNS),
		@OKVED = CONVERT (VARCHAR (8), OKVED),
		@DEP_NAME = [NAME],
		@OKTMO_DIC = CONVERT (VARCHAR (11), REPLACE (OKTMO, ' ', ''))
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @DEP_LINK

	SELECT
		@TLF_GL_BUH = PHONE
	FROM dbo.DICTIONARY_OTV_FACE
	WHERE DEP_LINK = @DEP_LINK
		AND [NAME] = 'Главный бухгалтер'

	SELECT
		@NAME_RUK = IM,
		@FAM_RUK = FM,
		@OT_RUK = OT
	FROM dbo.KU_EMPL_PLACING 
	WHERE LINK = (SELECT FACE_LINK FROM dbo.DICTIONARY_OTV_FACE
					WHERE DEP_LINK = @DEP_LINK
						AND [NAME] = 'Руководитель')

	--- !!!РАСЧЕТ!!! ---
	-- Данные раздела 1 --
	SELECT 
		@iLINK_TABLE = RT.LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 1
		)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R1
		(
		CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (50),
		COL2 VARCHAR(254),	-- КБК
		FCOL2 VARCHAR (254),
		COL3 VARCHAR (100), 	-- ОКТМО
		FCOL3 VARCHAR (254),
		COL4 VARCHAR(100), 	-- Сумма к уплате
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Сумма к уменьшению
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- По месту нахождения
		FCOL6 VARCHAR (254),
		COL7 VARCHAR(100), 	-- Вид имущества
		FCOL7 VARCHAR (254),
		COL8 VARCHAR(100), 	-- Код налогового периода
		FCOL8 VARCHAR (254),
		COL9 VARCHAR(100), 	-- Форма реорганизации
		FCOL9 VARCHAR (254),
		COL10 VARCHAR(100), 	-- INN реорганизации
		FCOL10 VARCHAR (254),
		COL11 VARCHAR(100), 	-- KPP реорганизации
		FCOL11 VARCHAR (254),
		COL12 VARCHAR(100), 	-- Номер корректировки
		FCOL12 VARCHAR (254),
		ITOG NUMERIC (20)
		) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R1 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, FCOL2, COL3, FCOL3,
		COL4, FCOL4, COL5, FCOL5,
		COL6, FCOL6, COL7, FCOL7,
		COL8, FCOL8, COL9, FCOL9,
		COL10, FCOL10, COL11, FCOL11, COL12, FCOL12, ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

	SELECT
		@KBK = ISNULL (COL2, ''),
		@OKTMO = ISNULL (COL3, ''),
		@SUMMA = CONVERT (NUMERIC (15), COL4) - ISNULL (CONVERT (NUMERIC (15), COL5), 0),
		@C_PLACE = ISNULL (COL6, ''),
		@cPERIOD_NUM = ISNULL (COL8, ''),

		@cREORG_CODE = ISNULL (COL9, ''),
		@cREORG_INN = ISNULL (COL10, ''),
		@cREORG_KPP = ISNULL (COL11, ''),

		@strNUM_COR = ISNULL (COL12, ''),
		@C_TYPE = ISNULL (COL7, '')
	FROM #TAB_R1

	-- ДАННЫЕ РАЗДЕЛА 2 --
	-- Данные раздела 2.1 --
	--- Остаточная стоимость имущества по месяцам ---
	SELECT 
		@iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 2
		)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R21
		(
		CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (254),
		COL2 VARCHAR(254),	
		COL3 NUMERIC (20), 	-- Сумма
		FCOL3 VARCHAR (254),
		COL4 NUMERIC (20), 	-- Налоговая ставка
		FCOL4 VARCHAR (254),
		ITOG NUMERIC (20)
		) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R21 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, COL3, FCOL3,
		COL4, FCOL4, ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

-- SELECT * FROM #TAB_R21

	-- Данные раздела 2.2 --
	-- !!!Расчет!!! --
	SELECT
		@iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 3
		)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R22
		(CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (254),
		COL2 VARCHAR(254),	
		COL3 NUMERIC (20), 	-- Сумма
		FCOL3 VARCHAR (254),
		COL4 NUMERIC (20, 2), 	-- Налоговая ставка
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Код налоговой льготы 1
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- Код налоговой льготы 2
		FCOL6 VARCHAR (254),
		ITOG NUMERIC (20)) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R22 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, COL3, FCOL3,
		COL4, FCOL4, COL5, FCOL5,
		COL6, FCOL6, 
		ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

-- SELECT * FROM #TAB_R22

	SELECT
		@ST_IMUSH = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '120'

	SELECT
		@CODE_NL = CONVERT (VARCHAR (7), COL5)
		+ CASE
			WHEN LEN (COL6) = 0 THEN ''
			ELSE '/' + CONVERT (VARCHAR (12), COL6)
		END
	FROM #TAB_R22
	WHERE CODE = '130'

	SELECT
		@ST_IMUSH_NO = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '140'

	SELECT
		@Dol_ST = CONVERT (VARCHAR (22), COL5)
	FROM #TAB_R22
	WHERE CODE = '150'

	SELECT
		@CODE_LG_PNS = CONVERT (VARCHAR (7), COL5)
		+ CASE
			WHEN LEN (COL6) = 0 THEN ''
			ELSE '/' + CONVERT (VARCHAR (12), COL6)
		END
	FROM #TAB_R22
	WHERE CODE = '160'

	SELECT
		@NAL_STAV = CONVERT (NUMERIC (4,2), COL4)
	FROM #TAB_R22
	WHERE CODE = '170'

	SELECT
		@SUM_NAL_PER = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '180'

	SELECT
		@CODE_LG_UM = CONVERT (VARCHAR (7), COL5)
		+ CASE
			WHEN LEN (COL6) = 0 THEN ''
			ELSE '/' + CONVERT (VARCHAR (12), COL6)
		END
	FROM #TAB_R22
	WHERE CODE = '190'

	SELECT
		@SUM_LG_UM = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '200'
	
	SELECT
		@OST_SUM_ALL = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '210'

	-- Данные раздела 3 --
	-- !!!Расчет!!! --
	SELECT 
		@iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 4
		)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R3
		(
		CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (254),
		COL2 VARCHAR(254),	
		COL3 NUMERIC (20), 	-- Сумма
		FCOL3 VARCHAR (254),
		COL4 NUMERIC (20, 2), 	-- Налоговая ставка
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Код налоговой льготы 1
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- Код налоговой льготы 2
		FCOL6 VARCHAR (254),
		COL7 VARCHAR (100), 	-- Кадастровый номер
		FCOL7 VARCHAR (254),
		ITOG NUMERIC (20)
		) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R3 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, COL3, FCOL3,
		COL4, FCOL4, COL5, FCOL5,
		COL6, FCOL6, COL7, FCOL7, 
		ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

 -- SELECT * FROM #TAB_R3
	--- Формирование XML ---
	SELECT
		@FNAME_ID = 'NO_IMUR_' + ISNULL (RTRIM (@IMNS), '0000') + '_' + ISNULL (RTRIM (@IMNS), '0000') + '_'
		+ ISNULL (RTRIM (@INN), '0000000000') + ISNULL (RTRIM (@KPP), '000000000')
		+ '_' + CONVERT (VARCHAR (10), GETDATE (), 112) + '_'
		+ SUBSTRING (@PART_NAME_NNN, LEN (@PART_NAME_NNN) - 36, 36) 

	SELECT @FNAME = RTRIM (@FNAME_ID) + '.XML'

	DECLARE @OUTPUT TABLE
		(
		ID INT IDENTITY (1,1),
		F_NAME VARCHAR(254) DEFAULT (''),
		OUT_TEXT TEXT DEFAULT ('')
		)

	--Строка заголовка
	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 = 'SMETA'

	SET @NAME_PROG = RTRIM (@NAME_PROG) + ' ' + @VERS_PROG

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'OEM')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<?xml version="1.0" encoding="windows-1251" ?>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Файл xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИдФайл="' + RTRIM (@FNAME_ID) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсПрог="' + RTRIM (LEFT (@NAME_PROG, 40)) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсФорм="5.03">')

	-- Документ
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Документ КНД="1152028"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ДатаДок="' + CONVERT (VARCHAR (10), GETDATE (), 104) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Период="' + @cPERIOD_NUM + '"')	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ОтчетГод="' + LTRIM (STR (YEAR (@dDATE_FORM))) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КодНО="' + ISNULL (@IMNS, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НомКорр="' + ISNULL (@strNUM_COR, '0') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ПоМесту="' + ISNULL (@C_PLACE, '') + '">')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СвНП ОКВЭД="' + ISNULL (@OKVED, '') + '"')
	IF ISNULL (@TLF_GL_BUH, '') <> ''
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Тлф="' + RTRIM (ISNULL (@TLF_GL_BUH, '')) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НПЮЛ НаимОрг="'
			 + RTRIM (ISNULL (REPLACE (@DEP_NAME, '"', '&quot;'), '')) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИННЮЛ="' + ISNULL (@INN, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КПП="' + ISNULL (@KPP, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '>')

	-- Сведения о реорганизованной (ликвидированной) организации (СвРеоргЮЛ)
	IF LEN (@cREORG_CODE) > 0	
	BEGIN
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СвРеоргЮЛ ФормРеорг="'
			+ ISNULL (@cREORG_CODE, '') + '"')
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИННЮЛ="' + ISNULL (@cREORG_INN, '') + '"')
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КПП="' + ISNULL (@cREORG_KPP, '') + '"')
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '/>')
	END

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</НПЮЛ>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СвНП>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Подписант ПрПодп="1">')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ФИО Фамилия="' + RTRIM (ISNULL (@FAM_RUK, '')) 
					+ '" Имя="' + RTRIM (@NAME_RUK) + '"'
					+ CASE WHEN ISNULL (@OT_RUK, '') <> '' THEN ' Отчество="' + RTRIM (ISNULL (@OT_RUK, '')) + '"'
							ELSE '' END
					+ '/>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Подписант>')

	-- Данные налога на имущество --
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ИмущАв>')

   	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СумНалПУ КБК="' + ISNULL (@KBK, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ОКТМО="' + CASE WHEN ISNULL (@OKTMO, '') = ''
											THEN ISNULL (@OKTMO_DIC, '')
											ELSE @OKTMO END + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалПУ="' + LTRIM (STR (ISNULL (@SUMMA, 0))) + '">')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОбДеятРФ>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОб ВидИмущ="' + ISNULL (@C_TYPE, '') + '">')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ДанРас СтИмущ="' + LTRIM (STR (ISNULL (@ST_IMUSH, 0))) + '"'
			+	CASE WHEN ISNULL (@CODE_NL, '') = '' THEN ''
					ELSE ' КодНалЛьг="' + @CODE_NL + '"'
				END
			+	CASE WHEN ISNULL (@ST_IMUSH_NO, 0) = 0 THEN ''
					ELSE ' СтИмущНеобл="' + LTRIM (STR (ISNULL (@ST_IMUSH_NO, 0))) + '"'
				END
			+	CASE WHEN ISNULL (@Dol_ST, '') = '' THEN ''
					ELSE ' ДолСт="' + @Dol_ST + '"'
				END
			+	CASE WHEN ISNULL (@CODE_LG_PNS, '') = '' THEN ''
					ELSE ' КодЛгПНС="' + @CODE_LG_PNS + '"'
				END
			+	' НалСтав="' + LTRIM (STR (ISNULL (@NAL_STAV, 0.0), 4, 2)) + '"'
			+ '>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СтоимМес>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) 
	SELECT @FNAME,
		CASE
			WHEN CODE = '141' THEN '<ВтчНедИм'
			ELSE '<ОстСтом' + REPLACE (RTRIM (COL1), '.', '')
		END
		+ CASE WHEN ISNULL (COL3, 0) = 0 THEN ''
				ELSE ' СтОстОН="' + LTRIM (STR (COL3)) +'"'
			END
		+ CASE WHEN ISNULL (COL4, 0) = 0 THEN ''
				ELSE ' СтЛьгИмущ="' + LTRIM (STR (COL4)) +'"'
			END
		+ '/>'
	FROM #TAB_R21

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СтОстВс>' + LTRIM (STR (ISNULL (@OST_SUM_ALL, 0))) + '</СтОстВс>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СтоимМес>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ДанРас>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ОтчПер СумАвИсчисл="' + LTRIM (STR (ISNULL (@SUM_NAL_PER, 0))) + '"'
			+ CASE WHEN ISNULL (@CODE_LG_UM, '') = '' THEN ''
					ELSE ' КодЛгУмен="' + RTRIM (@CODE_LG_UM) + '"'
			END
			+ CASE WHEN ISNULL (@SUM_LG_UM, 0) = 0 THEN ''
					ELSE ' СумЛгУмен="' + LTRIM (STR (ISNULL (@SUM_LG_UM, 0))) + '"'
			END
			+ '/>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОб>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОбДеятРФ>')

	-- Выгрузка 3 раздела --
	IF EXISTS (SELECT 1 FROM #TAB_R3 WHERE (CODE = '014' OR CODE = '015') AND ISNULL (COL7, '') <> '')
	BEGIN
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОБНедИО>')

		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОб>')
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ДанРас>')
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) 
		SELECT
			@FNAME,
			CASE
				WHEN CODE = '014' THEN '<НомКадЗдан>' + LTRIM (ISNULL (COL7, '')) + '</НомКадЗдан>'
				WHEN CODE = '015' AND (ISNULL (COL7, '')) <> '' THEN '<НомКадПом>' + LTRIM (COL7) + '</НомКадПом>'
				WHEN CODE = '020' THEN '<СтИмущК>' + CONVERT (VARCHAR (20), ISNULL (COL3, 0)) + '</СтИмущК>'
				WHEN CODE = '030' AND ISNULL (COL3, 0) <> 0 THEN '<СтИмущНеоблК>' + CONVERT (VARCHAR (20), COL3) + '</СтИмущНеоблК>'
				WHEN CODE = '040' AND (ISNULL (COL5, '')) <> '' THEN '<КодНалЛьг>' + LTRIM (COL5)
						+
						CASE
							WHEN ISNULL (COL6, '') = '' THEN ''
							ELSE '/' + LTRIM (COL6)
						END
						+ '</КодНалЛьг>'
				WHEN CODE = '050' AND (ISNULL (COL5, '')) <> '' THEN '<ДолСт>' + LTRIM (COL5) + '</ДолСт>'		
				WHEN CODE = '060' AND (ISNULL (COL5, '')) <> '' THEN '<КодЛгПНС>' + LTRIM (COL5)
						+
						CASE
							WHEN ISNULL (COL6, '') = '' THEN ''
							ELSE '/' + LTRIM (COL6)
						END
						+ '</КодЛгПНС>'
				WHEN CODE = '070' THEN '<НалСтав>' + CONVERT (VARCHAR (10), ISNULL (COL4, 0)) + '</НалСтав>'		
				WHEN CODE = '080' AND (ISNULL (COL5, '')) <> '' THEN '<КоэфК>' + LTRIM (COL5)
						+
						CASE
							WHEN ISNULL (COL6, '') = '' THEN ''
							ELSE '/' + LTRIM (COL6)
						END
						+ '</КоэфК>'
				ELSE ''
			END
		FROM #TAB_R3
		WHERE CODE = '014'
			OR CODE = '015'
			OR CODE = '020'
			OR CODE = '030' 
			OR CODE = '040'
			OR CODE = '050'
			OR CODE = '060'
			OR CODE = '070'
			OR CODE = '080'
		ORDER BY CODE	

		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ДанРас>')
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ОтчПер>')
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT)
		SELECT
			@FNAME,
			CASE 
				WHEN CODE = '090' THEN '<СумАвИсчисл>' + CONVERT (VARCHAR (20), ISNULL (COL3, 0)) + '</СумАвИсчисл>'
				WHEN CODE = '100' AND (ISNULL (COL5, '')) <> '' THEN '<КодЛгУмен>' + LTRIM (COL5)
						+
						CASE
							WHEN ISNULL (COL6, '') = '' THEN ''
							ELSE '/' + LTRIM (COL6)
						END
						+ '</КодЛгУмен>'
				WHEN CODE = '110' AND ISNULL (COL3, 0) <> 0 THEN '<СумЛгУмен>' + CONVERT (VARCHAR (20), COL3) + '</СумЛгУмен>'
				ELSE ''
			END
		FROM #TAB_R3
		WHERE
			CODE = '090' 
			OR CODE = '100' 
			OR CODE = '110' 
		ORDER BY CODE	
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ОтчПер>')

		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОб>')
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОБНедИО>')
	END	-- Выгрузка 3 раздела --
	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СумНалПУ>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ИмущАв>')

	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Документ>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Файл>')

	SELECT * FROM @OUTPUT ORDER BY ID

	DROP TABLE #TAB_R1
	DROP TABLE #TAB_R21
	DROP TABLE #TAB_R22
	DROP TABLE #TAB_R3
	DROP TABLE #TASK_PROP

END 

GO

GRANT EXECUTE ON dbo.[BK_EXPORT_F1152028_503] TO PUBLIC

GO

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


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

GO

CREATE    PROCEDURE [dbo].U_SAVE_DICTIONARY_STAFF_ALL_PFR
	@parLINK		int = null,
	@parLINK_UP		int = null,
	@parDATE_BEGIN	DATETIME = NULL,
	@parTERR_USL	INT = NULL,
	@parTERR_RK		NUMERIC(6,2) = 0,
	@parOSOB_USL	INT = NULL,
	@parPOS_SP1		INT = NULL,
	@parPOS_SP2		INT = NULL,
	@parSPO_UT		INT = NULL,
	@parDOS_USL		INT = NULL,
	@parPED_MED		NUMERIC(6,2) = 0,
	@parCOD_PROF	INT = NULL,
	@parOSN_STRAH	INT = NULL
AS
DECLARE @ERROR	tinyint,
		@strVALUE	varchar(7000),
		@trancount	int,
		@ObjectLink int,
		@EventText	varchar(254),
		@SQLError int
SET @trancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

	if @parLINK = 0 SET @parLINK = null
	if @parLINK_UP = 0 SET @parLINK_UP = null
	if @parTERR_USL = 0 SET @parTERR_USL = null
	if @parOSOB_USL = 0 SET @parOSOB_USL = null
	if @parPOS_SP1 = 0 SET @parPOS_SP1 = null
	if @parPOS_SP2 = 0 SET @parPOS_SP2 = NULL
	if @parSPO_UT = 0 SET @parSPO_UT = null
	if @parDOS_USL = 0 SET @parDOS_USL = null
	if @parCOD_PROF = 0 SET @parCOD_PROF = null
	if @parOSN_STRAH = 0 SET @parOSN_STRAH = null


	IF ISNULL(@parLINK,0) != 0
		UPDATE	staff
		SET		terr_usl_trud = @parTERR_USL, terr_rk = @parTERR_RK, osob_usl_trud = @parOSOB_USL, cod_pos_spisok = @parPOS_SP1, cod_pos_spisok2 = @parPOS_SP2, COD_SPO_USL_TRUD = @parSPO_UT,
				usl_dosroch_pens = @parDOS_USL, stavka_ped_med = @parPED_MED, COD_PROF = @parCOD_PROF, OSNOVANIE = @parOSN_STRAH 
		WHERE	link = @parLINK
	ELSE
	IF ISNULL(@parLINK_UP,0) != 0
		UPDATE	staff
		SET		terr_usl_trud = @parTERR_USL, terr_rk = @parTERR_RK, osob_usl_trud = @parOSOB_USL, cod_pos_spisok = @parPOS_SP1, cod_pos_spisok2 = @parPOS_SP2, COD_SPO_USL_TRUD = @parSPO_UT,
				usl_dosroch_pens = @parDOS_USL, stavka_ped_med = @parPED_MED, COD_PROF = @parCOD_PROF, OSNOVANIE = @parOSN_STRAH
		WHERE	LINK_UP = @parLINK_UP AND DATE_BEGIN = @parDATE_BEGIN

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

	SELECT @ObjectLink = LINK FROM S_OBJECTS WHERE CODE = 'DICTIONARY_STAFF_ALL'
	SET @EventText = 'История штатного расписания'
	EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника по ПФР', @EventText, @ObjectLink, 'STAFF', @parLINK_UP
IF @@TRANCOUNT > @trancount
	COMMIT TRAN

RETURN 0



GO


GRANT EXECUTE ON dbo.[U_SAVE_DICTIONARY_STAFF_ALL_PFR] TO PUBLIC

GO



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

GO


------------------------------------------------------------------------
CREATE   PROCEDURE dbo.SA_SZV4_STAZH_SAVE
	@link		int output,
	@link_up	int,
	@orders		int,
	@date1		datetime,
	@date2		datetime,
	@ter_usl	varchar(10) = '',
	@ter_koef	numeric(18,2),
	@osob_usl	varchar(10) = '',
	@osob_k1	varchar(20) = '',
	@osob_k2	varchar(20) = '',
	@osob_SPO	varchar(20) = '',
	@osob_k3	varchar(20) = '',
	@is_osnov	varchar(10) = '',
	@is_dop		varchar(20) = '',
	@is_dop_m	tinyint,
	@is_dop_d	tinyint,
	@ud_osnov	varchar(10) = '',
	@ud_dop_m	int,
	@ud_dop_d	int,
	@ud_dop_k	numeric(18,2)
AS
DECLARE @varKSERROR	tinyint, @varKSstrVALUE	 varchar(7000), @varKStrancount	 int, @varKSRowCount INT, @varKSsoLink int

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


IF coalesce(@link_up,0) = 0 or @date1 is null
BEGIN
	ROLLBACK
	RETURN 5
END

IF exists (select * from dbo.SZV4_STAZH where link <> @link and link_up = @link_up and (@date1 between date1 and coalesce(date2,'20990101') 
										or coalesce(@date2,'20990101') between date1 and coalesce(date2,'20990101') ))
BEGIN
	ROLLBACK
	RETURN 8
END

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

IF @LINK is null OR @LINK = 0
	BEGIN
		INSERT INTO dbo.SZV4_STAZH WITH (ROWLOCK) (link_up, orders, date1, date2, ter_usl, ter_koef, osob_usl, osob_k1, osob_k2, osob_spo, osob_k3, 
								is_osnov, is_dop, is_dop_m, is_dop_d, ud_osnov, ud_dop_m, ud_dop_d, ud_dop_k)
			VALUES (@link_up, @orders, @date1, @date2, RTRIM(LTRIM(@ter_usl)), @ter_koef, RTRIM(LTRIM(@osob_usl)), RTRIM(LTRIM(@osob_k1)), 
								RTRIM(LTRIM(@osob_k2)), RTRIM(LTRIM(@osob_SPO)), RTRIM(LTRIM(@osob_k3)), RTRIM(LTRIM(@is_osnov)), RTRIM(LTRIM(@is_dop)), 
								@is_dop_m, @is_dop_d, RTRIM(LTRIM(@ud_osnov)), @ud_dop_m, @ud_dop_d, @ud_dop_k)

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

		UPDATE dbo.SZV4_STAZH WITH (ROWLOCK) 
		SET 	link_up =@link_up, orders =@orders, date1 =@date1, date2 =@date2, 
			ter_usl = RTRIM(LTRIM(@ter_usl)), ter_koef = @ter_koef, osob_usl = RTRIM(LTRIM(@osob_usl)), 
			osob_k1 = RTRIM(LTRIM(@osob_k1)), osob_k2 = RTRIM(LTRIM(@osob_k2)),osob_spo = RTRIM(LTRIM(@osob_SPO)), osob_k3 = RTRIM(LTRIM(@osob_k3)), 
			is_osnov = RTRIM(LTRIM(@is_osnov)), is_dop = RTRIM(LTRIM(@is_dop)), is_dop_m = @is_dop_m, 
			is_dop_d = @is_dop_d, ud_osnov = RTRIM(LTRIM(@ud_osnov)), ud_dop_m = @ud_dop_m, ud_dop_d = @ud_dop_d, ud_dop_k = @ud_dop_k

		WHERE LINK = @LINK

		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END

/*Правильная сортировка*/
declare @uslovie int
set @uslovie = 1

update SZV4_STAZH set orders = 0 where link_up = @link_up

while @uslovie > 0
begin
	update SZV4_STAZH set orders = @uslovie 
	from SZV4_STAZH as tt
	where 	
		link_up = @link_up
		and coalesce(orders,0) = 0
		and date1 = (select min(t.date1) from SZV4_STAZH t where coalesce(orders,0) = 0 and link_up = @link_up)

	if @@rowcount > 0
		set @uslovie = @uslovie + 1
	else
		set @uslovie = 0
end


declare @varKSEventText varchar(200)
Select  @varKSEventText = 'Стаж персонифицированного учета по физлицу ' + RTRIM(LTRIM(FIO)) from dbo.SA_SZV4_SVEDENIA where link = @LINK_UP
EXECUTE WF_GENERATEEVENT 'Сохранение расчета', @varKSEventText, @varKSsoLink, 'SA_SZV4_STAZH',@LINK
WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN

RETURN 0


GO


GRANT EXECUTE ON dbo.[SA_SZV4_STAZH_SAVE] TO PUBLIC

GO



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

GO

CREATE       PROCEDURE dbo.BV_SELECT_INV_TREE
	@varKSnLINK_SELF	INT = NULL
AS

IF @varKSnLINK_SELF = 0
	SET @varKSnLINK_SELF = NULL
SELECT	0 as CHECKED, 0 as UPD, 0 as DEL, 
	-G1.LINK AS LINK,
	G2.LINK AS LINK_SELF,
	G1.CODE,
	RTRIM(LTRIM(G1.CODE)) + ' ' + G1.[NAME] AS [NAME],
	CHILDRENS = CONVERT(BIT,0),
	IMAGEINDEX = 'FOLDER'
INTO #T1
FROM dbo.GROUP_INV G1
LEFT JOIN dbo.GROUP_INV G2 ON (LTRIM(RTRIM(G2.CODE)) = LEFT(LTRIM(RTRIM(G1.CODE)), 5) AND G2.LINK <> G1.LINK)
LEFT JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = G1.ACCOUNT)
WHERE  G1.[TYPE] = 1
	AND (SA.LINK IS NULL
		OR (ZABALANS = 1 OR SA.cSinth LIKE '10[1-3]' OR SA.cSinth LIKE '108' AND cANALIT LIKE '5[1,2,4,5]')
		)
	AND G1.ISUSED = 1
UNION
SELECT	0 as CHECKED, 0 as UPD, 0 as DEL, 
	N.LINK,
	G3.LINK AS LINK_SELF,
	N.CODE,
	RTRIM(LTRIM(N.CODE)) + ' ' + N.[NAME] AS [NAME],
	CHILDRENS = CONVERT(BIT,0),
	IMAGEINDEX = 'ACCOUNT'
FROM NOMENCLATURE N
INNER JOIN GROUP_INV G3 ON (G3.LINK = N.GROUP_INV and G3.TYPE = 1)
WHERE N.ISUSED = 1

UPDATE #T1
SET	CHILDRENS = CONVERT(BIT,1)
WHERE NOT EXISTS(SELECT * FROM #T1 A WHERE A.LINK_SELF = -#T1.LINK )

SELECT * FROM #T1 
WHERE (@varKSnLINK_SELF IS NULL AND #T1.LINK_SELF IS NULL) OR (#T1.LINK_SELF = @varKSnLINK_SELF)
ORDER BY LINK_SELF, IMAGEINDEX DESC, CODE

DROP TABLE #T1

GO


GRANT EXECUTE ON dbo.[BV_SELECT_INV_TREE] TO PUBLIC

GO


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


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(ZT.BK_CODE,'.',''),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
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_NUO_DGH_FILL]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_NUO_DGH_FILL]

GO

CREATE PROCEDURE DBO.SD_NUO_DGH_FILL
@varKSdDate datetime = NULL,
@DEP_LINK INT = NULL,
@MODE TINYINT = 1,
@BUFFER VARCHAR(20) = NULL
AS 
DECLARE @varKSDateB datetime, @varKSDateE datetime
set @varKSDateB = dbo.DateBeginOfMonth(@varKSdDate)
set @varKSDateE = dbo.DateEndOfMonth(@varKSdDate)

DECLARE @EKR213 INT
SET @EKR213 = (SELECT TOP 1 LINK FROM DICTIONARY_ITEM WHERE CODE = '213')

CREATE TABLE #DOG(LINK_DOG INT)

IF @BUFFER IS NOT NULL
	INSERT INTO #DOG (LINK_DOG)
	SELECT LINK FROM dbo.BUFFER WITH (NOLOCK) WHERE ID = @BUFFER AND SID = SUSER_SID()

DECLARE @EKR211 INT
SET @EKR211 = (SELECT TOP 1 LINK FROM DICTIONARY_ITEM WHERE CODE = '211')

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

--Инвалиды и процент по ним
CREATE TABLE #INV (LINK INT)
INSERT  INTO #INV (LINK)
SELECT
	I.PERS_LINK
FROM	
	dbo.PERS_INVALID I
WHERE
	(YEAR(@varKSDateE) * 100 + MONTH(@varKSDateE)) BETWEEN YEAR(ISNULL(I.DATE_BEGIN,@varKSDateE)) * 100 + MONTH(ISNULL(I.DATE_BEGIN,@varKSDateE))
											AND YEAR(ISNULL(I.DATE_END,@varKSDateE)) * 100 + MONTH(ISNULL(I.DATE_END,@varKSDateE))

--1) РЕЕСТР ДОГОВОРОВ ДЛЯ РАСЧЁТА
CREATE TABLE #DGH(
	PERS_LINK INT,
	FIO VARCHAR(254),
	DATE1 DATETIME,
	DATE2 DATETIME,
	SUMMA NUMERIC(18,2),
	SUMMA_ADD NUMERIC(18,2),
	LINK_PAYS INT,
	CODE_PAYS VARCHAR(10),
	NAME_PAYS VARCHAR(60),
	LINK INT, 
	NUMBER VARCHAR(10),
	[DATE] DATETIME,
	PAYMENT TINYINT,
	VZNOS TINYINT,
	FLAG_NALOG  TINYINT,
	FLAG_ESN TINYINT,
	FLAG_TRAVMA  TINYINT,
	BIRTHDATE DATETIME, 
	SEX TINYINT,
	DATE_BEGIN DATETIME,
	DATE_END DATETIME,
	SUMMA_CALC NUMERIC(18,2),
	LINK_VKR INT,
	NAME_VKR VARCHAR(254),
	LINK_EKR INT,
	CODE_EKR VARCHAR(3),
	LINK_EKR3 INT,
	CODE_EKR3 VARCHAR(3),
	KATEG TINYINT,
	RESIDENT TINYINT
)
INSERT INTO #DGH(
	PERS_LINK,FIO,DATE1,DATE2,SUMMA,SUMMA_ADD,LINK_PAYS,CODE_PAYS,NAME_PAYS,LINK,NUMBER,[DATE],
	PAYMENT,VZNOS,FLAG_NALOG,FLAG_ESN,FLAG_TRAVMA,BIRTHDATE,SEX,DATE_BEGIN,DATE_END,SUMMA_CALC,
	LINK_VKR,NAME_VKR,LINK_EKR,CODE_EKR,LINK_EKR3,CODE_EKR3,KATEG,RESIDENT)
SELECT 
	SRD.PERS_LINK,FIO,DATE1,DATE2,
	[SUMMA] = SRD.SUMMA, 
	[SUMMA_ADD] =  0,
	LINK_PAYS,CODE_PAYS,NAME_PAYS,
	SRD.LINK, SRD.NUMBER,
	SRD.[DATE],PAYMENT,
	VZNOS,FLAG_NALOG,FLAG_ESN,FLAG_TRAVMA,
	BIRTHDATE, SEX,
	[DATE_BEGIN] =(case when date1<@varKSDateB then @varKSDateB else date1 end),
	[DATE_END] =(case when date2>@varKSDateE then @varKSDateE else date2 end),
	[SUMMA_CALC] = SRD.SUMMA *(case when PAYMENT=2 then ((datediff(d,(case when DATE1>@varKSDateB then DATE1 else @varKSDateB end),(case when DATE2<@varKSDateE then DATE2 else @varKSDateE end))+1)/(datediff(d,@varKSDateB,@varKSDateE)+1)) else 1 end),
	[LINK_VKR]=SRD.LINK_KBK,
	[NAME_VKR]= SRD.CODE_KBK,
	[LINK_EKR]= P.link_ekr,
	[CODE_EKR]= DI.CODE,
	[LINK_EKR3]= CASE WHEN P.link_ekr = @EKR211 THEN @EKR213 ELSE P.link_ekr END,
	[CODE_EKR3]= CASE WHEN P.link_ekr = @EKR211 THEN '213' ELSE DI.CODE END,
	KATEG = (CASE WHEN I.LINK IS NULL THEN 1 ELSE 3 END), -- SELECT * FROM SA_PFR_KATEG
	SRD.RESIDENT
FROM 
	dbo.SALARY_REESTR_DGH SRD 
	INNER JOIN dbo.PAYS P ON SRD.LINK_PAYS = P.LINK
	LEFT JOIN dbo.DICTIONARY_ITEM DI ON DI.LINK = P.LINK_EKR
	LEFT JOIN #INV I ON I.LINK = SRD.PERS_LINK
WHERE 
	((date1<=@varKSDateE AND date2>=@varKSDateB  and @varKSdDate is not null ) or @varKSdDate is null )
	AND dep_link = @DEP_LINK
	AND @varKSdDate IS NOT NULL
	AND (@MODE = 1 OR @MODE = 2 AND EXISTS (SELECT * FROM #DOG WHERE LINK_DOG = SRD.LINK))
	

INSERT INTO #DGH(
	PERS_LINK,FIO,DATE1,DATE2,SUMMA,SUMMA_ADD,LINK_PAYS,CODE_PAYS,NAME_PAYS,LINK,NUMBER,[DATE],
	PAYMENT,VZNOS,FLAG_NALOG,FLAG_ESN,FLAG_TRAVMA,BIRTHDATE,SEX,DATE_BEGIN,DATE_END,SUMMA_CALC,
	LINK_VKR,NAME_VKR,LINK_EKR,CODE_EKR,LINK_EKR3,CODE_EKR3,KATEG,RESIDENT)
SELECT 
	SRD.PERS_LINK,FIO,DATE1,DATE2,
	[SUMMA] = 0, 
	[SUMMA_ADD] =  SUM(AD.SUMMA),
	LINK_PAYS,CODE_PAYS,NAME_PAYS,
	SRD.LINK, SRD.NUMBER,
	SRD.[DATE],PAYMENT,
	VZNOS,FLAG_NALOG,FLAG_ESN,FLAG_TRAVMA,
	BIRTHDATE, SEX,
	[DATE_BEGIN] = NULL,
	[DATE_END] =NULL,
	[SUMMA_CALC] = 0,
	[LINK_VKR]= 0,
	[NAME_VKR]= '',
	[LINK_EKR]=0,
	[CODE_EKR]= '',
	[LINK_EKR3]=0,
	[CODE_EKR3]= '',
	KATEG = (CASE WHEN I.LINK IS NULL THEN 1 ELSE 3 END), -- SELECT * FROM SA_PFR_KATEG
	SRD.RESIDENT
FROM 
	dbo.SALARY_REESTR_DGH SRD 
	INNER JOIN dbo.SD_NDFL_ADDITION_DOHOD  AD ON AD.DGH_LINK = SRD.LINK AND AD.PERS_TYPE = 2 
	LEFT JOIN #INV I ON I.LINK = SRD.PERS_LINK	
WHERE 
	dep_link = @DEP_LINK
	AND @varKSdDate IS NULL
	AND (@MODE = 1 OR @MODE = 2 AND EXISTS (SELECT * FROM #DOG WHERE LINK_DOG = SRD.LINK))
GROUP BY
	SRD.PERS_LINK,FIO,DATE1,DATE2,
	LINK_PAYS,CODE_PAYS,NAME_PAYS,
	SRD.LINK, SRD.NUMBER,
	SRD.[DATE],PAYMENT,
	VZNOS,FLAG_NALOG,FLAG_ESN,FLAG_TRAVMA,
	BIRTHDATE, SEX, I.LINK, SRD.RESIDENT

IF @MODE = 1 BEGIN
	SELECT
		[NAME_DOG] = '№ '+rtrim(NUMBER)+' от '+convert(varchar(20),DATE,104),
		*
	FROM #DGH ORDER BY FIO
	RETURN 0
END
	
--2) СПИСОК ВИДОВ ВЗНОСОВ НА ДАННЫЙ ПЕРИОД	
CREATE TABLE #PAYS3	(LINK INT)

INSERT INTO #PAYS3 (LINK)
SELECT 
	T.REF_PAY
FROM
	dbo.MINROT M 
	INNER JOIN dbo.DICTIONARY_MROT_TABLE4 T ON T.LINK_MINROT = M.LINK
WHERE
	M.LINK = ( SELECT TOP 1 M2.LINK FROM dbo.MINROT M2 WHERE M2.PERIOD <= @varKSDateE ORDER BY M2.PERIOD DESC )

--Травматизм
INSERT INTO #PAYS3 (LINK)
SELECT LINK FROM dbo.PAYS P
WHERE 
	[OBJECT] = 3 AND WAY_CALC = 5
	AND NOT EXISTS (SELECT * FROM #PAYS3 PP WHERE PP.LINK = P.LINK)

DECLARE @PERC_TRAVM_IVALID NUMERIC(18,2)
SET @PERC_TRAVM_IVALID = ISNULL((SELECT TOP 1 MP.summa FROM dbo.MINROT_PAYS MP WHERE LINK_MINROT = (SELECT TOP 1 LINK FROM dbo.MINROT WHERE PERIOD<=@varKSDateE ORDER BY PERIOD DESC)),0)

--Базовые начисления
CREATE TABLE #TR(LINK_TAX INT, LINK_PAYS INT)
INSERT INTO #TR(LINK_TAX, LINK_PAYS)
SELECT DISTINCT R.LINK_TAX, R.LINK_PAYS
FROM
	dbo.TAX_REF R
	INNER JOIN dbo.PAYS P ON P.LINK = R.LINK_TAX
WHERE	
	(P.OBJECT = 2) 
	or 
	(P.OBJECT = 3 AND EXISTS (SELECT * FROM #PAYS3 P3 WHERE P3.LINK = P.LINK))	

--
DECLARE @BY DATETIME
SET @BY = dbo.DateBeginOfYear(@varKSDateB)

CREATE TABLE #DICT_VICHET (LINK_DOG INT, LINK_DED INT, PREDEL NUMERIC(18,2), SUMMA NUMERIC(18,2), DATE1 DATETIME, DATE2 DATETIME, MONS INT)

INSERT INTO #DICT_VICHET (LINK_DOG, LINK_DED, PREDEL, SUMMA, DATE1, DATE2)
SELECT 
	LINK_DGH, DED_LINK, SD.PREDEL, SD.SUMMA, 
	
	DATE1 = CASE WHEN (CASE WHEN D.DATE1 < SRD.DATE1 THEN SRD.DATE1 ELSE D.DATE1 END) <= @BY
				THEN @BY
				ELSE (CASE WHEN D.DATE1 < SRD.DATE1 THEN SRD.DATE1 ELSE D.DATE1 END)
			END, 
	
	DATE2 = CASE WHEN (CASE WHEN D.DATE2 > SRD.DATE2 THEN SRD.DATE2 ELSE D.DATE2 END) > @varKSDateE
				THEN @varKSDateE
				ELSE (CASE WHEN D.DATE2 > SRD.DATE2 THEN SRD.DATE2 ELSE D.DATE2 END)
			END
FROM
	#DOG A 
	INNER JOIN dbo.SALARY_REESTR_DGH SRD ON SRD.LINK = A.LINK_DOG
	INNER JOIN dbo.EMPL_DED D ON D.LINK_DGH = A.LINK_DOG
	INNER JOIN dbo.Salary_deductions(@varKSDateE) SD ON SD.REF_PAY = D.DED_LINK
WHERE
	(CASE WHEN D.DATE1 < SRD.DATE1 THEN SRD.DATE1 ELSE D.DATE1 END)<=@varKSDateE 
	AND 
	(CASE WHEN D.DATE2 > SRD.DATE2 THEN SRD.DATE2 ELSE D.DATE2 END)>=@varKSDateB

UPDATE #DICT_VICHET
SET MONS = MONTH(DATE2) - MONTH(DATE1) + 1

---
CREATE TABLE #TAX (	
	ID INT IDENTITY(1,1), ORDERS INT,
	LINK_DOG INT, SUMMA_BASE NUMERIC(18,2), PERS_LINK INT, LINK INT, CODE VARCHAR(10), 
	NAME VARCHAR(254), WAY_CALC TINYINT, [PERCENT] NUMERIC(18,4), [OBJECT] INT,
	BASE_YEAR NUMERIC(18,2), SUMMA_YEAR NUMERIC(18,2), SUMMA_OLD NUMERIC(18,2), SUMMA NUMERIC(18,2), LINK_SFIN INT)

INSERT INTO #TAX (LINK_DOG, SUMMA_BASE, PERS_LINK, LINK, CODE, NAME, WAY_CALC, [PERCENT], [OBJECT])	
SELECT
	LINK_DOG = D.LINK,
	SUMMA_BASE = ISNULL(SUMMA,0) + ISNULL(SUMMA_ADD,0),
	PERS_LINK = D.PERS_LINK,
	P.LINK,
	P.CODE,
	P.NAME,
	P.WAY_CALC,
	[percent] =	(CASE WHEN P.WAY_CALC NOT IN (6,7,8,9) THEN 
					(CASE WHEN 
							WAY_CALC = 5 --ФСС ТРАВМАТИЗМ
							AND 
							(CASE WHEN ISNULL(D.KATEG,0) > (ISNULL(F.ENVD,0) + 1) THEN ISNULL(D.KATEG,0) ELSE (ISNULL(F.ENVD,0) + 1) END) = 3 
						THEN
							@PERC_TRAVM_IVALID
					ELSE 
						ISNULL((	SELECT TOP 1 DR.[percent] 
							from dbo.dictionary_range DR
							where 
								(	
									DR.TARIF = (CASE WHEN ISNULL(D.KATEG,0) > (ISNULL(F.ENVD,0) + 1) THEN ISNULL(D.KATEG,0) ELSE (ISNULL(F.ENVD,0) + 1) END)
									OR --Для подоходного налога по общему тарифу всегда
									DR.TARIF = 1 
									AND 
									EXISTS (SELECT * FROM dbo.PAYS P1 WHERE DR.LINK_PAYS = P1.LINK AND P1.[OBJECT] = 2 AND P1.WAY_CALC IN (4,5,6)) 
								)
								AND DR.LINK_PAYS = P.LINK and [DATE]<=@varKSDateE order by DR.[DATE] desc, DR.PREDEL asc
						),0)  
									
					END)	
			ELSE
				ISNULL((SELECT TOP 1 (CASE WHEN 
								(CASE 
									WHEN YEAR(BIRTHDATE)<=(CASE WHEN D.SEX = 1 THEN 1952 ELSE 1956 END) THEN 1 
									WHEN (YEAR(BIRTHDATE)>(CASE WHEN D.SEX = 1 THEN 1952 ELSE 1956 END) AND YEAR(BIRTHDATE)<1967) THEN 2 
									ELSE 3 
								END) = 1 
								THEN PERCENT1 
							WHEN 
								(CASE 
									WHEN YEAR(BIRTHDATE)<=(CASE WHEN D.SEX = 1 THEN 1952 ELSE 1956 END) THEN 1 
									WHEN (YEAR(BIRTHDATE)>(CASE WHEN D.SEX = 1 THEN 1952 ELSE 1956 END) AND YEAR(BIRTHDATE)<1967) THEN 2 
									ELSE 3 
								END) = 2  
								THEN PERCENT2 
							ELSE PERCENT3 END) 
					FROM 
						DBO.DICTIONARY_RANGE_PF
					WHERE 
							TARIF = (CASE WHEN ISNULL(D.KATEG,0) > (ISNULL(F.ENVD,0) + 1) THEN ISNULL(D.KATEG,0) ELSE (ISNULL(F.ENVD,0) + 1) END) 
							AND SpecO IS NULL
							AND LINK_PAYS = P.LINK 
							AND DATE<=@varKSDateE 
					ORDER BY DATE DESC, PREDEL ASC),0)  
			 END),
	P.[OBJECT]
FROM 
	#DGH D
	INNER JOIN dbo.SAL_SFIN F ON F.LINK = D.LINK_VKR
	INNER JOIN #TR R ON R.LINK_PAYS = D.LINK_PAYS
	INNER JOIN dbo.PAYS P ON P.LINK = R.LINK_TAX
WHERE
	(
		P.[OBJECT] = 2 AND D.FLAG_NALOG = 1 AND (D.RESIDENT = 1 AND P.WAY_CALC = 4 OR D.RESIDENT <> 1 AND P.WAY_CALC = 5)
		OR 
		P.[OBJECT] = 3 
				AND (P.WAY_CALC = 5 AND D.FLAG_TRAVMA = 1 OR P.WAY_CALC = 2 AND D.VZNOS = 1 OR P.WAY_CALC IN (1,3,4,6,7,8,9) AND D.FLAG_ESN = 1)
				AND EXISTS (SELECT * FROM #PAYS3 P3 WHERE P3.LINK = P.LINK)
	)
ORDER BY
	P.OBJECT, D.LINK	

--- Прочие удержания по договорникам
INSERT INTO #TAX (LINK_DOG, SUMMA_BASE, PERS_LINK, LINK, CODE, NAME, WAY_CALC, [PERCENT], [OBJECT], LINK_SFIN)	
SELECT
	LINK_DOG = D.LINK,
	SUMMA_BASE = 
			CASE WHEN P.WAY_CALC IN (2,3) THEN
				ISNULL(D.SUMMA,0) * ISNULL( (SELECT MAX(1) FROM dbo.TAX_REF G WHERE G.LINK_TAX = T.LINK_TAX AND G.LINK_PAYS = D.LINK_PAYS) ,0)
			ELSE
				0
			END,
	PERS_LINK = D.PERS_LINK,
	P.LINK,
	P.CODE,
	P.NAME,
	P.WAY_CALC,	
	[percent] =	T.SUMMA,
	P.[OBJECT],
	(CASE WHEN ISNULL(T.LINK_VKR,0) = 0 THEN D.LINK_VKR ELSE T.LINK_VKR END)
FROM 
	#DGH D
	INNER JOIN dbo.SD_EMPL_TAX T ON T.LINK_DGH = D.LINK
	INNER JOIN dbo.PAYS P ON P.LINK = T.LINK_TAX
WHERE
	P.[OBJECT] = 2
ORDER BY
	P.CODE, D.LINK

--3) РАНЕЕ НАЧИСЛЕННЫЕ ДОХОДЫ,ВЗНОСЫ И НАЛОГИ
CREATE TABLE #OLD (MON INT, PERS_LINK INT, LINK_DOG INT, LINK INT, SUMMA_D NUMERIC(18,2), SUMMA_N NUMERIC(18,2))

INSERT INTO #OLD (MON, PERS_LINK, LINK_DOG, LINK, SUMMA_D, SUMMA_N)
SELECT 
	MONTH(D.[DATE]),
	T2.PERS_LINK,
	D.LINK,
	T2.LINK_PAY,
	SUMMA_D = SUM(T2.SUMMA_BASE),
	SUMMA_N = SUM(T2.SUMMA)
FROM
	dbo.SDOC D
	INNER JOIN dbo.SDOC_DGH_TABLE T2 ON T2.LINK_UP = D.LINK 
	INNER JOIN dbo.PAYS P ON P.LINK = T2.LINK_PAY
WHERE 
	D.LINK_DEP = @DEP_LINK
	AND
	D.FLAG_JC = 1
	AND
	T2.[OBJECT] = 2	
	AND
	P.[OBJECT] = 2 AND P.WAY_CALC IN (4,5,6)
	AND
	YEAR(D.[DATE]) = YEAR(@varKSDateE)
	AND
	MONTH(D.[DATE]) <= MONTH(@varKSDateE)
GROUP BY
	MONTH(D.[DATE]),
	T2.PERS_LINK,
	D.LINK,
	T2.LINK_PAY
	
INSERT INTO #OLD (MON, PERS_LINK, LINK_DOG, LINK, SUMMA_D, SUMMA_N)
SELECT 
	MONTH(D.[DATE]),
	T2.PERS_LINK,
	D.LINK,
	T2.LINK_PAY,
	SUMMA_D = SUM(T2.SUMMA_BASE),
	SUMMA_N = SUM(T2.SUMMA)
FROM
	dbo.SDOC D
	INNER JOIN dbo.SDOC_DGH_TABLE T2 ON T2.LINK_UP = D.LINK 
	INNER JOIN dbo.PAYS P ON P.LINK = T2.LINK_PAY
WHERE 
	D.LINK_DEP = @DEP_LINK
	AND
	D.FLAG_JC = 1
	AND
	T2.[OBJECT] = 3	
	AND
	P.[OBJECT] = 3 AND EXISTS (SELECT * FROM #PAYS3 P3 WHERE P3.LINK = P.LINK)
	AND
	YEAR(D.[DATE]) = YEAR(@varKSDateE)
	AND
	MONTH(D.[DATE]) <= MONTH(@varKSDateE)
GROUP BY
	MONTH(D.[DATE]),
	T2.PERS_LINK,
	D.LINK,
	T2.LINK_PAY	

--4) РАСЧЁТ НАЛОГОВ
--Определение базы с начала года	
UPDATE T SET 
	T.BASE_YEAR =	(
					ISNULL((SELECT SUM(O.SUMMA_D) FROM #OLD O WHERE O.PERS_LINK = T.PERS_LINK AND O.LINK = T.LINK),0)
					+ ISNULL((SELECT SUM(N.SUMMA_BASE) FROM #TAX N WHERE N.PERS_LINK = T.PERS_LINK AND N.LINK = T.LINK),0)
					) 
					* 
					(CASE WHEN ISNULL((SELECT SUM(N.SUMMA_BASE) FROM #TAX N WHERE N.PERS_LINK = T.PERS_LINK AND N.LINK = T.LINK),0) > 0
						THEN T.SUMMA_BASE / ISNULL((SELECT SUM(N.SUMMA_BASE) FROM #TAX N WHERE N.PERS_LINK = T.PERS_LINK AND N.LINK = T.LINK),0)
						ELSE 0
					END)	
	,T.SUMMA_OLD = ISNULL((SELECT SUM(O.SUMMA_N) FROM #OLD O WHERE O.PERS_LINK = T.PERS_LINK AND O.LINK = T.LINK),0)
					* 
					(CASE WHEN ISNULL((SELECT SUM(N.SUMMA_BASE) FROM #TAX N WHERE N.PERS_LINK = T.PERS_LINK AND N.LINK = T.LINK),0) > 0
						THEN T.SUMMA_BASE / ISNULL((SELECT SUM(N.SUMMA_BASE) FROM #TAX N WHERE N.PERS_LINK = T.PERS_LINK AND N.LINK = T.LINK),0)
						ELSE 0
					END)	
FROM 
	#TAX T
WHERE
	T.[OBJECT] = 2 AND T.WAY_CALC IN (4,5,6)
	OR
	T.[OBJECT] = 3

--
CREATE TABLE #DOXOD (LINK_PERS INT, MON INT, SUMMA NUMERIC(18,2), SUMMA2 NUMERIC(18,2))
INSERT INTO #DOXOD (LINK_PERS, MON, SUMMA, SUMMA2)
SELECT PERS_LINK, MON, SUM(SUMMA_D), 0
FROM
	(
	SELECT PERS_LINK, MON, SUMMA_D FROM #OLD O INNER JOIN dbo.PAYS P ON P.LINK = O.LINK WHERE P.[OBJECT] = 2 AND P.WAY_CALC IN (4,5,6)
	UNION ALL	
	SELECT PERS_LINK, MON = MONTH(@varKSdDate), SUMMA_BASE FROM #TAX T INNER JOIN dbo.PAYS P ON P.LINK = T.LINK WHERE P.[OBJECT] = 2 AND P.WAY_CALC IN (4,5,6)
	) T
GROUP BY PERS_LINK, MON

--
UPDATE D
SET SUMMA2 = (SELECT SUM(SUMMA) FROM #DOXOD D2 WHERE D2.LINK_PERS = D.LINK_PERS AND D2.MON <= D.MON)
FROM #DOXOD D

--
DELETE FROM [dbo].[SAL_DED_MONTH]
WHERE EXISTS (SELECT * FROM #DGH H WHERE H.LINK = [dbo].[SAL_DED_MONTH].[LINK_DGH])

--
INSERT INTO [dbo].[SAL_DED_MONTH] (REF_DED, SUMMA, DATE_DED, LINK_VKR, LINK_EKR, [TYPE], KOEF_VKR, KOL, LINK_DGH)
SELECT 
	REF_DED = V.LINK_DED, 
	V.SUMMA,
	DATE_DED = M.DATE_BEGIN,
	LINK_VKR = H.LINK_VKR,
	LINK_EKR = H.LINK_EKR,
	[TYPE] = 1,
	KOEF_VKR = 1,
	KOL = 1,
	LINK_DGH = H.LINK
FROM
	dbo.MONTHS_EX (@BY, @varKSDateE) M
	INNER JOIN #TAX T ON 1=1
	INNER JOIN #DGH H ON H.LINK = T.LINK_DOG
	INNER JOIN #DICT_VICHET V ON T.LINK_DOG = V.LINK_DOG
	LEFT JOIN #DOXOD D ON D.LINK_PERS = T.PERS_LINK AND D.MON = M.M
WHERE
	T.[OBJECT] = 2 AND T.WAY_CALC = 4
	AND
	M.M BETWEEN MONTH(V.DATE1) AND MONTH(V.DATE2)
	AND
	(CASE WHEN ISNULL(D.SUMMA2,0) <= ISNULL(V.PREDEL,0) OR ISNULL(V.PREDEL,0) = 0 THEN ISNULL(V.SUMMA,0) ELSE 0 END) > 0

--определение вычетов с начала года
CREATE TABLE #SUM_VYCH (LINK_DOG INT, LINK INT, SUMMA_YEAR NUMERIC(18,2), SUMMA_M NUMERIC(18,2))
INSERT INTO #SUM_VYCH (LINK_DOG, LINK, SUMMA_YEAR, SUMMA_M)
SELECT 
	T.LINK_DOG,
	T.LINK,
	SUM_VICH = (SELECT SUM(SUMMA) FROM [dbo].[SAL_DED_MONTH] SDM WHERE SDM.LINK_DGH = T.LINK_DOG AND YEAR(DATE_DED) =YEAR(@varKSDateE) AND MONTH(DATE_DED) <= MONTH(@varKSDateE)),
	SUMMA_M = (SELECT SUM(SUMMA) FROM [dbo].[SAL_DED_MONTH] SDM WHERE SDM.LINK_DGH = T.LINK_DOG AND YEAR(DATE_DED) =YEAR(@varKSDateE) AND MONTH(DATE_DED) = MONTH(@varKSDateE))
FROM 
	#TAX T
WHERE
	T.[OBJECT] = 2 AND T.WAY_CALC = 4
GROUP BY
	T.LINK_DOG, T.LINK

--Определенеи налога с начала года
UPDATE T SET 
	T.SUMMA_YEAR = 
		CASE WHEN P.OBJECT = 2 THEN
			ROUND((T.BASE_YEAR - ISNULL(V.SUMMA_YEAR,0)) * ISNULL(T.[PERCENT],0) / 100,0)
		ELSE
			T.BASE_YEAR * ISNULL(T.[PERCENT],0) / 100
		END
FROM 
	#TAX T
	INNER JOIN dbo.PAYS P ON P.LINK = T.LINK
	LEFT JOIN #SUM_VYCH V ON V.LINK_DOG = T.LINK_DOG

--Определенеи налога за месяц
UPDATE T SET 
	T.SUMMA = T.SUMMA_YEAR - T.SUMMA_OLD
FROM 
	#TAX T

--ОКРУГЛЯЕМ МЕСЯЧНЫЙ НАЛОГ ДО КОПЕЕК
CREATE TABLE #TAX1 (PERS_LINK INT,LINK INT,SUMMA NUMERIC(18,2))
INSERT INTO #TAX1 (PERS_LINK,LINK,SUMMA)
SELECT T.PERS_LINK, T.LINK, SUM(T.SUMMA) 
FROM #TAX T INNER JOIN dbo.PAYS P ON T.LINK = P.LINK
WHERE P.[OBJECT] = 2 AND P.WAY_CALC IN (4,5,6)
GROUP BY T.PERS_LINK, T.LINK

--Округление НДФЛ за месяц
UPDATE T SET 
	T.SUMMA = CONVERT(NUMERIC(18,0),T.SUMMA)
FROM 
	#TAX T
WHERE	
	T.[OBJECT] = 2 AND T.WAY_CALC IN (4,5,6)
	
--
UPDATE T SET 
	T.SUMMA = 
		CASE WHEN T.WAY_CALC = 1
			THEN T.[PERCENT] --T.[PERCENT] СОДЕРЖИТ СУММУ
			ELSE SUMMA_BASE * T.[PERCENT] / 100 --T.[PERCENT] СОДЕРЖИТ ПРОЦЕНТ
		END,
	BASE_YEAR = 0,
	SUMMA_YEAR = 0,
	SUMMA_OLD = 0		
FROM 
	#TAX T
WHERE
	T.[OBJECT] = 2 AND T.WAY_CALC IN (1,2,3)	


CREATE TABLE #TAX2 (PERS_LINK INT,LINK_DOG INT,LINK INT,SUMMA NUMERIC(18,2))
INSERT INTO #TAX2 (PERS_LINK, LINK_DOG, LINK, SUMMA)
SELECT PERS_LINK, MAX(LINK_DOG), T.LINK, SUM(SUMMA) 
FROM #TAX T INNER JOIN dbo.PAYS P ON T.LINK = P.LINK
WHERE P.[OBJECT] = 2 AND P.WAY_CALC IN (4,5,6)
GROUP BY T.PERS_LINK, T.LINK

UPDATE T SET 
	T.SUMMA = CONVERT(NUMERIC(18,0), ISNULL(T.SUMMA,0) + ISNULL((SELECT T1.SUMMA FROM #TAX1 T1 WHERE T2.PERS_LINK = T1.PERS_LINK AND T2.LINK = T1.LINK),0) - ISNULL(T2.SUMMA,0))
FROM 
	#TAX T
	INNER JOIN #TAX2 T2 ON T.LINK_DOG = T2.LINK_DOG AND T.LINK = T2.LINK
	
DECLARE @Cur1 CURSOR
DECLARE @ID INT, @OBJECT INT, @OBJECT2 INT, @NEXT INT
SELECT @NEXT = 0, @OBJECT2 = 0
SET @Cur1 = CURSOR FORWARD_ONLY

FOR SELECT ID, OBJECT FROM #TAX ORDER BY ID

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @ID, @OBJECT
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN

		IF @OBJECT <> @OBJECT2 BEGIN
			SET @NEXT = 1
			SET @OBJECT2 = @OBJECT
		END			
		ELSE
			SET @NEXT = @NEXT + 1
		
		UPDATE #TAX SET ORDERS = @NEXT WHERE ID = @ID

	END

	FETCH NEXT FROM @Cur1 INTO @ID, @OBJECT
END

CLOSE @Cur1
DEALLOCATE @Cur1


SELECT
	T.ORDERS,
	D.LINK, D.PERS_LINK, D.FIO, D.LINK_VKR, D.NAME_VKR, D.LINK_EKR, D.CODE_EKR,
	LINK_PAY = P.LINK, CODE_PAY = P.CODE, NAME_PAY = P.NAME, P.[OBJECT],
	T.BASE_YEAR, T.SUMMA_BASE, 
	V_SUM_Y = ISNULL(V.SUMMA_YEAR,0), V_SUM_M = ISNULL(V.SUMMA_M,0),
	T.[PERCENT], T.SUMMA_YEAR, T.SUMMA_OLD, T.SUMMA
FROM
	#DGH D 
	INNER JOIN #TAX T ON D.LINK = T.LINK_DOG
	INNER JOIN dbo.PAYS P ON P.LINK = T.LINK
	LEFT JOIN #SUM_VYCH V ON V.LINK = T.LINK AND V.LINK_DOG = T.LINK_DOG
ORDER BY
	P.[OBJECT], D.FIO	

RETURN 0
	


GO


GRANT EXECUTE ON dbo.[SD_NUO_DGH_FILL] TO PUBLIC

GO

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

GO

/*
© Кейсистемс (Keysystems), 2006
27.01.06 Бочкарев Е.Ю. 
Таблица остатков для заполнения документа недостающими строками 
*/

CREATE  PROCEDURE [dbo].FB_ADD_REST 
		@varKSintLink 	int,
		@varKSdDate 	datetime,
		@varKSintFYear 	int,
		@varKSintPer_num 	int,
		@varKSintChange	int,
		@varKSintDepAcc int,
		@varKSintRBSAcc	int,
		@varKScObjCode	varchar(100)

AS
BEGIN
	IF @varKScObjCode = 'FINANS_LIMIT' OR @varKScObjCode = 'FINANS_CC_LIMIT'
		SELECT
			F.DEP_ACC, F.VKR, F.EKR, F.DOP_CL, F.REG, 
			F.P1, F.P2, F.P3, F.P4, F.P5, F.P6, F.P7, F.P8, F.P9, F.P10, F.P11, F.P12,
			ISNULL (F.Y2, 0) AS Y2, ISNULL (F.Y3, 0) AS Y3,
			[VKR_CODE] 	= VKR.CODE,
			[VKR_NAME] 	= VKR.NAME,
			[EKR_CODE] 	= EKR.CODE,
			[EKR_NAME] 	= EKR.NAME,
			[DOP_CL_CODE]	= DCL.CODE,
			[DOP_CL_NAME] 	= DCL.NAME,
			[REG_CODE]	=	REG.CODE,
			[REG_NAME]	=	REG.CODE,
			[KBK_ADM] 	= VKR.LINK_ADM
		FROM dbo.FB_RESTRICT_LIMIT
				(
				@varKSintFYear,
				@varKSdDate,
				@varKSintLink,
				@varKSintChange,
				@varKSintPer_num,
				NULL,
				NULL,
				NULL,
				NULL,
				@varKSintDepAcc,
				@varKSintRBSAcc
				) F
		LEFT OUTER JOIN dbo.KL_KBK VKR ON VKR.LINK = F.VKR
		LEFT OUTER JOIN dbo.DICTIONARY_ITEM EKR ON EKR.LINK = F.EKR
		LEFT OUTER JOIN dbo.DOP_CLASSIF DCL ON DCL.LINK = F.DOP_CL
		LEFT OUTER JOIN dbo.KL_REG REG ON REG.LINK = F.REG
		ORDER BY VKR_CODE, EKR_CODE, DOP_CL_CODE

	IF @varKScObjCode = 'FINANS_ASSIGN' OR @varKScObjCode = 'FINANS_CC_ASSIGN'
		SELECT @varKSintDepAcc as DEP_ACC, F.VKR, F.EKR, F.DOP_CL, F.REG, 
			F.P1, F.P2, F.P3, F.P4, F.P5, F.P6, F.P7, F.P8, F.P9, F.P10, F.P11, F.P12,
			ISNULL (F.Y2, 0) AS Y2, ISNULL (F.Y3, 0) AS Y3,
			[VKR_CODE] 	= VKR.CODE,
			[VKR_NAME] 	= VKR.NAME,
			[EKR_CODE] 	= EKR.CODE,
			[EKR_NAME] 	= EKR.NAME,
			[DOP_CL_CODE]	= DCL.CODE,
			[DOP_CL_NAME] 	= DCL.NAME,
			[REG_CODE]	=	REG.CODE,
			[REG_NAME]	=	REG.CODE,
			[KBK_ADM] 	= VKR.LINK_ADM
		FROM dbo.FB_RESTRICT_ASSIGN
				(
				@varKSintFYear,
				@varKSdDate,
				@varKSintLink,
				@varKSintChange,
				NULL,
				NULL,
				NULL,
				NULL,
				@varKSintRBSAcc
				) F
		LEFT OUTER JOIN dbo.KL_KBK VKR ON VKR.LINK = F.VKR
		LEFT OUTER JOIN dbo.DICTIONARY_ITEM EKR ON EKR.LINK = F.EKR
		LEFT OUTER JOIN dbo.DOP_CLASSIF DCL ON DCL.LINK = F.DOP_CL
		LEFT OUTER JOIN dbo.KL_REG REG ON REG.LINK = F.REG
		ORDER BY VKR_CODE, EKR_CODE, DOP_CL_CODE

	IF @varKScObjCode = 'FINANS_LIMIT_SVOD' OR @varKScObjCode = 'FINANS_CC_LIMIT_SVOD'
		SELECT F.DEP_ACC, F.VKR, F.EKR, F.DOP_CL, F.REG,  
			F.P1, F.P2, F.P3, F.P4, F.P5, F.P6, F.P7, F.P8, F.P9, F.P10, F.P11, F.P12,
			ISNULL (F.Y2, 0) AS Y2, ISNULL (F.Y3, 0) AS Y3,
			[VKR_CODE] 	= VKR.CODE,
			[VKR_NAME] 	= VKR.NAME,
			[EKR_CODE] 	= EKR.CODE,
			[EKR_NAME] 	= EKR.NAME,
			[DOP_CL_CODE]	= DCL.CODE,
			[DOP_CL_NAME] 	= DCL.NAME,
			[REG_CODE]	=	REG.CODE,
			[REG_NAME]	=	REG.CODE,
			[KBK_ADM] 	= VKR.LINK_ADM
		FROM dbo.FB_RESTRICT_LIMIT_SVOD
				(
				@varKSintFYear,
				@varKSdDate,
				@varKSintLink,
				@varKSintChange,
				@varKSintPer_num,
				NULL,
				NULL,
				NULL,
				NULL,
				@varKSintRBSAcc
				) F
		LEFT OUTER JOIN dbo.KL_KBK VKR ON VKR.LINK = F.VKR
		LEFT OUTER JOIN dbo.DICTIONARY_ITEM EKR ON EKR.LINK = F.EKR
		LEFT OUTER JOIN dbo.DOP_CLASSIF DCL ON DCL.LINK = F.DOP_CL
		LEFT OUTER JOIN dbo.KL_REG REG ON REG.LINK = F.REG
		ORDER BY VKR_CODE, EKR_CODE, DOP_CL_CODE

END

GO

GRANT EXECUTE ON dbo.[FB_ADD_REST] TO PUBLIC

GO

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

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

GO

CREATE PROCEDURE dbo.BB_EXPORT_PP
	@cBuffId	varchar(30) = '',
	@cFormat	varchar(30) = ''

AS

DECLARE @iLinkedKBK	tinyint,
	@iGroupKBK	tinyint,
	
		@DATE_MAX	DATETIME,
		@COUNT_DOC	INT,
		@SUM_TOTAL	NUMERIC (28,4),
		@iCity int,
		@iCityP int
		

select @iCity = BANK_CITY from dbo.DOCUMENTS_PAY_OPTIONS
select @iCityP = BANK_CITY from dbo.DOCUMENTS_PAY_OPTIONS
	
set @iLinkedKBK = isnull(dbo.sa_get_option_by_code('NASTR_PAY_LINKED_KBK'),0)
set @iGroupKBK = isnull(dbo.sa_get_option_by_code('NASTR_PAY_GROUP_KBK'),0)

if left(@cFormat,2) = 'TX'
begin 
	DECLARE @iDepLink	int
	set @iDepLink = isnull(dbo.BK_GetDepZB(),dbo.GetOwnDepLink())

	-- Таблица 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 	= BUDG,
			NAME_UBP	= left(rtrim(D.prefix) + rtrim(D.FULL_NAME) + case when charindex('(',D.prefix,0) > 0 then ')' else '' end,2000),
			0 as link,
			0 as link_up,
			-- Поля для приема выписки
			KOD_TOFK  = '0000',
			NAME_TOFK = space(2000)
			
	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,
			-- Поля для приема выписки
			BUDG_LEVEL  = '00',
			KOD_UBP 	= '00000',
			NAME_UBP	= space(2000)
	from dbo.DEPARTMENTS D
	inner join dbo.TREASURY TOFK on D.TOFK_LINK = TOFK.LINK
	where D.LINK = @iDepLink

	-- Таблица 4 (PP)
	IF exists(select * from dbo.DEPARTMENTS where LINK = @iDepLink AND BUH_TYPE < 4)
		SELECT  LINK 	= 0,
			LINK_UP	= 0,
			LS = space(11),
			[DATE]	= MAX(G.DATE),
			GUID_OTCH = space(36),
			KOD_DOC = '  ',
			VID_OTCH = '1',
			KOL		= COUNT(*),
			SUM_TOTAL	= SUM(G.SUMMA)
		FROM dbo.G_PROV G
		inner join dbo.BufferGetTableByID(@cBuffId) B on B.LINK = G.LINK
	else
		SELECT  LINK 	= 0,
			LINK_UP	= 0,
			LS = space(11),
			[DATE]	= '',
			GUID_OTCH = space(36),
			KOD_DOC = '  ',
			VID_OTCH = '1',
			KOL		= 0,
			SUM_TOTAL	= 0
		where 1>2
	
--	IF OBJECT_ID ('TEMPDB..#SMETA_EXPORT_PP') IS NOT NULL
--			EXECUTE ('DROP TABLE #SMETA_EXPORT_PP')

/*	SELECT 
		@DATE_MAX	=	MAX(G.DATE),
		@COUNT_DOC	=	COUNT(*),
		@SUM_TOTAL	=	SUM(G.SUMMA)
	FROM dbo.G_PROV G
	inner join dbo.BufferGetTableByID(@cBuffId) B on B.LINK = G.LINK
*/
/*
	SELECT  LINK 	= 0,
			LINK_UP	= 0,
			LS = space(11),
			[DATE]	= MAX(G.DATE),
			GUID_OTCH = space(36),
			KOD_DOC = '  ',
			KOL		= COUNT(*),
			SUM_TOTAL	= SUM(G.SUMMA)
--	INTO #SMETA_EXPORT_PP		
	FROM dbo.G_PROV G
	inner join dbo.BufferGetTableByID(@cBuffId) B on B.LINK = G.LINK
*/
/*	INNER JOIN dbo.DEPARTMENTS DEP ON (DEP.LINK = G.DEP
		AND DEP.BUH_TYPE < 4)
*/

/*
	IF @cFormat > 'TXPP120101'
		SELECT T1.*
		FROM #SMETA_EXPORT_PP	T1
		INNER JOIN dbo.DEPARTMENTS DEP ON (DEP.LINK = T.DEP
			AND DEP.BUH_TYPE < 4)
	ELSE
			SELECT T1.*
			FROM #SMETA_EXPORT_PP	T1

	DROP TABLE #SMETA_EXPORT_PP
*/
/*	END		
	ELSE
		SELECT  LINK 	= 0,
				LINK_UP	= 0,
				LS = space(11),
				[DATE]	= MAX(G.DATE),
				GUID_OTCH = space(36),
				KOD_DOC = '  ',
				KOL		= COUNT(*),
				SUM_TOTAL	= SUM(G.SUMMA)
		FROM dbo.G_PROV G
		inner join dbo.BufferGetTableByID(@cBuffId) B on B.LINK = G.LINK
*/
		-- Разница в наименовании полей --
		IF OBJECT_ID ('TEMPDB..#SMETA_EXPORT_PPT') IS NOT NULL
				EXECUTE ('DROP TABLE #SMETA_EXPORT_PPT')

		SELECT  LINK 		 = PP.LINK,
				LINK_UP		 = PP.LINK,
				NOM_PP		 = PP.NUMBER,
				DATE_PP		 = PP.DATE,
				SUM_PP		 = PP.SUMMA,
				VID_PL		 = CASE	PP.KIND WHEN 'почтой'     THEN '1'
											 WHEN 'телеграфом' THEN '2'
											 WHEN 'электронно' THEN '3'
											 WHEN 'срочно' 	   THEN '4'
											 ELSE '0' END,
				VID_OPER	= '01', 
				INN_PAY		= PP.S_INN,
				KPP_PAY		= PP.S_KPP,
				--CNAME_PAY	= PP.S_FNAME,
				CNAME_PAY	= dbo.BB_DEP_NAME_FOR_SHABLON(isnull(APO.SHABLON_D,APOD.SHABLON_D), default, PP.S_ACC_LINK),
				BS_PAY		= case PP.S_ACC_TYPE when 1 then PP.S_ACC_NUM else PP.S_SCH_K end,
				BIC_PAY		= PP.S_BIK,
				NAME_BIC_PAY = PP.S_BANK + case isnull(@iCity,0) when 1 then ' ' + isnull(PP.S_BANK_CITY,'') else '' end,
				BS_KS_PAY	= PP.S_SCH_B,
				INN_RCP		= PP.D_INN,
				KPP_RCP		= PP.D_KPP,
				NAME_RCP	= dbo.BB_DEP_NAME_FOR_SHABLON(CASE WHEN PPA.DOH_CODE is not null or PPA.OKATO is not null or P_REASON is not null or PPA.PERIOD is not null or TREBNUM is not null or TREBDATE is not null or P_TYPE is not null or STATUS is not null THEN isnull

(APO.SHABLON_N, APOD.SHABLON_N) else isnull(APO.SHABLON_S, APOD.SHABLON_S) end, default, PP.D_ACC_LINK),
		
				--NAME_RCP	= PP.D_FNAME,
				BS_RCP		= replace(isnull(PP.D_ACC_NUM,PP.D_SCH_K),'00000000000000000000',''),
				BIC_RCP		= PP.D_BIK,
				NAME_BIC_RCP = PP.D_BANK + case isnull(@iCityP,0) when 1 then ' ' + isnull(PP.D_BANK_CITY,'') else '' end,
				BS_KS_RCP	 = PP.D_SCH_B,
				DATE_PAY	= PP.SROK, 
				ORDER_PAY   = PP.[Order],
				PURPOSE = case PP.BK_IN_TGT when 1 then rtrim(replace(replace(replace(replace(replace(replace(
													case isnull(ltrim(rtrim(PP.BO_NUM)),'') when '' then rtrim(dbo.BB_DDELIM_DEL(isnull(APO.LS_FMT, APOD.LS_FMT),'<БО>')) else isnull(APO.LS_FMT, APOD.LS_FMT) end, 
													'<БО>', isnull(ltrim(rtrim(PP.BO_NUM)),'')),
													'<Счет>', case PP.S_ACC_TYPE when 1 then '' else rtrim(PP.S_ACC_NUM) end),
													'<Перевод_строки>', '
	)'),												'<БК>',rtrim(dbo.BB_BK_FOR_SHABLON(PP.LINK, isnull(APO.SHABLON_BK, APOD.SHABLON_BK),isnull(APO.DELIM, APOD.DELIM),isnull(APO.DELIM5, APOD.DELIM5)))),
														--'<БК>',/*str(P.S_ACC_LINK) + '#' +*/ APO.SHABLON_BK /*+ '#' + APO.DELIM + '#' + APO.DELIM5*/),
													'<Руб>',rtrim(ltrim(str(floor(PP.SUMMA))))),
													'<Коп>', right('00' + rtrim(ltrim(str((PP.SUMMA - floor(PP.SUMMA)) * 100))),2))) + ' ' 
					else '' end + ltrim(replace(replace(PP.TARGETTEXT,char(10),''),char(13),'')) + ' ' + ltrim(dbo.PrintPlatporGetNDSString(PP.LINK,0)),

				PAYSTATUS	= PPA.[STATUS],
				KBK			= rtrim(replace(PPA.DOH_CODE,'.','')) + PPA.SGU_CODE,
				OKATO		= PPA.OKATO,
				OSNPLAT		= PPA.P_REASON,
				NAL_PER		= PPA.[PERIOD],
				NOM_DOK		= PPA.TREBNUM,
				DATE_DOK	= case PPA.ZERODATE when 1 then /*'00.00.0000'*/ '0' else CONVERT(CHAR(10),PPA.TREBDATE,104) end,
				TYPE_PL		= PPA.P_TYPE,
				GUID_FK		= '',
				KOD_TOFK_PAY = PP.S_KAZN_CODE,
				NAME_TOFK_PAY	 = PP.S_KAZN,
				KOD_UBP_PAY	= PP.S_BUDG,
				NAME_UBP_PAY = PP.S_FNAME,
				LS_PAY	 = case PP.S_ACC_TYPE when 1 then '' else PP.S_ACC_NUM end,
				LS_PAY_RCP	 = '',
				PRINT_KPP = str(PP.PRINT_KPP),	
				PRIZ = '1',
				-- Поля для приема выписки
				DATE_PP_IN = PP.DATE,
				DATE_PP_SPS = PP.DATE,
				NOM_PL_PO = '',
				SHIFR_RD_PO = '',
				NOM_RD_PO = '',
				DATE_RD_PO = PP.DATE,
				SUM_OST_PO = '',
				OPER_PO = '',
				DATE_IN_TOFK = PP.DATE,
				[GUID] = '',
				UIN_CODE = LTRIM(RTRIM(ISNULL(ppA.UIN_CODE,'')))--CASE WHEN ISNULL(ppA.UIN_CODE,'') = '' THEN CAST('0' AS VARCHAR(20)) ELSE ppA.UIN_CODE END
				--ppA.UIN_CODE
		INTO #SMETA_EXPORT_PPT	
		FROM dbo.DOCUMENTS_PAY PP
		inner join dbo.BufferGetTableByID(@cBuffId) B on B.LINK = PP.LINK
		LEFT JOIN dbo.DOCUMENTS_PAY_ADD PPA on PP.LINK = PPA.LINK
		left join dbo.BB_PAY_ACC_OPTIONS APO on APO.LINK_ACC = PP.S_ACC_LINK
		left join dbo.DOCUMENTS_PAY_ACC_OPTIONS APOD on APOD.OSN = 1
		inner join dbo.DEPARTMENT_ACCOUNTS DA on APOD.LINK_ACC = DA.LINK and PP.S_ACC_TYPE = DA.TYPE

		SELECT *,
			NAME_RCP AS CNAME_UBP_RCP,
			NOM_DOK AS NUM_DOK
		FROM #SMETA_EXPORT_PPT
--	ELSE
-- СNAME_UBP_RCP
--		SELECT * 
--		FROM #SMETA_EXPORT_PP

	DROP TABLE #SMETA_EXPORT_PPT

	if @iGroupKBK = 1
	-- Таблица 5 (PPST)
		select  LINK = GP.LINK,
				LINK_UP = GP.LINK,
				KBK = left(replace(isnull(KBK1.CODE, KBK.CODE),'.','') + SGU.CODE ,20),
				TYPE_KBK = case isnull(KBK1.[TYPE], KBK.[TYPE]) when 1 then '10'
												 when 2 then '20'
												 when 4 then '31'
												 when 8 then '32'
												 else '' end,
				ADD_KLASS = ISNULL(DCL.CODE,''),
				ADD_KLASS_RCP = '',
				[SUM] = sum(GP2.SUMMA),
				DIR_SUM	= '1',
				MES_FIN	= right('0' + rtrim(ltrim(convert(char(2), month(GP.DATE)))),2),
				REZERV	= '',
				KOD_FIN = case D.BUH_TYPE when '1' then SA.cSource else '' end,
				-- Поля для приема выписки
				NUM_BO = '',
				ОКАТО = ''

		from G_PROV GP 
		inner join dbo.BufferGetTableByID(@cBuffId) B on GP.LINK = B.LINK
		inner join 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 GPA1 ON GP2.LINK = GPA1.LINK_UP AND DB_KR = 1
		INNER JOIN dbo.DEPARTMENTS D on GP.DEP = D.LINK
		INNER JOIN dbo.S_ACCOUNTS SA on GPA1.ACCOUNT = SA.LINK
		LEFT JOIN KL_KBK KBK ON GPA1.KBK = KBK.LINK
		LEFT JOIN KL_KBK_LINKED KBKL ON KBKL.LINK = KBK.LINK and @iLinkedKBK = 1
		LEFT JOIN KL_KBK KBK1 ON KBKL.LINK_KBK = KBK1.LINK
		LEFT JOIN KOSGU SGU ON GPA1.EKR = SGU.LINK
		LEFT JOIN DOP_CLASSIF DCL ON GPA1.AP2 = DCL.LINK
		group by GP.LINK, right('0' + rtrim(ltrim(convert(char(2), month(GP.DATE)))),2), left(replace(isnull(KBK1.CODE, KBK.CODE),'.','') + SGU.CODE ,20), ISNULL(DCL.CODE,''), isnull(KBK1.[TYPE], KBK.[TYPE]),  D.BUH_TYPE, SA.cSource
	else
		select  LINK = GP2.LINK,
				LINK_UP = GP.LINK,
				KBK = left(replace(isnull(KBK1.CODE, KBK.CODE),'.','') + SGU.CODE ,20),
				TYPE_KBK = case isnull(KBK1.[TYPE], KBK.[TYPE]) when 1 then '10'
												 when 2 then '20'
												 when 4 then '31'
												 when 8 then '32'
												 else '' end,
				ADD_KLASS = ISNULL(DCL.CODE,''),
				ADD_KLASS_RCP = '',
				[SUM] = GP2.SUMMA,
				DIR_SUM	= '1',
				MES_FIN	= right('0' + rtrim(ltrim(convert(char(2), month(GP.DATE)))),2),
				REZERV	= '',
				KOD_FIN = case D.BUH_TYPE when '1' then SA.cSource else '' end,
				-- Поля для приема выписки
				NUM_BO = '',
				ОКАТО = ''

		from G_PROV GP 
		inner join dbo.BufferGetTableByID(@cBuffId) B on GP.LINK = B.LINK
		inner join 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 GPA1 ON GP2.LINK = GPA1.LINK_UP AND DB_KR = 1
		INNER JOIN dbo.DEPARTMENTS D on GP.DEP = D.LINK
		INNER JOIN dbo.S_ACCOUNTS SA on GPA1.ACCOUNT = SA.LINK
		LEFT JOIN KL_KBK KBK ON GPA1.KBK = KBK.LINK
		LEFT JOIN KL_KBK_LINKED KBKL ON KBKL.LINK = KBK.LINK and @iLinkedKBK = 1
		LEFT JOIN KL_KBK KBK1 ON KBKL.LINK_KBK = KBK1.LINK
		LEFT JOIN KOSGU SGU ON GPA1.EKR = SGU.LINK
		LEFT JOIN DOP_CLASSIF DCL ON GPA1.AP2 = DCL.LINK	


end
else
begin

	select
		P.link, 
		P.link as link_up,
		BK_IN_TGT,
		S_ACC_LINK,
		DATE,

		[NUM_PP] = NUMBER,
		[DATE_PP] = DATE,
		[VID_PL] = 
			CASE	
				WHEN KIND = 'почтой'     THEN '1'
				WHEN KIND = 'телеграфом' THEN '2'
				WHEN KIND = 'электронно' THEN '3'
				WHEN KIND = 'срочно' 	 THEN '4'
				ELSE '0' 
			END,
		[SUM_PP] = summa, 
		[INN_PAY] = P.S_INN,
		[KPP_PAY] = case P.PRINT_KPP when 1 then P.S_KPP else '' end,
		[KOD_BP_PAY] = P.S_BUDG,
		[NAME_BP_PAY] = convert(varchar(120), ltrim(rtrim(S_FNAME))),
		[NAME_PAY] = dbo.BB_DEP_NAME_FOR_SHABLON(isnull(APO.SHABLON_D,APOD.SHABLON_D), default, P.S_ACC_LINK), 
		[NUM_LS_PAY] = S_ACC_NUM,
		[KOD_TOFK_PAY] = P.S_KAZN_CODE,
		[INN_OK_PAY] = case P2.INN_OK_PAY when 1 THEN P.S_KAZN_INN ELSE '' END,
		[NM_OK_PAY] = CASE P2.NM_OK_PAY when 1 THEN convert(varchar(120), P.S_KAZN) ELSE '' END,
		[RS_PAY] = case P.S_ACC_TYPE when 1 then P.S_ACC_NUM else P.S_SCH_K end,
		[BIK_PAY] = P.S_BIK,
		[BANK_PAY] = P.S_BANK + case isnull(@iCity,0) when 1 then ' ' + isnull(P.S_BANK_CITY,'') else '' end,
    	[FILIAL_PAY] = case P2.FILIAL_PAY when 1 THEN P.S_BANK_FILIAL ELSE '' END,
		[KS_PAY] = P.S_SCH_B,
		[INN_RCP]=D_INN,
		[KPP_RCP]= case P.PRINT_KPP when 1 then P.D_KPP else '' end,
		[NAME_RCP]=dbo.BB_DEP_NAME_FOR_SHABLON(CASE WHEN P1.DOH_CODE is not null or P1.OKATO is not null or P_REASON is not null or P1.PERIOD is not null or TREBNUM is not null or TREBDATE is not null or P_TYPE is not null or STATUS is not null THEN isnull(APO.

SHABLON_N, APOD.SHABLON_N) else isnull(APO.SHABLON_S, APOD.SHABLON_S) end, default, P.D_ACC_LINK),
		[INN_OK_RCP]= CASE P2.INN_OK_RCP WHEN 1 THEN P.D_KAZN_INN ELSE '' END,
		[NM_OK_RCP] = CASE P2.NM_OK_RCP WHEN 1 THEN P.D_FNAME ELSE '' END,
		[RS_RCP] = case P.D_ACC_TYPE when 1 then P.D_ACC_NUM else P.D_SCH_K end,
		[LS_RCP] = case P.D_ACC_TYPE when 1 then '' else P.D_ACC_NUM end,
		[BIK_RCP] = P.D_BIK,
		[BANK_RCP]= P.D_BANK + case isnull(@iCityP,0) when 1 then ' ' + isnull(P.D_BANK_CITY,'') else '' end,
		[FILIAL_RCP]= CASE P2.FILIAL_RCP when 1 THEN P.D_BANK_FILIAL ELSE '' END,
		[KS_RCP]= P.D_SCH_B,
		[TIME_PAY] = CASE P2.TIME_PAY WHEN 1 THEN srok ELSE cast (null as datetime) END,
		[ORDER_PAY] = P.[ORDER],
		[PURPOSE] = case P.BK_IN_TGT when 1 then rtrim(replace(replace(replace(replace(replace(replace(
													case isnull(ltrim(rtrim(P.BO_NUM)),'') when '' then rtrim(dbo.BB_DDELIM_DEL(isnull(APO.LS_FMT, APOD.LS_FMT),'<БО>')) else isnull(APO.LS_FMT, APOD.LS_FMT) end, 
													'<БО>', isnull(ltrim(rtrim(P.BO_NUM)),'')),
													'<Счет>', case P.S_ACC_TYPE when 1 then '' else rtrim(P.S_ACC_NUM) end),
													'<Перевод_строки>', '
	)'),												'<БК>',rtrim(dbo.BB_BK_FOR_SHABLON(P.LINK, isnull(APO.SHABLON_BK, APOD.SHABLON_BK),isnull(APO.DELIM, APOD.DELIM),isnull(APO.DELIM5, APOD.DELIM5)))),
														--'<БК>',/*str(P.S_ACC_LINK) + '#' +*/ APO.SHABLON_BK /*+ '#' + APO.DELIM + '#' + APO.DELIM5*/),
													'<Руб>',rtrim(ltrim(str(floor(P.SUMMA))))),
													'<Коп>', right('00' + rtrim(ltrim(str((P.SUMMA - floor(P.SUMMA)) * 100))),2))) + ' ' 
					else '' end + ltrim(replace(replace(P.TARGETTEXT,char(10),''),char(13),'')) + ' ' + ltrim(dbo.PrintPlatporGetNDSString(P.LINK,0)),

		[PRINT_KPP]='0',

		[PAYSTATUS] = P1.STATUS,
		[KBKD] = rtrim(ltrim(replace(P1.doh_code,'.',''))) + ltrim(P1.sgu_code),
		[PAYOKATO] = P1.OKATO,
		[OSNPLAT] = P1.P_REASON, 
		[NAL_PER] = P1.PERIOD,
		[N_DOK] = P1.TREBNUM, 
		[D_DOK] = CASE WHEN ISNULL(ZERODATE, 0) = 1 THEN '0' ELSE CONVERT(CHAR(10), P1.TREBDATE,104) END,
		[TYPE_PL] = P1.P_TYPE,
		[Name_Budg] = --convert(char(20), (
						(select top 1 budg.name --budg.code БРАТЬ БЮДЖЕТ ОТПРАВИТЕЛЯ?
						FROM G_PROV1 GP1 INNER JOIN G_PROV2 GP2 ON (GP1.LINK_UP = P.LINK AND GP2.LINK_UP = GP1.LINK)
						INNER JOIN G_PROV_AP GPA1 ON GP2.LINK = GPA1.LINK_UP AND DB_KR = 0
						LEFT JOIN BI_DICTION_KBK F ON GPA1.KBK = F.LINK
						LEFT JOIN kl_admin_bs adm ON adm.link = f.link_ADM 
						LEFT JOIN kl_budg_type budg ON budg.link = adm.link_budg) /* 2005.12 */

	from dbo.documents_pay P
	inner join dbo.BufferGetTableByID(@cBuffId) B on P.LINK = B.LINK
	LEFT OUTER JOIN DOCUMENTS_PAY_ADD P1 ON P.LINK = P1.LINK
	LEFT OUTER JOIN DOCUMENTS_PAY_ADD2 P2 ON P.LINK = P2.LINK
	left join dbo.BB_PAY_ACC_OPTIONS APO on APO.LINK_ACC = P.S_ACC_LINK
	left join dbo.DOCUMENTS_PAY_ACC_OPTIONS APOD on APOD.OSN = 1
	inner join dbo.DEPARTMENT_ACCOUNTS DA on APOD.LINK_ACC = DA.LINK and P.S_ACC_TYPE = DA.TYPE
		

	-- Если платежка налоговая 
	/*
	  1. Если в проводочной части указана Доходная классификация то
	   в блок PPST выгружаем код дохода = код дохода + сгу (20 символов)
	   и сумму - больше ничего !
	  2. Если в проводочной части указана Расходная классификация
	   то выгружаем поблочно раздел, подраздел и т.д. .
	   поле код дохода - пустой
	*/

	if @iGroupKBK = 1
	SELECT
		LINK = GP1.LINK_UP,
		LINK_UP = GP1.LINK_UP,	
		[MARKER] = 'PPST',
		[GLAVA] = LTRIM(RTRIM(COALESCE(F1.ADM_CODE, F.ADM_CODE, ''))),
		[RAZDEL] =LTRIM(RTRIM(COALESCE(F1.DIV_CODE, F.DIV_CODE, ''))),
		[STATIA] = LTRIM(RTRIM(COALESCE(F1.CSR_CODE, F.CSR_CODE, ''))),
		[VID] = LTRIM(RTRIM(COALESCE(F1.EXP_CODE, F.EXP_CODE, ''))),
	--	[KOD_FP] = '',
		[KOD_FP] = convert(varchar(3), isnull(DC.CODE,'')), 
		[E_KLASS] = LTRIM(RTRIM(ISNULL(KEK.CODE, ''))),
		[NUM_BO] =  LTRIM(RTRIM(ISNULL(P.bo_num,''))),
		[MON_FIN]='',
		[SUM_STR] = sum(GP2.summa),
		[FOND_P] = '',
		[KKIVNF] = CASE COALESCE(F1.[TYPE], F.[TYPE]) WHEN 8 THEN REPLACE(COALESCE(F1.CODE, F.CODE, ''),'.','') + SGU.CODE else '' end,

		[KKIVF] = CASE COALESCE(F1.[TYPE], F.[TYPE]) WHEN 4 THEN REPLACE(COALESCE(F1.CODE, F.CODE, ''),'.','') + SGU.CODE else '' end,
		[KDOH] = CASE COALESCE(F1.[TYPE], F.[TYPE]) WHEN 2 THEN REPLACE(COALESCE(F1.CODE, F.CODE, ''),'.','') + SGU.CODE else '' end,

		[ADD_KLASS] = isnull(DC.CODE,''),	/* 2005.12 */
		[KOD_FIN] = (select top 1 left(code, 1) from s_accounts SA where SA.link = GPA1.Account), /* 2005.12 */
		[REZERV] = convert(varchar(40),'')	/* 2005.12 */
	FROM G_PROV1 GP1 
	inner join dbo.BufferGetTableByID(@cBuffId) B on GP1.LINK_UP = B.LINK
	inner join dbo.documents_pay P on P.LINK = B.LINK
	INNER JOIN G_PROV2 GP2 ON GP2.LINK_UP = GP1.LINK
	INNER JOIN G_PROV_AP GPA1 ON GP2.LINK = GPA1.LINK_UP AND DB_KR = 1
	LEFT OUTER JOIN BI_DICTION_KBK_FULL F ON GPA1.KBK = F.LINK
	LEFT JOIN KL_KBK_LINKED KBKL ON KBKL.LINK = F.LINK and @iLinkedKBK = 1
	LEFT JOIN BI_DICTION_KBK_FULL F1 ON KBKL.LINK_KBK = F1.LINK
	LEFT OUTER JOIN DICTIONARY_ITEM KEK ON GPA1.EKR = KEK.LINK
	LEFT OUTER JOIN KOSGU SGU ON GPA1.SGU = SGU.LINK
	LEFT OUTER JOIN BD_DOP_CLASSIF DC on DC.link = GPA1.AP2
	group by GP1.LINK_UP, LTRIM(RTRIM(COALESCE(F1.ADM_CODE, F.ADM_CODE, ''))),
		LTRIM(RTRIM(COALESCE(F1.DIV_CODE, F.DIV_CODE, ''))),
		LTRIM(RTRIM(COALESCE(F1.CSR_CODE, F.CSR_CODE, ''))),
		LTRIM(RTRIM(COALESCE(F1.EXP_CODE, F.EXP_CODE, ''))),
		convert(varchar(3), isnull(DC.CODE,'')), 
		LTRIM(RTRIM(ISNULL(KEK.CODE, ''))),
		LTRIM(RTRIM(ISNULL(P.bo_num,''))),
		CASE COALESCE(F1.[TYPE], F.[TYPE]) WHEN 8 THEN REPLACE(COALESCE(F1.CODE, F.CODE, ''),'.','') + SGU.CODE else '' end,
		CASE COALESCE(F1.[TYPE], F.[TYPE]) WHEN 4 THEN REPLACE(COALESCE(F1.CODE, F.CODE, ''),'.','') + SGU.CODE else '' end,
		CASE COALESCE(F1.[TYPE], F.[TYPE]) WHEN 2 THEN REPLACE(COALESCE(F1.CODE, F.CODE, ''),'.','') + SGU.CODE else '' end,
		isnull(DC.CODE,''),
		GPA1.Account
else
	SELECT
		LINK = GP2.LINK,
		LINK_UP = GP1.LINK_UP,	
		[MARKER] = 'PPST',
		[GLAVA] = LTRIM(RTRIM(COALESCE(F1.ADM_CODE, F.ADM_CODE, ''))),
		[RAZDEL] =LTRIM(RTRIM(COALESCE(F1.DIV_CODE, F.DIV_CODE, ''))),
		[STATIA] = LTRIM(RTRIM(COALESCE(F1.CSR_CODE, F.CSR_CODE, ''))),
		[VID] = LTRIM(RTRIM(COALESCE(F1.EXP_CODE, F.EXP_CODE, ''))),
	--	[KOD_FP] = '',
		[KOD_FP] = convert(varchar(3), isnull(DC.CODE,'')), 
		[E_KLASS] = LTRIM(RTRIM(ISNULL(KEK.CODE, ''))),
		[NUM_BO] =  LTRIM(RTRIM(ISNULL(P.bo_num,''))),
		[MON_FIN]='',
		[SUM_STR] = GP2.summa,
		[FOND_P] = '',
		[KKIVNF] = CASE COALESCE(F1.[TYPE], F.[TYPE]) WHEN 8 THEN REPLACE(COALESCE(F1.CODE, F.CODE, ''),'.','') + SGU.CODE else '' end,

		[KKIVF] = CASE COALESCE(F1.[TYPE], F.[TYPE]) WHEN 4 THEN REPLACE(COALESCE(F1.CODE, F.CODE, ''),'.','') + SGU.CODE else '' end,
		[KDOH] = CASE COALESCE(F1.[TYPE], F.[TYPE]) WHEN 2 THEN REPLACE(COALESCE(F1.CODE, F.CODE, ''),'.','') + SGU.CODE else '' end,

		[ADD_KLASS] = isnull(DC.CODE,''),	/* 2005.12 */
		[KOD_FIN] = (select top 1 left(code, 1) from s_accounts SA where SA.link = GPA1.Account), /* 2005.12 */
		[REZERV] = convert(varchar(40),'')	/* 2005.12 */
	FROM G_PROV1 GP1 
	inner join dbo.BufferGetTableByID(@cBuffId) B on GP1.LINK_UP = B.LINK
	inner join dbo.documents_pay P on P.LINK = B.LINK
	INNER JOIN G_PROV2 GP2 ON GP2.LINK_UP = GP1.LINK
	INNER JOIN G_PROV_AP GPA1 ON GP2.LINK = GPA1.LINK_UP AND DB_KR = 1
	LEFT OUTER JOIN BI_DICTION_KBK_FULL F ON GPA1.KBK = F.LINK
	LEFT JOIN KL_KBK_LINKED KBKL ON KBKL.LINK = F.LINK and @iLinkedKBK = 1
	LEFT JOIN BI_DICTION_KBK_FULL F1 ON KBKL.LINK_KBK = F1.LINK
	LEFT OUTER JOIN DICTIONARY_ITEM KEK ON GPA1.EKR = KEK.LINK
	LEFT OUTER JOIN KOSGU SGU ON GPA1.SGU = SGU.LINK
	LEFT OUTER JOIN BD_DOP_CLASSIF DC on DC.link = GPA1.AP2

end





GO


GRANT EXECUTE ON dbo.[BB_EXPORT_PP] TO PUBLIC

GO


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


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

GO

CREATE procedure dbo.I_REPORT_FORMULA_4FSS_RAZD1
	@varKSOUT_VAL NUMERIC(20,2) OUTPUT,
	@varKScCode	char(10) = '',
	@varKSiCol	smallint = '0'
AS
DECLARE @varKSname VARCHAR(100), 
	@varKSSQL VARCHAR(8000)
	SET @varKSname = (SELECT ID FROM BUFFER WHERE LINK = -115 AND SID = SUSER_SID() )

	CREATE     TABLE #TMP(
		BASE_FSS NUMERIC(20,2), 
		CNT_FSS INT,
		CNT_FEM	INT)

	SET @varKSSQL = '

		INSERT INTO #TMP
		SELECT  BASE_FSS, CNT_FSS, CNT_FEM
		FROM ' + @varKSname + ' 
		WHERE CODE_STR=' + ltrim(@varKScCode)

	EXEC (@varKSSQL)

	IF @varKSiCol = 3
		SET @varKSOUT_VAL = (SELECT BASE_FSS FROM #TMP)
	IF @varKSiCol = 6
		SET @varKSOUT_VAL = (SELECT CNT_FSS FROM #TMP)
	IF @varKSiCol = 7
		SET @varKSOUT_VAL = (SELECT CNT_FEM FROM #TMP)
	IF @varKSiCol = 8
		SET @varKSOUT_VAL = (SELECT CNT_FEM FROM #TMP)
	
	DROP TABLE #TMP
	SELECT @varKSOUT_VAL = ISNULL(@varKSOUT_VAL, 0)


GO


GRANT EXECUTE ON dbo.[I_REPORT_FORMULA_4FSS_RAZD1] TO PUBLIC

GO



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

GO


CREATE            PROCEDURE [dbo].FB_REPORT_RBS
	@varKSiFyear	int,
	@varKSdDateB	datetime,
	@varKSdDateE	datetime,
	@varKSiDocType	tinyint,
	@varKSiIFType	INT,
	@varKScVal1 		char(1), 
	@varKSnOtborLink1 	int,
	@varKScVal2 		char(1), 
	@varKSnOtborLink2 	int,
	@varKScVal3 		char(1), 
	@varKSnOtborLink3 	int,
	@varKScVal4		char(1), 
	@varKSnOtborLink4 	int


AS
DECLARE	@varKSintFinPeriod	tinyint, 
	@varKSFinObjCode 	char(100),
	@varKSintSummaType 	tinyint,
	@cCROSS_TABLE 		char(100),
	@intCOUNTER		INT,
	@cSQL_STR		VARCHAR (1000),
	@cCOUNTER		VARCHAR (10),
	@intMAX_REC		INT,
	@intCOUNT_COLROW	INT,
	@varKScIF		char(1),
	@varKSintDopEkr 	tinyint,
	@varKSiPeriod 		int,
	@varKScPerTiile 	varchar	(200),
	@varKSintTypePer	int,
	@iDopCl int
	
set @iDopCl = isnull((select FIN_TABLE_DOP_CL from workmode),0)

	
set @varKSiPeriod = month(@varKSdDateE)
select @varKScIF = (case @varKSiIFType when 2 then '2' else '1' end) 

SELECT @varKSintDopEkr = FIN_DOP_EKR FROM WORKMODE


SET @intMAX_REC = 10
DECLARE @varKSInTable TABLE( 
	VKR 	INT,
	EKR 	INT, 
	DOP_CL 	INT,
	DEP_ACC INT, 
	ord		int,
	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,
	ITOG 	[numeric](28, 2) NULL)

SELECT @varKSFinObjCode = (CASE @varKSiDocType 	WHEN 1 	THEN  'FINANS_LIMIT'
						WHEN 2 	THEN  'FINANS_ASSIGN' END)


IF @varKSFinObjCode like '%_ASSIGN%'
BEGIN
	SELECT @varKSintFinPeriod = max(FIN_SMETA_PER), @varKSintTypePer = 0 FROM WorkMode
	SELECT @varKSintSummaType = ISNULL(UM,1) FROM FINANS_ASSIGN_OPTIONS
	set @varKScIF = null
END
IF @varKSFinObjCode like '%_LIMIT%'
BEGIN
	SELECT	@varKSintFinPeriod = /*(max(FIN_LIM_type) * 10 + */max(FIN_LIM_PER), 
		@varKSintTypePer = max(FIN_LIM_type) FROM WorkMode
	SELECT @varKSintSummaType = ISNULL(UM,1) FROM FINANS_LIMIT_OPTIONS
END


if @varKSiFyear is null
BEGIN
	INSERT INTO @varKSInTable
	SELECT F.VKR, F.EKR, dop_cl = case @iDopCl when 1 then F.DOP_CL else null end, FH.ACCOUNT, 0, 
		sum(F.P1), sum(F.P2), sum(F.P3), sum(F.P4), sum(F.P5), sum(F.P6), sum(F.P7), sum(F.P8), sum(F.P9), sum(F.P10), sum(F.P11), sum(F.P12),
		[ITOGS] = sum(F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11 + F.P12)
	FROM dbo.FINANSE F
	inner join dbo.G_Prov GP on GP.DATE_PROV is not null and F.LINK_UP = GP.LINK 
	inner join dbo.FINANSE_HEAD FH on FH.LINK = GP.LINK
	inner join dbo.BufferGetTableByID('REPORT_RBS') B on GP.LINK = B.LINK
	inner join dbo.S_OBJECTS SO on SO.CODE = @varKSFinObjCode and GP.OBJECT = SO.LINK
	GROUP BY F.VKR, F.EKR, case @iDopCl when 1 then F.DOP_CL else null end, FH.ACCOUNT
	ORDER BY FH.ACCOUNT, F.VKR, F.EKR, DOP_CL
	select @varKSiFyear = max(year(DATE_PROV)) from dbo.G_PROV where LINK in (select LINK from  dbo.BufferGetTableByID('REPORT_RBS'))
end	
else
begin 
	-- Выбираем счета из фильтра
	DECLARE @varKStDEP_ACC  TABLE (LINK_ACC [INT])	
	IF LEN (@varKScVal1) > 0
		INSERT INTO @varKStDEP_ACC
		SELECT RECORD
		FROM OBJECT_VAR_DEPARTMENT_ACCOUNTS
		WHERE LINK_UP = @varKSnOtborLink1
	ELSE
		INSERT INTO @varKStDEP_ACC
		SELECT DA.LINK
		FROM dbo.DEPARTMENT_ACCOUNTS DA
		inner join dbo.DEPARTMENTS D on D.LINK = DA.LINK_UP and (D.TYPE = 4 OR D.TYPE = 2 OR D.ZB = 1)
		where DA.TYPE = 2 or DA.TYPE = 4
	
	-- Выбираем КБК из фильтров по Подразделам и ЦС
	DECLARE @varKStVKR  TABLE (LINK [INT])	
	IF LEN (@varKScVal2) > 0 AND LEN (@varKScVal4) > 0
		INSERT INTO @varKStVKR
		SELECT LINK
		FROM dbo.KL_KBK KBK
		INNER JOIN dbo.KL_VKR VKR ON KBK.LINK = VKR.LINK_KBK 
		INNER JOIN dbo.OBJECT_VAR_DIVISION OVD ON OVD.LINK_UP = @varKSnOtborLink2 AND OVD.RECORD = VKR.LINK_DIV
		INNER JOIN dbo.OBJECT_VAR_TARGET_ITEM OVI ON OVI.LINK_UP = @varKSnOtborLink4 AND OVI.RECORD = VKR.LINK_CSR
	
	IF LEN (@varKScVal2) > 0 AND NOT LEN (@varKScVal4) > 0
		INSERT INTO @varKStVKR
		SELECT LINK
		FROM dbo.KL_KBK KBK
		INNER JOIN dbo.KL_VKR VKR ON KBK.LINK = VKR.LINK_KBK
		INNER JOIN dbo.OBJECT_VAR_DIVISION OVD ON OVD.LINK_UP = @varKSnOtborLink2 AND OVD.RECORD = VKR.LINK_DIV 
	
	IF NOT LEN (@varKScVal2) > 0 AND LEN (@varKScVal4) > 0
		INSERT INTO @varKStVKR
		SELECT LINK
		FROM dbo.KL_KBK KBK
		INNER JOIN dbo.KL_VKR VKR ON KBK.LINK = VKR.LINK_KBK
		INNER JOIN dbo.OBJECT_VAR_TARGET_ITEM OVI ON OVI.LINK_UP = @varKSnOtborLink4 AND OVI.RECORD = VKR.LINK_CSR
	
	IF LEN (@varKScVal2) = 0 AND NOT LEN (@varKScVal4) > 0
		INSERT INTO @varKStVKR
		SELECT LINK
		FROM dbo.KL_KBK
		WHERE TYPE = 1
	
	-- Выбираем ЕКР из фильтра
	DECLARE @varKStEKR  TABLE (LINK [INT])	
	IF LEN (@varKScVal3) > 0
		INSERT INTO @varKStEKR
		SELECT RECORD
		FROM dbo.OBJECT_VAR_KOSGU
		WHERE LINK_UP = @varKSnOtborLink3
	ELSE
		INSERT INTO @varKStEKR
		SELECT LINK
		FROM dbo.KOSGU
		WHERE IS_EKR = 1

	INSERT INTO @varKSInTable
	SELECT * FROM (select * from (SELECT FS.VKR, FS.EKR,DOP_CL = case @iDopCl when 1 then FS.DOP_CL else null end, FS.DEP_ACC, odr = 0, 
		sum(FS.P1) as P1, sum(FS.P2) as P2, sum(FS.P3) as P3, sum(FS.P4) as P4,	sum(FS.P5) as P5, sum(FS.P6) as P6,	sum(FS.P7) as P7, sum(FS.P8) as P8, sum(FS.P9) as P9, sum(FS.P10) as P10, sum(FS.P11) as P11, sum(FS.P12) as P12,
		[ITOGS] = sum(FS.P1 + FS.P2 + FS.P3 + FS.P4 + FS.P5 + FS.P6 + FS.P7 + FS.P8 + FS.P9 + FS.P10 + FS.P11 + FS.P12)
		FROM dbo.FB_FINANS_POLUCH(@varKSiFyear, @varKSdDateB, @varKSdDateE,@varKSiPeriod, @varKSintSummaType,0, @varKSFinObjCode, @varKSintFinPeriod, @varKScIF) FS
		GROUP BY FS.VKR, FS.EKR, case @iDopCl when 1 then FS.DOP_CL else null end, FS.DEP_ACC) F --AND NOT SUMMA = 0
		WHERE	F.EKR is not null
			AND F.DEP_ACC in (select LINK_ACC from @varKStDEP_ACC)
			AND F.EKR in (select LINK from @varKStEKR)
			AND F.VKR in (select LINK from @varKStVKR)) FS1 
	WHERE NOT FS1.ITOGS = 0 
	ORDER BY FS1.DEP_ACC, FS1.VKR, FS1.EKR, FS1.DOP_CL
end

INSERT INTO @varKSInTable
SELECT  VKR, EKR, NULL, DEP_ACC, 1, sum(P1), sum(P2) , sum(P3), sum(P4), sum(P5), sum(P6), sum(P7), sum(P8), sum(P9), sum(P10), sum(P11), sum(P12), SUM(ITOG)
FROM @varKSInTable T
WHERE @varKSintDopEkr = 1 and exists(select * from @varKSInTable T1 where T1.VKR =T.VKR and T1.EKR =T.EKR and T1.DOP_CL is not null)
GROUP BY VKR, EKR, DEP_ACC

INSERT INTO @varKSInTable
SELECT F1.VKR, EKR2.LINK, null, F1.DEP_ACC, 2, sum(P1), sum(P2) , sum(P3), sum(P4), sum(P5), sum(P6), sum(P7), sum(P8), sum(P9), sum(P10), sum(P11), sum(P12), SUM(ITOG)
FROM @varKSInTable F1 
INNER JOIN dbo.KOSGU EKR1 ON EKR1.LINK = F1.EKR AND RIGHT(EKR1.CODE,1) <> '0' 
INNER JOIN dbo.KOSGU EKR2 ON EKR2.CODE = LEFT(EKR1.CODE,2) + '0' AND NOT EXISTS(SELECT * FROM @varKSInTable T1 WHERE T1.VKR = F1.VKR and EKR2.LINK = T1.EKR)
WHERE @varKSintDopEkr = 1 and ord = 0
GROUP BY F1.VKR, EKR2.LINK , F1.DEP_ACC

INSERT INTO @varKSInTable
SELECT F1.VKR, EKR2.LINK, null, F1.DEP_ACC, 3, sum(P1), sum(P2) , sum(P3), sum(P4), sum(P5), sum(P6), sum(P7), sum(P8), sum(P9), sum(P10), sum(P11), sum(P12), SUM(ITOG)
FROM @varKSInTable F1 
INNER JOIN dbo.KOSGU EKR1 ON EKR1.LINK = F1.EKR AND RIGHT(EKR1.CODE,1) <> '00' 
INNER JOIN dbo.KOSGU EKR2 ON EKR2.CODE = LEFT(EKR1.CODE,2) + '00' AND NOT EXISTS(SELECT * FROM @varKSInTable T1 WHERE T1.VKR = F1.VKR and EKR2.LINK = T1.EKR)
WHERE @varKSintDopEkr = 1 and ord = 0
GROUP BY F1.VKR, EKR2.LINK , F1.DEP_ACC


select @varKScPerTiile = 'на ' + isnull(p.period + ' ' ,'') + convert(char(4),@varKSiFyear) + ' г.'
from (select period FROM PERIODS
where 	((ord = @varKSiPeriod and @varKSintFinPeriod = 3) OR
	(((ord = 13 and @varKSiPeriod in(1,2,3)) or 
		(ord = 14 and @varKSiPeriod in(4,5,6)) or
		(ord = 15 and @varKSiPeriod in(7,8,9)) or
		(ord = 16 and @varKSiPeriod in(10,11,12))) and @varKSintFinPeriod = 2)) and @varKSintTypePer = 1
union 
select '' as period where @varKSintTypePer = 0 or @varKSintFinPeriod = 1) p
		



insert into @varKSInTable
SELECT VKR, null, null, DEP_ACC, 4, sum(P1), sum(P2) , sum(P3), sum(P4), sum(P5), sum(P6), sum(P7), sum(P8), sum(P9), sum(P10), sum(P11), sum(P12), SUM(ITOG)
FROM @varKSInTable
where ord = 0
group by dep_acc, vkr

insert into @varKSInTable
SELECT null, null, null, DEP_ACC, 5, sum(P1), sum(P2) , sum(P3), sum(P4), sum(P5), sum(P6), sum(P7), sum(P8), sum(P9), sum(P10), sum(P11), sum(P12), SUM(ITOG)
FROM @varKSInTable
where ord = 0
group by dep_acc


insert into @varKSInTable
SELECT null, null, null, null, 6, sum(P1), sum(P2) , sum(P3), sum(P4), sum(P5), sum(P6), sum(P7), sum(P8), sum(P9), sum(P10), sum(P11), sum(P12), SUM(ITOG)
FROM @varKSInTable
where ord = 0

Select F.VKR, F.EKR, F.DOP_CL, F.DEP_ACC, F.P1, F.P2, F.P3, F.P4, F.P5, F.P6, F.P7, F.P8, F.P9, F.P10, F.P11, F.P12,
	PSI1 = SIT.P1, PSI2 = SIT.P2, PSI3 = SIT.P3, PSI4 = SIT.P4, PSI5 = SIT.P5, PSI5 = SIT.P6, PSI7 = SIT.P7, PSI8 = SIT.P8, PSI9 = SIT.P9, PSI10 = SIT.P10, PSI11 = SIT.P11, PSI12 = SIT.P12,
	PDI1 = DIT.P1, PDI2 = DIT.P2, PDI3 = DIT.P3, PDI4 = DIT.P4, PDI5 = DIT.P5, PDI6 = DIT.P6, PDI7 = DIT.P7, PDI8 = DIT.P8, PDI9 = DIT.P9, PDI10 = DIT.P10, PDI11 = DIT.P11, PDI12 = DIT.P12,
	[VKR_CODE] = VKR.CODE,
	[VKR_NAME] = VKR.NAME,
	[EKR_CODE] = EKR.CODE,
	[EKR_NAME] = coalesce(DCL.NAME, rtrim(EKR.NAME) + case F.ORD when 1 then '(Итого)' else '' end, VKR.NAME), --EKR.NAME
	[DOP_CODE] = DCL.CODE,
	--[DOP_NAME] = DCL.NAME,
	[DEP_CODE] = D.CODE,
	[DEP_NAME] = D.NAME,
	[ACC_CODE] = DA.CODE,
	F.ITOG, ITOGSI = SIT.ITOG, ITOGDI = DIT.ITOG,
	[um] 	= @varKSintSummaType, 
	[title]	= (case @varKSiDocType when 1 then 'ЛИМИТЫ БЮДЖЕТНЫХ ОБЯЗАТЕЛЬСТВ' else 'БЮДЖЕТНЫЕ АССИГНОВАНИЯ' end),  
	[per_title]	= @varKScPerTiile
	From @varKSInTable F  
	LEFT OUTER JOIN dbo.KL_KBK VKR ON VKR.LINK = F.VKR
	LEFT outer JOIN dbo.KOSGU EKR ON EKR.LINK = F.EKR
	LEFT outer JOIN dbo.DOP_CLASSIF DCL ON DCL.LINK = F.DOP_CL
	LEFT JOIN @varKSInTable SIT ON SIT.DEP_ACC = F.DEP_ACC and sit.ord = 5
	LEFT JOIN @varKSInTable DIT ON Dit.ord = 6 
	LEFT OUTER JOIN dbo.DEPARTMENT_ACCOUNTS DA ON DA.LINK = F.DEP_ACC
	LEFT OUTER JOIN dbo.DEPARTMENTS D ON D.LINK = DA.LINK_UP
	where F.ord < 5
	ORDER BY d.code, da.code, VKR.CODE,EKR.CODE, DCL.CODE, F.ORD desc   

RETURN 1


GO


GRANT EXECUTE ON dbo.[FB_REPORT_RBS] TO PUBLIC

GO

GO

--AFTER CODE 06.04.2014
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXPP140331' 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','Платежное поручение','TXPP140331',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 	= 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, 23,'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 		= 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
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_UIN_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_ZAYAVKA_KR_UIN_CODE', 'Код(УИН)', 37, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_ZAYAVKA_KR_UIN_CODE', NAME = 'Код(УИН)', ORDERS = '37', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_ZAYAVKA_KR_UIN_CODE'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_UIN_CODE', 'TITLE', 'Код(УИН)'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_UIN_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_UIN_CODE', 'CONTROLSOURCE', 'm.cAlias+".UIN_CODE"'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_UIN_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_UIN_CODE', 'SHORT_CODE_OBJ', 'UIN_CODE'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_UIN_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".UIN_CODE"'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_UIN_CODE', 'CONTROL_NAME_EDIT', 'parent.page3.ATXT23'
GO

GO
/****** Объект: Код спец. оценки условий труда (ссылка)******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COD_SPO_USL_TRUD_LINK_1')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'COD_SPO_USL_TRUD_LINK_1')
	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 = 'COD_SPO_USL_TRUD_LINK_1')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'COD_SPO_USL_TRUD_LINK_1')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COD_SPO_USL_TRUD_LINK_1'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COD_SPO_USL_TRUD_LINK_1')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COD_SPO_USL_TRUD_LINK_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COD_SPO_USL_TRUD_LINK_1', 'Код спец. оценки условий труда (ссылка)', 41, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_STAFF_ALL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COD_SPO_USL_TRUD_LINK_1', NAME = 'Код спец. оценки условий труда (ссылка)', ORDERS = '41', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_STAFF_ALL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COD_SPO_USL_TRUD_LINK_1'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_LINK_1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_LINK_1', 'CONTROLSOURCE', 'm.cAlias + ".SPO_UT"'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_LINK_1', 'TYPE_FIELD_DICT', 'VARCHAR(120)'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_LINK_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SPO_UT"'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_LINK_1', 'COMMENTARY', 'Источник финансирования'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
/****** Объект: Код спец. оценки условий труда (ссылка)******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COD_SPO_USL_TRUD_LINK')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'COD_SPO_USL_TRUD_LINK')
	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 = 'COD_SPO_USL_TRUD_LINK')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'COD_SPO_USL_TRUD_LINK')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COD_SPO_USL_TRUD_LINK'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COD_SPO_USL_TRUD_LINK')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COD_SPO_USL_TRUD_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COD_SPO_USL_TRUD_LINK', 'Код спец. оценки условий труда(ссылка)', 47, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_STAFF'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COD_SPO_USL_TRUD_LINK', NAME = 'Код спец. оценки условий труда(ссылка)', ORDERS = '47', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_STAFF'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COD_SPO_USL_TRUD_LINK'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_LINK', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_LINK', 'CONTROLSOURCE', 'm.cAlias + ".SPO_UT"'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_LINK', 'TYPE_FIELD_DICT', 'VARCHAR(120)'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SPO_UT"'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_LINK', 'COMMENTARY', 'Источник финансирования'
GO


/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
/****** Объект: Код спец. оценки условий труда******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COD_SPO_USL_TRUD_NAME_1')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'COD_SPO_USL_TRUD_NAME_1')
	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 = 'COD_SPO_USL_TRUD_NAME_1')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'COD_SPO_USL_TRUD_NAME_1')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COD_SPO_USL_TRUD_NAME_1'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COD_SPO_USL_TRUD_NAME_1')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COD_SPO_USL_TRUD_NAME_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COD_SPO_USL_TRUD_NAME_1', 'Код спец. оценки условий труда', 42, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_STAFF_ALL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COD_SPO_USL_TRUD_NAME_1', NAME = 'Код спец. оценки условий труда', ORDERS = '42', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_STAFF_ALL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COD_SPO_USL_TRUD_NAME_1'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_NAME_1', 'TITLE', 'Код спец. оценки условий труда'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_NAME_1', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("SA_SZV4_SPR",oobj.parent.parent.recordsource,"LINK, CODE", "SPO_UT, SPO_UT_N", "", "", "SPR_CODE LIKE ''SPO_USL_TRUDA''", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_NAME_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_NAME_1', 'CONTROLSOURCE', 'm.cAlias + ".SPO_UT_N"'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_NAME_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_NAME_1', 'TYPE_FIELD_DICT', 'VARCHAR(120)'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_NAME_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SPO_UT_N"'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_NAME_1', 'CONTROL_NAME_EDIT', 'pgf.page3.asel22'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_NAME_1', 'COMMENTARY', 'Код позиции списка'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DOC_PAY_UIN_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DOC_PAY_UIN_CODE', 'Код(УИН)', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_PAY_ADD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DOC_PAY_UIN_CODE', NAME = 'Код(УИН)', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_PAY_ADD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DOC_PAY_UIN_CODE'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_UIN_CODE', 'TITLE', 'Код(УИН)'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_UIN_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_UIN_CODE', 'CONTROLSOURCE', 'm.cAlias+".UIN_CODE"'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_UIN_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_UIN_CODE', 'SHORT_CODE_OBJ', 'UIN_CODE'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_UIN_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".UIN_CODE"'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_UIN_CODE', 'CONTROL_NAME_EDIT', 'ATXT23'
GO

GO
/****** Объект: Спец. оценка условий труда******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_NAME_PAYS_TARIF_NSPO')
	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_NAME_PAYS_TARIF_NSPO')
	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_NAME_PAYS_TARIF_NSPO')
	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_NAME_PAYS_TARIF_NSPO')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_NAME_PAYS_TARIF_NSPO'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_NAME_PAYS_TARIF_NSPO')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_PAYS_TARIF_NSPO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_PAYS_TARIF_NSPO', 'Спец. оценка условий труда', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_RANGE_PF'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NAME_PAYS_TARIF_NSPO', NAME = 'Спец. оценка условий труда', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_RANGE_PF'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NAME_PAYS_TARIF_NSPO'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAYS_TARIF_NSPO', 'TITLE', 'Спец. оценка условий труда'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAYS_TARIF_NSPO', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("SA_SZV4_SPR",oForm.ALIAS,"LINK, CODE", "SpecO, NSPECO", "", "", "SPR_CODE LIKE ''SPO_USL_TRUDA''", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAYS_TARIF_NSPO', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAYS_TARIF_NSPO', 'CONTROLSOURCE', 'm.cAlias + ".NSPECO"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAYS_TARIF_NSPO', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAYS_TARIF_NSPO', 'TYPE_FIELD_DICT', 'varchar(120)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAYS_TARIF_NSPO', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NSPECO"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAYS_TARIF_NSPO', 'CONTROL_NAME_EDIT', 'sprSPO'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAYS_TARIF_NSPO', 'COMMENTARY', 'Спец. оценка условий труда'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
/****** Объект: Спец. оценка условий труда(ссылка)******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_NAME_PAYS_TARIF_SPO')
	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_NAME_PAYS_TARIF_SPO')
	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_NAME_PAYS_TARIF_SPO')
	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_NAME_PAYS_TARIF_SPO')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_NAME_PAYS_TARIF_SPO'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_NAME_PAYS_TARIF_SPO')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_PAYS_TARIF_SPO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_PAYS_TARIF_SPO', 'Спец. оценка условий труда(ссылка)', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_RANGE_PF'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NAME_PAYS_TARIF_SPO', NAME = 'Спец. оценка условий труда(ссылка)', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_RANGE_PF'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NAME_PAYS_TARIF_SPO'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAYS_TARIF_SPO', 'TITLE', 'Спец. оценка условий труда'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAYS_TARIF_SPO', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAYS_TARIF_SPO', 'CONTROLSOURCE', 'm.cAlias + ".SpecO"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAYS_TARIF_SPO', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAYS_TARIF_SPO', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAYS_TARIF_SPO', 'TYPE_FIELD_DICT', 'varchar(4)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAYS_TARIF_SPO', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SpecO"'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
IF not exists(select * from dbo.formula_bridge where name = 'РСВ1_14_УСТАНОВКА' and PROC_NAME = 'SA_RSV_1_14_PFR_PREPARE')
begin
  	
  IF not exists(select * from dbo.DICTION where name = 'РСВ1_14_УСТАНОВКА')
  begin
		-- insert формулы установки в таблицу dbo.DICTION  
		declare @linkObjF int,
				@LinkOBJ int
							
		set @linkObjF  = (select link from dbo.s_objects where code = 'FORMULA_BRIDGE')
  
		insert into  dbo.DICTION (NAME,[OBJECT], CODE, begindate, enddate)
			values ('РСВ1_14_УСТАНОВКА', @linkObjF, NULL, '17530101','99991231')
		
		set @LinkOBJ = (select link from dbo.DICTION where name = 'РСВ1_14_УСТАНОВКА')
		
		-- insert порядка для формулы в таблицу dbo.DICTION_APP 
		IF not exists(select * from dbo.DICTION_APP where link_up = (select link from dbo.DICTION where name = 'РСВ1_14_УСТАНОВКА') and [object] = (select link from s_objects where  code = 'FORMULA_ORDERS'))
		begin	
			declare @linkObjF_ORD int 
					
			set @linkObjF_ORD = (select link from dbo.s_objects where code = 'FORMULA_ORDERS') 
			
			insert into  dbo.DICTION_APP (LINK_UP,[OBJECT], VALUE)
				values (@LinkOBJ, @linkObjF_ORD, '9')		
				
		end
		-- insert процедуры обработки для формулы в таблицу dbo.DICTION_APP 		
		IF not exists(select * from dbo.DICTION_APP where link_up = (select link from dbo.DICTION where name = 'РСВ1_14_УСТАНОВКА') and [object] = (select link from s_objects where  code = 'FORMULA_PROCEDURE'))
		begin	
			
			declare @linkObjF_PROC int 
					
			set @linkObjF_PROC = (select link from dbo.s_objects where code = 'FORMULA_PROCEDURE') 
		
			insert into  dbo.DICTION_APP (LINK_UP,[OBJECT], VALUE)
				values (@LinkOBJ, @linkObjF_PROC, 'SA_RSV_1_14_PFR_PREPARE')		
 
		end
			
  end	
 
end  
GO
IF not exists(select * from dbo.formula_bridge where name = 'РСВ1_14_ПФР_УСТАНОВКА' and PROC_NAME = 'SA_RSV_1_14_PFR_PREPARE')
begin
  	
  IF not exists(select * from dbo.DICTION where name = 'РСВ1_14_ПФР_УСТАНОВКА')
  begin
		-- insert формулы установки в таблицу dbo.DICTION  
		declare @linkObjF int,
				@LinkOBJ int
							
		set @linkObjF  = (select link from dbo.s_objects where code = 'FORMULA_BRIDGE')
  
		insert into  dbo.DICTION (NAME,[OBJECT], CODE, begindate, enddate)
			values ('РСВ1_14_ПФР_УСТАНОВКА', @linkObjF, NULL, '17530101','99991231')

		set @LinkOBJ = (select link from dbo.DICTION where name = 'РСВ1_14_ПФР_УСТАНОВКА')
		
		
		-- insert порядка для формулы в таблицу dbo.DICTION_APP 
		IF not exists(select * from dbo.DICTION_APP where link_up = (select link from dbo.DICTION where name = 'РСВ1_14_ПФР_УСТАНОВКА') and [object] = (select link from s_objects where  code = 'FORMULA_ORDERS'))
		begin	
			declare @linkObjF_ORD int 
					
			set @linkObjF_ORD = (select link from dbo.s_objects where code = 'FORMULA_ORDERS') 
			
			insert into  dbo.DICTION_APP (LINK_UP,[OBJECT], VALUE)
				values (@LinkOBJ, @linkObjF_ORD, '9')		
				
		end
		-- insert процедуры обработки для формулы в таблицу dbo.DICTION_APP 		
		IF not exists(select * from dbo.DICTION_APP where link_up = (select link from dbo.DICTION where name = 'РСВ1_14_ПФР_УСТАНОВКА') and [object] = (select link from s_objects where  code = 'FORMULA_PROCEDURE'))
		begin	
			
			declare @linkObjF_PROC int 
					
			set @linkObjF_PROC = (select link from dbo.s_objects where code = 'FORMULA_PROCEDURE') 
		
			insert into  dbo.DICTION_APP (LINK_UP,[OBJECT], VALUE)
				values (@LinkOBJ, @linkObjF_PROC, 'SA_RSV_1_14_PFR_PREPARE')		
 
		end
			
  end	
 
end   

GO
--Изменение размерности колонки REASON_DOP в таблице ITEM_VACATION
IF COLUMNPROPERTY(object_id('[dbo].[ITEM_VACATION]'), 'REASON_DOP', 'PRECISION')  = 254
	ALTER TABLE [dbo].[ITEM_VACATION] alter column [REASON_DOP] VARCHAR(500) NULL 
GO
GO
/****** Объект: Использовать ОКАТО или ОКТМО******/


DECLARE @T TABLE (LINK INT, CODE VARCHAR(30), FLAG TINYINT)

/******--Запомнить настройки на базе пользователя ******/
INSERT @T (LINK, CODE, FLAG)
SELECT LINK, CODE, 1
FROM  dbo.S_OBJECTS SO WHERE CODE='NASTR_USE_OKATO_OKTMO'

WHILE EXISTS(SELECT * FROM dbo.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM @T WHERE FLAG=1))
BEGIN
	INSERT @T (LINK, CODE,FLAG)
	SELECT LINK, CODE, 0 
	FROM dbo.S_OBJECTS SO WHERE LINK_SELF IN (SELECT LINK FROM @T WHERE FLAG=1)
	UPDATE @T SET FLAG=2 WHERE FLAG=1
	UPDATE @T SET FLAG=1 WHERE FLAG=0
END


IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_NASTR_USE_OKATO_OKTMO]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_NASTR_USE_OKATO_OKTMO]

CREATE TABLE  dbo._UPD_OPT_NASTR_USE_OKATO_OKTMO (CODE VARCHAR(30), [SID] varbinary(85), VALUE VARCHAR(1000))

INSERT INTO _UPD_OPT_NASTR_USE_OKATO_OKTMO (CODE, [SID], VALUE)
SELECT T.CODE, so.[sid], so.VALUE
FROM 
	@T T INNER JOIN dbo.S_OPTIONS so ON so.[OBJECT] = T.LINK

GO

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'NASTR_USE_OKATO_OKTMO')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'NASTR_USE_OKATO_OKTMO')
	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 = 'NASTR_USE_OKATO_OKTMO')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'NASTR_USE_OKATO_OKTMO')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'NASTR_USE_OKATO_OKTMO'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'NASTR_USE_OKATO_OKTMO')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NASTR_USE_OKATO_OKTMO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NASTR_USE_OKATO_OKTMO', 'Использовать ОКАТО или ОКТМО', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='ALL_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NASTR_USE_OKATO_OKTMO', NAME = 'Использовать ОКАТО или ОКТМО', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ALL_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NASTR_USE_OKATO_OKTMO'
GO
EXEC X_SET_PROP 'NASTR_USE_OKATO_OKTMO', 'TITLE', 'Использовать ОКАТО или ОКТМО'
GO
EXEC X_SET_PROP 'NASTR_USE_OKATO_OKTMO', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'NASTR_USE_OKATO_OKTMO', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NASTR_USE_OKATO_OKTMO', 'ROWSOURCE', 'ОКАТО,ОКТМО'
GO
EXEC X_SET_PROP 'NASTR_USE_OKATO_OKTMO', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'NASTR_USE_OKATO_OKTMO', 'TYPE_FIELD_DICT', 'varchar(5)'
GO
EXEC X_SET_PROP 'NASTR_USE_OKATO_OKTMO', 'CONTROL_NAME_EDIT', 'aComboBox3'
GO
EXEC X_SET_PROP 'NASTR_USE_OKATO_OKTMO', 'COMMENTARY', 'Использовать ОКАТО или ОКТМО'
GO
/******--Восстановить, либо установить настройки на базе пользователя ******/
DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'NASTR_USE_OKATO_OKTMO' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_NASTR_USE_OKATO_OKTMO] WHERE CODE = 'NASTR_USE_OKATO_OKTMO')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'NASTR_USE_OKATO_OKTMO'), SID, VALUE = 2 FROM [dbo].[_UPD_OPT_NASTR_USE_OKATO_OKTMO] WHERE CODE = 'NASTR_USE_OKATO_OKTMO'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, 2 FROM  dbo.S_OBJECTS WHERE CODE = 'NASTR_USE_OKATO_OKTMO'

GO


IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_NASTR_USE_OKATO_OKTMO]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_NASTR_USE_OKATO_OKTMO]

GO


/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
/****** Объект: Код спец. оценки условий труда******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COD_SPO_USL_TRUD_NAME')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'COD_SPO_USL_TRUD_NAME')
	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 = 'COD_SPO_USL_TRUD_NAME')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'COD_SPO_USL_TRUD_NAME')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COD_SPO_USL_TRUD_NAME'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COD_SPO_USL_TRUD_NAME')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COD_SPO_USL_TRUD_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COD_SPO_USL_TRUD_NAME', 'Код спец. оценки условий труда', 48, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_STAFF'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COD_SPO_USL_TRUD_NAME', NAME = 'Код спец. оценки условий труда', ORDERS = '48', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_STAFF'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COD_SPO_USL_TRUD_NAME'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_NAME', 'TITLE', 'Код спец. оценки условий труда'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_NAME', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("SA_SZV4_SPR",oForm.ALIAS,"LINK, CODE", "SPO_UT, SPO_UT_N", "", "", "SPR_CODE LIKE ''SPO_USL_TRUDA''", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_NAME', 'CONTROLSOURCE', 'm.cAlias + ".SPO_UT_N"'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(120)'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SPO_UT_N"'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_NAME', 'CONTROL_NAME_EDIT', 'pgf.page3.asel22'
GO
EXEC X_SET_PROP 'COD_SPO_USL_TRUD_NAME', 'COMMENTARY', 'Код спец. оценки условий труда'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
EXEC X_SET_PROP 'DOCUMENTS_PAY_ADD', 'SAVE_OBJECT_METHOD', 'X_SAVE(''X_SAVE_DOCUMENTS_PAY_ADD'', m.cAlias,"SQLNULL(DOH_LINK), SQLNULL(SGU_LINK), OKATO, P_REASON, PERIOD, TREBNUM, SQLNULL(TREBDATE), ZERODATE, P_TYPE,STATUS,UIN_CODE","DOCUMENTS_PAY_ADD")'
GO

GO
/****** Объект: Справочник Да/Нет******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'RB_VIEW_ATR_DA_NET')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'RB_VIEW_ATR_DA_NET')
	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 = 'RB_VIEW_ATR_DA_NET')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'RB_VIEW_ATR_DA_NET')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'RB_VIEW_ATR_DA_NET'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'RB_VIEW_ATR_DA_NET')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RB_VIEW_ATR_DA_NET')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RB_VIEW_ATR_DA_NET', 'Справочник Да/Нет', 116, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_DICTIONARY'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RB_VIEW_ATR_DA_NET', NAME = 'Справочник Да/Нет', ORDERS = '116', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_DICTIONARY'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RB_VIEW_ATR_DA_NET'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RB_VIEW_ATR_DA_NET_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RB_VIEW_ATR_DA_NET_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='RB_VIEW_ATR_DA_NET'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RB_VIEW_ATR_DA_NET_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RB_VIEW_ATR_DA_NET'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RB_VIEW_ATR_DA_NET_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RB_VIEW_ATR_DA_NET_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RB_VIEW_ATR_DA_NET_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='RB_VIEW_ATR_DA_NET'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RB_VIEW_ATR_DA_NET_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RB_VIEW_ATR_DA_NET'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RB_VIEW_ATR_DA_NET_CODE'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET', 'TITLE', 'Справочник Да/Нет'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET', 'INIT_OBJECT_METHOD', 'x_spisok(''RB_VIEW_ATR_DA_NET'')'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET', 'SAVE_OBJECT_METHOD', 'sql.exec("if object_id(''tempdb..#RB_VIEW_ATR_DA_NET'') is not NULL drop table #RB_VIEW_ATR_DA_NETcreate table #RB_VIEW_ATR_DA_NET(link int, CODE varchar(3))", "")
A_SAVE_CURSOR (''#RB_VIEW_ATR_DA_NET'', m.cAlias, '''', ''link,CODE'', ''link,CODE'', ''upd=1'')
sql.call(''dbo.RT_WEB_SAVE_DICT_PRINT'',0,'''')
'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET', 'EDIT_OBJECT_METHOD', 'x_brow()'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET', 'SELECT_RECORDS_METHOD', 'sql.exec(''select 0 as checked, 0 as upd, 0 as del, * from RB_VIEW_ATR_DA_NET'',m.cAlias)'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET', 'SELECT_RECORDS_METHOD_EDIT', 'sql.exec(''select 0 as checked, 0 as upd, 0 as del, * from RB_VIEW_ATR_DA_NET where Link = '' + STR(m.nLink),m.cAlias)'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET', 'OPEN_CODE', 'TYPE'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET', 'MSG_SEL_ONE', 'IIF(ISNULL(TYPE),'''', TYPE) + [-] + IIF(ISNULL(NUMB), '''', NUMB)'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET', 'SERVER_TABLE_NAME', ''
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET', 'EDIT_OBJECT_METHOD_SQL', 'KU_EDIT_OBJECT_METHOD @cObject = ''RB_VIEW_ATR_DA_NET'''
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''RB_VIEW_ATR_DA_NET'''
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET', 'SAVE_OBJECT_METHOD_SQL', 'RT_WEB_SAVE_DICT_PRINT'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET', 'EXCH_MODEL_CODE', 'L'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET', 'EXCHANGE', '1'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET_MARKER', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET_MARKER', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET_MARKER', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET_MARKER', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET_MARKER', 'CONTROL_NAME_EDIT', 'check1'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET_MARKER', 'ASPTYPE', 'checkbox'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET_MARKER', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET_CODE', 'CONTROL_NAME_EDIT', 'ATxt1'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET_CODE', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET_CODE', 'ATTRIBUTES', 'style="Z-INDEX: 102; LEFT: 250px; POSITION: absolute; TOP: 16px""
Width="500px"'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET_CODE', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 101; LEFT: 24px; POSITION: absolute; TOP: 16px"'
GO
EXEC X_SET_PROP 'RB_VIEW_ATR_DA_NET_CODE', 'FIELD_DATA', 'NAME'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'RB_VIEW_ATR_DA_NET', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'RB_VIEW_ATR_DA_NET', 'Свод-КС', 63,0
GO


GO
/****** Объект: Да/Нет******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_INCR_ITOG')
	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_INCR_ITOG')
	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_INCR_ITOG')
	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_INCR_ITOG')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_INCR_ITOG'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_INCR_ITOG')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORTS_ATR_INCR_ITOG')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORTS_ATR_INCR_ITOG', 'Да/Нет', 53, (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_INCR_ITOG', NAME = 'Да/Нет', ORDERS = '53', 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_INCR_ITOG'
GO
EXEC X_SET_PROP 'REPORTS_ATR_INCR_ITOG', 'NAME', 'Расчет с нарастающим итогом'
GO
EXEC X_SET_PROP 'REPORTS_ATR_INCR_ITOG', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("RB_VIEW_ATR_DA_NET",oForm.ALIAS_ATR, "CODE", "REPORTS_ATR_INCR_ITOG", "", "", "", .T., 0, oForm, oObj)'
GO
EXEC X_SET_PROP 'REPORTS_ATR_INCR_ITOG', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORTS_ATR_INCR_ITOG', 'CONTROL_TYPE', '1'
GO
EXEC X_SET_PROP 'REPORTS_ATR_INCR_ITOG', 'SHORT_NAME', 'Расчет с нарастающим итогом'
GO
EXEC X_SET_PROP 'REPORTS_ATR_INCR_ITOG', 'CHECK_WHEN', 'ALIB_NEED_SPR (oObj)'
GO
EXEC X_SET_PROP 'REPORTS_ATR_INCR_ITOG', 'DEFAULT_VALUE', 'Да'
GO
EXEC X_SET_PROP 'REPORTS_ATR_INCR_ITOG', 'MAXWIDTH', '11'
GO
EXEC X_SET_PROP 'REPORTS_ATR_INCR_ITOG', 'DICTIONARY', 'RB_VIEW_ATR_DA_NET'
GO
EXEC X_SET_PROP 'REPORTS_ATR_INCR_ITOG', 'DICTIONARY_COLUMNS_LIST', 'REPORTS_ATR_INCR_ITOG'
GO
EXEC X_SET_PROP 'REPORTS_ATR_INCR_ITOG', 'DICTIONARY_FIELDS_LIST', 'CODE'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'REPORTS_ATR_INCR_ITOG', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'REPORTS_ATR_INCR_ITOG', 'Свод-КС', 63,0
GO


GO
/****** Объект: Номер расчета Перс. Учета******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_PERS_UCH')
	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_PERS_UCH')
	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_PERS_UCH')
	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_PERS_UCH')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_PERS_UCH'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_PERS_UCH')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORTS_ATR_PERS_UCH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORTS_ATR_PERS_UCH', 'Номер расчета Перс. Учета', 53, (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_PERS_UCH', 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_PERS_UCH'
GO
EXEC X_SET_PROP 'REPORTS_ATR_PERS_UCH', 'NAME', 'Расчет по перс. учету'
GO
EXEC X_SET_PROP 'REPORTS_ATR_PERS_UCH', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("SA_SZV4_PACHKA",oForm.ALIAS_ATR, "ALLTRIM(STR(link))", "REPORTS_ATR_PERS_UCH", "", "", " YEAR_BEGIN >=''2014'' and VID_KOR = 1 and PROVERKA = 1 ", .T., 0, oForm, oObj)'
GO
EXEC X_SET_PROP 'REPORTS_ATR_PERS_UCH', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORTS_ATR_PERS_UCH', 'CONTROL_TYPE', '1'
GO
EXEC X_SET_PROP 'REPORTS_ATR_PERS_UCH', 'SHORT_NAME', 'Расчет по перс. учету'
GO
EXEC X_SET_PROP 'REPORTS_ATR_PERS_UCH', 'CHECK_WHEN', 'ALIB_NEED_SPR (oObj)'
GO
EXEC X_SET_PROP 'REPORTS_ATR_PERS_UCH', 'DEFAULT_VALUE', ''
GO
EXEC X_SET_PROP 'REPORTS_ATR_PERS_UCH', 'MAXWIDTH', '11'
GO
EXEC X_SET_PROP 'REPORTS_ATR_PERS_UCH', 'DICTIONARY', 'SA_SZV4_PACHKA'
GO
EXEC X_SET_PROP 'REPORTS_ATR_PERS_UCH', 'DICTIONARY_COLUMNS_LIST', 'REPORTS_ATR_PERS_UCH'
GO
EXEC X_SET_PROP 'REPORTS_ATR_PERS_UCH', 'DICTIONARY_FIELDS_LIST', 'LINK'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'REPORTS_ATR_PERS_UCH', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'REPORTS_ATR_PERS_UCH', 'Свод-КС', 63,0
GO


GO


/*НАСТРОЙКИ ДОП ТАРИФОВ  2014 ГОДА Со спец оценкой*/
--Общий (НР)
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "О4"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1 AND SpecO = 2)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'О4')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1 AND SpecO = 2
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "О4"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1 AND SpecO = 2)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'О4')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1 AND SpecO = 2
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.4"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1  AND SpecO = 3)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.4')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1  AND SpecO = 3

GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.4"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1  AND SpecO = 3)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.4')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1  AND SpecO = 3
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.3"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1  AND SpecO = 4)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.3')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1  AND SpecO = 4
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.3"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1  AND SpecO = 4)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.3')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1  AND SpecO = 4
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.2"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1  AND SpecO = 5)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.2')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1  AND SpecO = 5
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.2"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1  AND SpecO = 5)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.2')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1  AND SpecO = 5
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.1"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1  AND SpecO = 6)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.1')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1  AND SpecO = 6
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.1"
IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1  AND SpecO = 6)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.1')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1  AND SpecO = 6
GO


--Инвалиды (ОЗОИ)
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "О4"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3  AND SpecO = 2)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'О4')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3  AND SpecO = 2
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "О4"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3  AND SpecO = 2)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'О4')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3  AND SpecO = 2
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.4"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3  AND SpecO = 3)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.4')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3  AND SpecO = 3
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.4"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3  AND SpecO = 3)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.4')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3  AND SpecO = 3
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.3"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3 AND SpecO = 4)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.3')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3 AND SpecO = 4
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.3"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3 AND SpecO = 4)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.3')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3 AND SpecO = 4
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.2"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3  AND SpecO = 5)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.2')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3  AND SpecO = 5
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.2"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3  AND SpecO = 5)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.2')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3  AND SpecO = 5
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.1"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3  AND SpecO = 6)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.1')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3  AND SpecO = 6
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.1"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3  AND SpecO = 6)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.1')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3  AND SpecO = 6
GO

--Упрощён. (ПНЭД)

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "О4"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2  AND SpecO = 2)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'О4')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2  AND SpecO = 2
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "О4"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2  AND SpecO = 2)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'О4')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2  AND SpecO = 2
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.4"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2  AND SpecO = 3)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.4')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2  AND SpecO = 3
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.4"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2  AND SpecO = 3)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.4')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2  AND SpecO = 3
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.3"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2 AND SpecO = 4)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.3')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2 AND SpecO = 4
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.3"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2 AND SpecO = 4)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.3')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2 AND SpecO = 4
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.2"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2  AND SpecO = 5)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.2')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2  AND SpecO = 5
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.2"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2  AND SpecO = 5)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.2')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2  AND SpecO = 5
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.1"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2  AND SpecO = 6)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.1')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2  AND SpecO = 6
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.1"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2  AND SpecO = 6)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.1')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2  AND SpecO = 6
GO


--СМИ(СМИ)

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "О4"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4  AND SpecO = 2)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'О4')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4  AND SpecO = 2
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "О4"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4  AND SpecO = 2)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'О4')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4  AND SpecO = 2
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.4"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4  AND SpecO = 3)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.4')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4  AND SpecO = 3
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.4"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4  AND SpecO = 3)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.4')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4  AND SpecO = 3
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.3"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4 AND SpecO = 4)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.3')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4 AND SpecO = 4
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.3"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4 AND SpecO = 4)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.3')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4 AND SpecO = 4
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.2"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4 AND SpecO = 5)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.2')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4 AND SpecO = 5
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.2"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4 AND SpecO = 5)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.2')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4 AND SpecO = 5
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.1"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4 AND SpecO = 6)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.1')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4 AND SpecO = 6
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.1"

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4 AND SpecO = 6)	
UPDATE a
SET SpecO =  (SELECT link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.1')
from dbo.stavki_pf a where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4 AND SpecO = 6
GO




GO

GO
/****** Объект: Процент******/
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'ESN_T1_PERC')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'ESN_T1_PERC')
	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 = 'ESN_T1_PERC')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'ESN_T1_PERC')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'ESN_T1_PERC'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'ESN_T1_PERC')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ESN_T1_PERC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ESN_T1_PERC', 'Процент', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DEDUCT_ESN_TABLE1_G'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ESN_T1_PERC', NAME = 'Процент', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DEDUCT_ESN_TABLE1_G'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ESN_T1_PERC'
GO
EXEC X_SET_PROP 'ESN_T1_PERC', 'TITLE', 'Процент'
GO
EXEC X_SET_PROP 'ESN_T1_PERC', 'ORDER_NUMBER', '10'
GO
EXEC X_SET_PROP 'ESN_T1_PERC', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'ESN_T1_PERC', 'CONTROLSOURCE', 'm.cAlias + ".PERC"'
GO
EXEC X_SET_PROP 'ESN_T1_PERC', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ESN_T1_PERC', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'ESN_T1_PERC', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'ESN_T1_PERC', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".PERC"'
GO
EXEC X_SET_PROP 'ESN_T1_PERC', 'INPUT_MASK', '999 999 999.99'
GO

/****** Объект: Тариф******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'ESN_T1_TARIF')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'ESN_T1_TARIF')
	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 = 'ESN_T1_TARIF')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'ESN_T1_TARIF')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'ESN_T1_TARIF'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'ESN_T1_TARIF')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ESN_T1_TARIF')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ESN_T1_TARIF', 'Тариф', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DEDUCT_ESN_TABLE1_G'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ESN_T1_TARIF', NAME = 'Тариф', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DEDUCT_ESN_TABLE1_G'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ESN_T1_TARIF'
GO
EXEC X_SET_PROP 'ESN_T1_TARIF', 'TITLE', 'Тариф'
GO
EXEC X_SET_PROP 'ESN_T1_TARIF', 'ORDER_NUMBER', '10'
GO
EXEC X_SET_PROP 'ESN_T1_TARIF', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'ESN_T1_TARIF', 'CONTROLSOURCE', 'm.cAlias + ".TARIF"'
GO
EXEC X_SET_PROP 'ESN_T1_TARIF', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ESN_T1_TARIF', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'ESN_T1_TARIF', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'ESN_T1_TARIF', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TARIF"'
GO
EXEC X_SET_PROP 'ESN_T1_TARIF', 'INPUT_MASK', '99'
GO

/****** Объект: Спец.оц.******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'ESN_T1_NSPECO')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'ESN_T1_NSPECO')
	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 = 'ESN_T1_NSPECO')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'ESN_T1_NSPECO')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'ESN_T1_NSPECO'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'ESN_T1_NSPECO')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ESN_T1_NSPECO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ESN_T1_NSPECO', 'Спец.оц.', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DEDUCT_ESN_TABLE1_G'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ESN_T1_NSPECO', NAME = 'Спец.оц.', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DEDUCT_ESN_TABLE1_G'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ESN_T1_NSPECO'
GO
EXEC X_SET_PROP 'ESN_T1_NSPECO', 'TITLE', 'Спец.оц.'
GO
EXEC X_SET_PROP 'ESN_T1_NSPECO', 'ORDER_NUMBER', '2'
GO
EXEC X_SET_PROP 'ESN_T1_NSPECO', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'ESN_T1_NSPECO', 'CONTROLSOURCE', 'm.cAlias + ".NSPECO"'
GO
EXEC X_SET_PROP 'ESN_T1_NSPECO', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'ESN_T1_NSPECO', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'ESN_T1_NSPECO', 'CONTROLSOURCE_EDIT', 'm.cAlias+ ".NSPECO"'
GO

GO
/****** Объект: Наименование спец. оценки условий труда******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_STAZH_N_OSOB_SPO')
	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_SZV4_STAZH_N_OSOB_SPO')
	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_SZV4_STAZH_N_OSOB_SPO')
	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_SZV4_STAZH_N_OSOB_SPO')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_STAZH_N_OSOB_SPO'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_STAZH_N_OSOB_SPO')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV4_STAZH_N_OSOB_SPO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV4_STAZH_N_OSOB_SPO', 'Наименование спец. оценки условий труда', 32, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV4_STAZH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV4_STAZH_N_OSOB_SPO', NAME = 'Наименование спец. оценки условий труда', ORDERS = '32', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV4_STAZH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV4_STAZH_N_OSOB_SPO'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_N_OSOB_SPO', 'TITLE', 'Наименование спец. оценки условий труда'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_N_OSOB_SPO', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_N_OSOB_SPO', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_N_OSOB_SPO', 'CONTROLSOURCE', 'm.cAlias + ".n_osob_spo"'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_N_OSOB_SPO', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_N_OSOB_SPO', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_N_OSOB_SPO', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".n_osob_spo"'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_N_OSOB_SPO', 'CONTROL_NAME_EDIT', 'apageframe1.Page2.aTextBox16'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
/****** Объект: Код спец. оценки условий труда******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_STAZH_OSOB_SPO')
	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_SZV4_STAZH_OSOB_SPO')
	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_SZV4_STAZH_OSOB_SPO')
	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_SZV4_STAZH_OSOB_SPO')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_STAZH_OSOB_SPO'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_STAZH_OSOB_SPO')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV4_STAZH_OSOB_SPO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV4_STAZH_OSOB_SPO', 'Код спец. оценки условий труда', 31, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV4_STAZH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV4_STAZH_OSOB_SPO', NAME = 'Код спец. оценки условий труда', ORDERS = '31', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV4_STAZH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV4_STAZH_OSOB_SPO'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_OSOB_SPO', 'TITLE', 'Код спец. оценки условий труда'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_OSOB_SPO', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_OSOB_SPO', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SA_SZV4_SPR'', oForm.ALIAS, ''CODE,NAME'', ''osob_spo,n_osob_spo'', '''', '''', "SPR_CODE = ''SPO_USL_TRUDA'' and DATE BETWEEN DATE1 AND COALESCE(DATE2,''30000101'')", .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_OSOB_SPO', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_OSOB_SPO', 'CONTROLSOURCE', 'm.cAlias + ".osob_spo"'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_OSOB_SPO', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_OSOB_SPO', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_OSOB_SPO', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_OSOB_SPO', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".osob_spo"'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_OSOB_SPO', 'CONTROL_NAME_EDIT', 'apageframe1.Page2.Asel_spr15'
GO


/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
-- Заявка на финансирование (FB_ZAYAVKA) --
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA', 'Заявка на финансирование', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_FINANSE_PLAN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA', NAME = 'Заявка на финансирование', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_FINANSE_PLAN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='FB_ZAYAVKA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_DEP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_DEP_NAME', 'Организация', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_DEP_NAME', NAME = 'Организация', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_DEP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_PDEP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_PDEP_NAME', 'Получатель', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_PDEP_NAME', NAME = 'Получатель', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_PDEP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_PACC_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_PACC_CODE', 'Счет получателя', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_PACC_CODE', NAME = 'Счет получателя', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_PACC_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_ODEP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_ODEP_NAME', 'Отправитель', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_ODEP_NAME', NAME = 'Отправитель', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_ODEP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_OACC_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_OACC_CODE', 'Счет отправителя', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_OACC_CODE', NAME = 'Счет отправителя', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_OACC_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_COMMENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_COMMENT', 'Комментарий', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_COMMENT', NAME = 'Комментарий', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_COMMENT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_NUM_REESTR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_NUM_REESTR', 'Номер реестра', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_NUM_REESTR', NAME = 'Номер реестра', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_NUM_REESTR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_DOC_SUMMA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_DOC_SUMMA', 'Сумма по документу', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_DOC_SUMMA', NAME = 'Сумма по документу', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_DOC_SUMMA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_PLAN_TABLE', 'Таблица сумм', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_PLAN_TABLE', NAME = 'Таблица сумм', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_PLAN_TABLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_OPTIONS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_OPTIONS', 'Настройки заявки на финансирование', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_OPTIONS', NAME = 'Настройки заявки на финансирование', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_OPTIONS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_TABLE_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_TABLE_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_TABLE_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_TABLE_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_TABLE_VKR_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_TABLE_VKR_CODE', 'Код КБК', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_TABLE_VKR_CODE', NAME = 'Код КБК', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_TABLE_VKR_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_TABLE_VKR_NAME_')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_TABLE_VKR_NAME_', 'Наименование КБК', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_TABLE_VKR_NAME_', NAME = 'Наименование КБК', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_TABLE_VKR_NAME_'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_TABLE_EKR_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_TABLE_EKR_CODE', 'Код ЭКР', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_TABLE_EKR_CODE', NAME = 'Код ЭКР', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_TABLE_EKR_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_TABLE_EKR_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_TABLE_EKR_NAME', 'Наименование ЭКР', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_TABLE_EKR_NAME', NAME = 'Наименование ЭКР', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_TABLE_EKR_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_TABLE_DOP_CL_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_TABLE_DOP_CL_CODE', 'Код Доп. классификации', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_TABLE_DOP_CL_CODE', NAME = 'Код Доп. классификации', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_TABLE_DOP_CL_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_TABLE_DOP_CL_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_TABLE_DOP_CL_NAME', 'Наименование Доп. классификации', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_TABLE_DOP_CL_NAME', NAME = 'Наименование Доп. классификации', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_TABLE_DOP_CL_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_TABLE_SUMMA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_TABLE_SUMMA', 'Сумма по документу', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_TABLE_SUMMA', NAME = 'Сумма по документу', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_TABLE_SUMMA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_TABLE_TITLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_TABLE_TITLE', 'Примечание', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_TABLE_TITLE', NAME = 'Примечание', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_PLAN_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_TABLE_TITLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_OPTIONS_PERIOD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FB_ZAYAVKA_OPTIONS_PERIOD', 'Период', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FB_ZAYAVKA_OPTIONS_PERIOD', NAME = 'Период', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FB_ZAYAVKA_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FB_ZAYAVKA_OPTIONS_PERIOD'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA', 'TITLE', 'Заявка на финансирование'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA', 'INIT_OBJECT_METHOD', 'FB_SPISOK_FINANS(m.Obj_Code)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "FB_ZAYAVKA", "BV_DELETE_DOCUMENTS", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA', 'SAVE_OBJECT_METHOD', 'X_SAVE ("FB_SAVE_ZAYAVKA ", m.cAlias,"SQLNULL(DATE), SQLNULL(DATE_PROV),NUMBER,  Summa, Comment, dep_link, acc_link, kacc_link,SQLNULL(link_reestr),IS_RBS","FB_ZAYAVKA")'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA', 'PRINT_OBJECT_METHOD', 'FB_PRINT_DOC(3)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA', 'EDIT_OBJECT_METHOD', 'finans_RBS_brow(''FB_PLAN'')'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_LIST_ZB("FB_ZAYAVKA")'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST("FB_ZAYAVKA")'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA', 'SNAME', 'Заявка на финансирование'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA', 'QUERY_REPORT', 'FB_ZAYAVKA.XLT'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA', 'OPTIONS_OBJECT_CODE', 'FB_ZAYAVKA_OPTIONS'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA', 'HELP_TOPIC', '64'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA', 'PREPARE_NEW_RECORD', 'v_new_findoc_rec(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA', 'EXCH_MODEL_CODE', 'ZF'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA', 'EXCHANGE', '1'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_DEP_NAME', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_DEP_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_DEP_NAME', 'CONTROLSOURCE', 'm.cAlias + ".DEP_NAME"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_DEP_NAME', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_DEP_NAME', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_DEP_NAME', 'TYPE_FIELD_DICT', 'varchar(100)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_DEP_NAME', 'SHORT_CODE_OBJ', 'DEP_NAME'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_DEP_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_PDEP_NAME', 'TITLE', 'Получатель'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_PDEP_NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_PDEP_NAME', 'CONTROLSOURCE', 'm.cAlias + ".PDEP_NAME"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_PDEP_NAME', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_PDEP_NAME', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_PDEP_NAME', 'TYPE_FIELD_DICT', 'varchar(100)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_PDEP_NAME', 'SHORT_CODE_OBJ', 'PDEP_NAME'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_PDEP_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".PDEP_NAME"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_PACC_CODE', 'TITLE', 'Счет получателя'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_PACC_CODE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_PACC_CODE', 'CONTROLSOURCE', 'm.cAlias + ".PACC_CODE"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_PACC_CODE', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_PACC_CODE', 'TYPE_FIELD_DICT', 'varchar(100)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_PACC_CODE', 'SHORT_CODE_OBJ', 'PACC_CODE'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_PACC_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".PACC_CODE"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_ODEP_NAME', 'TITLE', 'Отправитель'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_ODEP_NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_ODEP_NAME', 'CONTROLSOURCE', 'm.cAlias + ".ODEP_NAME"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_ODEP_NAME', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_ODEP_NAME', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_ODEP_NAME', 'TYPE_FIELD_DICT', 'varchar(100)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_ODEP_NAME', 'SHORT_CODE_OBJ', 'ODEP_NAME'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_ODEP_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ODEP_NAME"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OACC_CODE', 'TITLE', 'Счет отправителя'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OACC_CODE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OACC_CODE', 'CONTROLSOURCE', 'm.cAlias + ".OACC_CODE"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OACC_CODE', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OACC_CODE', 'TYPE_FIELD_DICT', 'varchar(100)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OACC_CODE', 'SHORT_CODE_OBJ', 'OACC_CODE'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OACC_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".OACC_CODE"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_COMMENT', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_COMMENT', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_COMMENT', 'CONTROLSOURCE', 'm.cAlias+".COMMENT"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_COMMENT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_COMMENT', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_COMMENT', 'STORAGE', 'G_PROV'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_COMMENT', 'TYPE_FIELD_DICT', 'varchar(1000)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_COMMENT', 'SHORT_CODE_OBJ', 'COMMENT'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_COMMENT', 'CONTROLSOURCE_EDIT', 'm.cAlias+".COMMENT"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_COMMENT', 'CONTROL_NAME_EDIT', 'aEditComment7'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_NUM_REESTR', 'TITLE', 'Реестр №'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_NUM_REESTR', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("FB_ZAYAVKA_S", oForm.ALIAS, "NUMBER,LINK", "NUM_REESTR,LINK_REESTR", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_NUM_REESTR', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_NUM_REESTR', 'CONTROLSOURCE', 'm.cAlias+".NUM_REESTR"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_NUM_REESTR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_NUM_REESTR', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NUM_REESTR"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_NUM_REESTR', 'CONTROL_NAME_EDIT', 'Asel_Spr4'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_NUM_REESTR', 'AUTO_FILL_CONTEXT', '1#Да#Нет'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_DOC_SUMMA', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_DOC_SUMMA', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_DOC_SUMMA', 'CONTROLSOURCE', 'm.cAlias+''.SUMMA'''
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_DOC_SUMMA', 'SHORT_CODE_OBJ', 'SUMMA'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_DOC_SUMMA', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.SUMMA'''
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_DOC_SUMMA', 'CONTROL_NAME_EDIT', 'parent.parent.ATxtN9'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_DOC_SUMMA', 'INPUT_MASK', '99 999 999 999.99'
GO
EXEC X_SET_PROP 'FB_PLAN_TABLE', 'SAVE_OBJECT_METHOD', 'x_save(''FB_SAVE_PLAN_TABLE'', m.cAlias, ''LINK_UP, VKR, EKR, SQLNULL(DOP_CL), SUMMA, TITLE'', ''FB_PLAN_TABLE'')'
GO
EXEC X_SET_PROP 'FB_PLAN_TABLE', 'CLOSE_CODE', ''
GO
EXEC X_SET_PROP 'FB_PLAN_TABLE', 'SELECT_RECORDS_METHOD', 'SQL.EXEC(''SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, * FROM dbo.FB_PLAN_TABLE WHERE LINK_UP = '' + STR(m.nLink), m.cAlias) > 0'
GO
EXEC X_SET_PROP 'FB_PLAN_TABLE', 'SERVER_TABLE_NAME', 'FINANSE_PLAN_SUMM'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OPTIONS', 'TITLE', 'Настройки'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OPTIONS', 'SAVE_OBJECT_METHOD', 'X_SAVE_DOCUMENT_OPTIONS()'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OPTIONS', 'EDIT_OBJECT_METHOD', 'finans_brow(''FB_ZAYAVKA_OPTIONS'')'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OPTIONS', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_OPTIONS(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_CHECKED', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_CHECKED', 'CONTROLSOURCE', 'm.cAlias+''.CHECKED'''
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_CHECKED', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_VKR_CODE', 'TITLE', 'КБК'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_VKR_CODE', 'EDIT_OBJECT_METHOD', 'fb_table_vibor ("BI_DICTION_KBK", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE,NAME,LINK_ADM", "VKR, VKR_CODE, VKR_NAME,KBK_ADM", "", "", "", .T., 1, oForm, oObj,,,)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_VKR_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_VKR_CODE', 'CONTROLSOURCE', 'm.cAlias + ".VKR_CODE"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_VKR_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_VKR_CODE', 'STORAGE', 'KL_KBK'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_VKR_CODE', 'TYPE_FIELD_DICT', 'char(5)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_VKR_CODE', 'SHORT_CODE_OBJ', 'VKR_CODE'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_VKR_NAME_', 'TITLE', 'Наименование КБК'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_VKR_NAME_', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_VKR_NAME_', 'CONTROLSOURCE', 'm.cAlias + ".VKR_NAME"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_VKR_NAME_', 'STORAGE', 'KL_KBK'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_VKR_NAME_', 'TYPE_FIELD_DICT', 'varchar(100)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_VKR_NAME_', 'SHORT_CODE_OBJ', 'VKR_NAME'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_VKR_NAME_', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_EKR_CODE', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_EKR_CODE', 'EDIT_OBJECT_METHOD', 'fb_table_vibor ("DICTIONARY_ITEM", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "EKR, EKR_CODE, SGU_NAME", "", "", "", .T., 1, oForm, oObj,,,)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_EKR_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_EKR_CODE', 'CONTROLSOURCE', 'm.cAlias + ".EKR_CODE"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_EKR_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_EKR_CODE', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_EKR_CODE', 'TYPE_FIELD_DICT', 'char(6)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_EKR_CODE', 'SHORT_CODE_OBJ', 'EKR_CODE'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_EKR_NAME', 'TITLE', 'Наименование ЭКР'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_EKR_NAME', 'CONTROLSOURCE', 'm.cAlias + ".EKR_NAME"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_EKR_NAME', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_EKR_NAME', 'TYPE_FIELD_DICT', 'varchar(100)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_EKR_NAME', 'SHORT_CODE_OBJ', 'EKR_NAME'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_DOP_CL_CODE', 'TITLE', 'Доп. классификация'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_DOP_CL_CODE', 'EDIT_OBJECT_METHOD', 'fb_table_vibor ("BD_DOP_CLASSIF", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "DOP_CL, DOP_CODE, DOP_NAME", "", "", "", .T., 1, oForm, oObj,,,)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_DOP_CL_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_DOP_CL_CODE', 'CONTROLSOURCE', 'm.cAlias + ".DOP_CODE"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_DOP_CL_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_DOP_CL_CODE', 'STORAGE', 'DOP_CLASSIF'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_DOP_CL_CODE', 'TYPE_FIELD_DICT', 'char(5)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_DOP_CL_CODE', 'SHORT_CODE_OBJ', 'DOP_CODE'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_DOP_CL_NAME', 'TITLE', 'Наименование Доп. классификациюи'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_DOP_CL_NAME', 'CONTROLSOURCE', 'm.cAlias + ".DOP_NAME"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_DOP_CL_NAME', 'STORAGE', 'DOP_CLASSIF'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_DOP_CL_NAME', 'TYPE_FIELD_DICT', 'varchar(100)'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_DOP_CL_NAME', 'SHORT_CODE_OBJ', 'DOP_NAME'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_SUMMA', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_SUMMA', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_SUMMA', 'CONTROLSOURCE', 'm.cAlias+''.SUMMA'''
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_SUMMA', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_SUMMA', 'SHORT_CODE_OBJ', 'SUMMA'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_SUMMA', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.SUMMA'''
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_SUMMA', 'INPUT_MASK', '9999999999999.99'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_TITLE', 'TITLE', 'Примечание'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_TITLE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_TITLE', 'CONTROLSOURCE', 'm.cAlias+''.TITLE'''
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_TITLE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_TITLE', 'SHORT_CODE_OBJ', 'TITLE'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_TABLE_TITLE', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.TITLE'''
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OPTIONS_PERIOD', 'TITLE', 'Период ведения документа'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OPTIONS_PERIOD', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OPTIONS_PERIOD', 'CONTROLSOURCE', 'm.cAlias + ".PERIOD"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OPTIONS_PERIOD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OPTIONS_PERIOD', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OPTIONS_PERIOD', 'TYPE_FIELD_DICT', 'tinyint'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OPTIONS_PERIOD', 'SHORT_CODE_OBJ', 'PERIOD'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OPTIONS_PERIOD', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".PERIOD"'
GO
EXEC X_SET_PROP 'FB_ZAYAVKA_OPTIONS_PERIOD', 'CONTROL_NAME_EDIT', 'ogrp1'
GO


GO
IF exists(select * from sysobjects where id = object_id('[dbo].[SPEC_OCENKA_USLT_RUD]'))
BEGIN
	IF NOT EXISTS(SELECT * FROM dbo.SPEC_OCENKA_USLT_RUD)
	BEGIN 
		INSERT INTO dbo.SPEC_OCENKA_USLT_RUD ([LINK1], [CODE] ,[YBEG],[YEND], [NAME])
		VALUES (1,'',2014,2999, '')
		INSERT INTO dbo.SPEC_OCENKA_USLT_RUD ([LINK1], [CODE] ,[YBEG],[YEND], [NAME])
		VALUES (2,'О4',2014,2999, 'Класс условий труда - опасный; Подкласс условий труда - 4')
		INSERT INTO dbo.SPEC_OCENKA_USLT_RUD ([LINK1], [CODE] ,[YBEG],[YEND], [NAME])
		VALUES (3,'В3.4',2014,2999, 'Класс условий труда - вредный; Подкласс условий труда - 3.4 (вредные условия труда 4-й степени)')
		INSERT INTO dbo.SPEC_OCENKA_USLT_RUD ([LINK1], [CODE] ,[YBEG],[YEND], [NAME])
		VALUES (4,'В3.3',2014,2999, 'Класс условий труда – вредный; Подкласс условий труда – 3.3 (вредные условия труда 3-й степени)')
		INSERT INTO dbo.SPEC_OCENKA_USLT_RUD ([LINK1], [CODE] ,[YBEG],[YEND], [NAME])
		VALUES (5,'В3.2',2014,2999, 'Класс условий труда – вредный; Подкласс условий труда – 3.2 (вредные условия труда 2-й степени)')
		INSERT INTO dbo.SPEC_OCENKA_USLT_RUD ([LINK1], [CODE] ,[YBEG],[YEND], [NAME])
		VALUES (6,'В3.1',2014,2999, 'Класс условий труда – вредный; Подкласс условий труда – 3.1 (вредные условия труда 1-й степени)')
	END
END				



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'),
							'Вкл.'
						
						
						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'),
							'Вкл.'
						
						
						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'),
							'Вкл.'
						
						
						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'),
							'Вкл.'
						
						
						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'),
							'Вкл.'
						
						
						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'),
							'Вкл.'
						
						
						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'),
							'Вкл.'
						
						
						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'),
							'Вкл.'
						
						
						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'),
							'Вкл.'
						
						
						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'),
							'01.10.2011'
						
						
						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'),
							'Начало расч. месяца'
						
						
						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'),
							'01.03.2011'
						
						
						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'),
							'01.01.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_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'),
							'31.10.2011'
						
						
						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'),
							'Конец расч. месяца'
						
						
						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'),
							'31.03.2011'
						
						
						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'),
							'31.10.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_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'),
							'размеру дохода'
						
						
						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'),
							'размеру дохода'
						
						
						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'),
							'размеру дохода'
						
						
						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'),
							'Выкл.'
						
						
						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'),
							'Выкл.'
						
						
						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'),
							'Выкл.'
						
						
						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'),
							'Вкл.'
						
						
						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'),
							'Вкл.'
						
						
						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'),
							'Вкл.'
						
						
						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'),
							'Выкл.'
						
						
						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'),
							'Выкл.'
						
						
						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'),
							'Выкл.'
						
						
						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'),
							'Выкл.'
						
						
						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'),
							'Выкл.'
						
						
						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'),
							'Выкл.'
						
						
						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


GO
-- Отчет "Справка об уплаченных суммах доп. страх. взносов на накопит. часть пенсии"
-- Сгенерировано скриптом scriptObjectVar 'SQL_REP_SPR_DOP_VZNOS'

/*** Сам отчет ***/

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_SPR_DOP_VZNOS'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'SQL_REP_SPR_DOP_VZNOS'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'Справка об уплаченных суммах доп. страх. взносов на накопит. часть пенсии',NULL, 
	(Select link from object_var where code = 'SQL_REPORT_CATALOG_SALARY'),
	'SQL_REP_SPR_DOP_VZNOS',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'SQL_REP_SPR_DOP_VZNOS') 
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_DATETIME'),
	VALUE= '0'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_FREEZEPANES'),
	VALUE= '0'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_PAGES'),
	VALUE= '0'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'EXEC dbo.SS_SPR_DOP_VZNOS
	@cYear1					/* Расчетный год */,
	@nSel_Spr1 /*Отбор сотрудника*/,
    @cText1 /* Номер справки */
'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_DATETIME'),
	VALUE= '0'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_DISTINCT'),
	VALUE= '0'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_FREEZEPANES'),
	VALUE= '0'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PAGES'),
	VALUE= '0'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#SS_SPR_DOP_VZNOS'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(spr_dop_prepare_report(),"SS_SPR_DOP_VZNOS.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #SS_SPR_DOP_VZNOS
	@nSel_Spr1 int	/* Сотрудник */,
	@cYear1 VARCHAR(4)	/* Расчетный год */,
	@cText1 varchar(8)	/* Номер справки */
AS
BEGIN

EXEC dbo.SS_SPR_DOP_VZNOS
	@cYear1					/* Расчетный год */,
	@nSel_Spr1 /*Отбор сотрудника*/,
    @cText1 /* Номер справки */


END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	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_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADD_MODULE'),
	VALUE= 'KirRepCommon.bas'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_CODE')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_CODE'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_DATE_TYPE')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_DATE_TYPE'),
	VALUE= '0'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS') and  PROPERTY = (Select LINK from s_property where code = 'SQUERY_NO_SHOW')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS'),
	PROPERTY= (Select LINK from s_property where code = 'SQUERY_NO_SHOW'),
	VALUE= '0'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_ALTERNATIVE_PRINT_METHOD')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ALTERNATIVE_PRINT_METHOD'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SPR_DOP_VZNOS') 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_SPR_DOP_VZNOS'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'SQL_REP_SPR_DOP_VZNOS_NASTR' 
		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_SPR_DOP_VZNOS'),
		'SQL_REP_SPR_DOP_VZNOS_NASTR',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SPR_DOP_VZNOS_MAIN_PARAM' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_LSEL_SPR'),
					'Сотрудник',2, 
					(Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_NASTR'),
					'SQL_REP_SPR_DOP_VZNOS_MAIN_PARAM',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_SPR_DOP_VZNOS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_MAIN_PARAM'),
							(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_SPR_DOP_VZNOS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'1'
						
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_SPR_DOP_VZNOS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_MAIN_PARAM'),
							(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_SPR_DOP_VZNOS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_MAIN_PARAM'),
							(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_SPR_DOP_VZNOS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'LSel_Spr'
						
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_SPR_DOP_VZNOS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_MAIN_PARAM'),
							(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_SPR_DOP_VZNOS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_MAIN_PARAM'),
							(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_SPR_DOP_VZNOS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_MAIN_PARAM'),
							(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_SPR_DOP_VZNOS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KU_EMPL_PLACING'
						
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_SPR_DOP_VZNOS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr1'
						
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_SPR_DOP_VZNOS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_MAIN_PARAM'),
							(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_SPR_DOP_VZNOS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_MAIN_PARAM'),
							(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_SPR_DOP_VZNOS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_MAIN_PARAM'),
							(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_SPR_DOP_VZNOS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SPR_DOP_VZNOS_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'),
					'Расчетный год',3, 
					(Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_NASTR'),
					'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_N1'),
							(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_SPR_DOP_VZNOS_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_N1'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SPR_DOP_VZNOS_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_TEXTBOX'),
					'Номер справки',4, 
					(Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_NASTR'),
					'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'TEXTBOX'
						
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_SPR_DOP_VZNOS_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@cText1'
						
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_SPR_DOP_VZNOS_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'varchar(8)'
						
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_SPR_DOP_VZNOS_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_N2'),
							(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_SPR_DOP_VZNOS_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_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_SPR_DOP_VZNOS_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SPR_DOP_VZNOS_N2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO



GO


/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Справка об уплаченных суммах доп. страх. взносов на накопит. часть пенсии"*************/ 

DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'SQL_REP_SPR_DOP_VZNOS')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SALARY_DOC_TREE_ROOT')

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_DOC_TREE_ROOT'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SNV_SQL_REP_SPR_DOP_VZNOS'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'SNV_SQL_REP_SPR_DOP_VZNOS', 'Справка об уплаченных суммах доп. страх. взносов на накопит. часть пенсии', @ORD, NULL, 1, @LINK_SELF, 'REPORT', @OBJECT, @LINK_VAR, 3
GO


GO
		CREATE TABLE #T_OV (LINK int, NAME varchar(254), OBJECT int, CODE varchar(60), USERS VARCHAR(85), ORDERS int, LINK_SELF int, LINK_STATE int, CODE_OBJ varchar(60), CODE_SELF varchar(60), CODE_STATE varchar(60), SYS BIT)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (85551.00, 'Список с датами рождения', 2688.00, 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', NULL, 0.00, 76111.00, NULL, 'SQUERY_USER', 'SYS_KADRY_USER_REPORTS_CATALOG', NULL, 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (86571.00, 'Организация - ключ', 2686.00, 'SYS_E4FCCF6C-6DE7-4DEB-A269-BC57AA99BDEB', NULL, 999.00, 85551.00, 81439.00, 'SQUERY_FIELD', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SYS_2452558_0S90YEMO0', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92275.00, 'Лицо', 2686.00, 'SYS_7B59C7F0-80A5-4860-B938-1284B40E14AE', NULL, 5.00, 85551.00, 90576.00, 'SQUERY_FIELD', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SYS_2452328_0LV0IROM7', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92276.00, 'Дата формирования', 2698.00, 'SYS_9064763_547885910', NULL, 1.00, 85551.00, 91923.00, 'SQUERY_NASTR', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SYS_2452362_0MT0KEIXO', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92277.00, '', 2693.00, 'SYS_D1B3CD13-76D1-4BE9-BF4D-789ACB7FC567', NULL, 0.00, 92275.00, 90576.00, 'SQUERY_LINK_BASE', 'SYS_7B59C7F0-80A5-4860-B938-1284B40E14AE', 'SYS_2452328_0LV0IROM7', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92278.00, '', 2691.00, 'SYS_19234F28-88E4-48E4-BEB0-458F144C529F', NULL, 0.00, 92275.00, 90576.00, 'SQUERY_LINK_SOURCE', 'SYS_7B59C7F0-80A5-4860-B938-1284B40E14AE', 'SYS_2452328_0LV0IROM7', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92279.00, 'ФИО', 2686.00, 'SYS_95E6B354-CA68-4453-9E1E-D098C0AE8A32', NULL, 2.00, 92275.00, 90581.00, 'SQUERY_FIELD', 'SYS_7B59C7F0-80A5-4860-B938-1284B40E14AE', 'SYS_2452328_0LV0IUCIO', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92280.00, 'Таб. №', 2686.00, 'SYS_5F3F3614-BCB8-4E68-810C-97A7DB251574', NULL, 1.00, 92275.00, 90582.00, 'SQUERY_FIELD', 'SYS_7B59C7F0-80A5-4860-B938-1284B40E14AE', 'SYS_2452328_0LV0IUPQW', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92281.00, 'Пол (сокр.)', 2686.00, 'SYS_415A5E71-291E-4618-AC29-172FB562C7A9', NULL, 4.00, 92275.00, 90601.00, 'SQUERY_FIELD', 'SYS_7B59C7F0-80A5-4860-B938-1284B40E14AE', 'SYS_2452362_0MT0T5Y6N', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92282.00, '', 2694.00, 'SYS_AFA2FE45-CBA5-4012-A951-EC9D8443BF35', NULL, 0.00, 92275.00, 90838.00, 'SQUERY_LINK_STATE', 'SYS_7B59C7F0-80A5-4860-B938-1284B40E14AE', 'SYS_2452566_0SH0LW148', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92283.00, '', 2694.00, 'SYS_2F943BC7-DA1B-41AD-8729-B2AA59785953', NULL, 1.00, 92275.00, 90923.00, 'SQUERY_LINK_STATE', 'SYS_7B59C7F0-80A5-4860-B938-1284B40E14AE', 'SYS_2452696_0W50UZSCL', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92284.00, '', 2695.00, 'SYS_34B18421-D579-44B6-B0E7-888D777E36D7', NULL, 0.00, 92275.00, 85551.00, 'SQUERY_LINK_SQUERY', 'SYS_7B59C7F0-80A5-4860-B938-1284B40E14AE', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92715.00, 'Дата рождения', 2686.00, 'SYS_5908125A-8479-4C9D-A520-98D260D5B29C', NULL, 0.00, 92275.00, NULL, 'SQUERY_FIELD', 'SYS_7B59C7F0-80A5-4860-B938-1284B40E14AE', NULL, 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92943.00, 'LINK', 2683.00, 'SYS_5CF91D0C-39EC-4E15-A480-5323DA721970', NULL, 0.00, 92275.00, 92944.00, 'SQUERY_LINK', 'SYS_7B59C7F0-80A5-4860-B938-1284B40E14AE', 'SYS_9389491A-2EC8-4F4E-B235-010AC3694457', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92944.00, 'Дата рождения', 2686.00, 'SYS_9389491A-2EC8-4F4E-B235-010AC3694457', NULL, 5.00, 92275.00, 90584.00, 'SQUERY_FIELD', 'SYS_7B59C7F0-80A5-4860-B938-1284B40E14AE', 'SYS_2452328_0LV0IV4AF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92945.00, 'LINK', 2683.00, 'SYS_C0BCF29A-8789-4D6B-AE10-B6D351EE27D6', NULL, 0.00, 92275.00, 92280.00, 'SQUERY_LINK', 'SYS_7B59C7F0-80A5-4860-B938-1284B40E14AE', 'SYS_5F3F3614-BCB8-4E68-810C-97A7DB251574', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92285.00, '', 2691.00, 'SYS_051AC27C-CC38-4BCF-8132-681D3C450506', NULL, 0.00, 92279.00, 90581.00, 'SQUERY_LINK_SOURCE', 'SYS_95E6B354-CA68-4453-9E1E-D098C0AE8A32', 'SYS_2452328_0LV0IUCIO', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92286.00, '', 2693.00, 'SYS_3727EC6B-4480-4A87-8072-D93797B1E18E', NULL, 0.00, 92279.00, 90581.00, 'SQUERY_LINK_BASE', 'SYS_95E6B354-CA68-4453-9E1E-D098C0AE8A32', 'SYS_2452328_0LV0IUCIO', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92287.00, '', 2693.00, 'SYS_6B570A17-2045-49AC-990C-2077AB666D2B', NULL, 0.00, 92280.00, 90582.00, 'SQUERY_LINK_BASE', 'SYS_5F3F3614-BCB8-4E68-810C-97A7DB251574', 'SYS_2452328_0LV0IUPQW', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92288.00, '', 2691.00, 'SYS_D2A44097-4AAA-40CE-9E32-9C082D712C67', NULL, 0.00, 92280.00, 90582.00, 'SQUERY_LINK_SOURCE', 'SYS_5F3F3614-BCB8-4E68-810C-97A7DB251574', 'SYS_2452328_0LV0IUPQW', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92289.00, '', 2693.00, 'SYS_3A167A52-15B2-4451-AB21-5EADC09E360B', NULL, 0.00, 92281.00, 90601.00, 'SQUERY_LINK_BASE', 'SYS_415A5E71-291E-4618-AC29-172FB562C7A9', 'SYS_2452362_0MT0T5Y6N', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92290.00, '', 2691.00, 'SYS_31E3094A-5B3C-466A-85EC-E8F7493DC19D', NULL, 0.00, 92281.00, 90601.00, 'SQUERY_LINK_SOURCE', 'SYS_415A5E71-291E-4618-AC29-172FB562C7A9', 'SYS_2452362_0MT0T5Y6N', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92291.00, '', 2695.00, 'SYS_88E7347D-338B-4B1E-8AB2-A07CF7577B2D', NULL, 0.00, 92281.00, 85551.00, 'SQUERY_LINK_SQUERY', 'SYS_415A5E71-291E-4618-AC29-172FB562C7A9', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92292.00, '', 2695.00, 'SYS_237D6F44-66A2-4F3D-B7D9-1B99B390B050', NULL, 0.00, 92280.00, 85551.00, 'SQUERY_LINK_SQUERY', 'SYS_5F3F3614-BCB8-4E68-810C-97A7DB251574', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92293.00, '', 2695.00, 'SYS_BCDEF263-BBAD-4491-840C-9E82145242B4', NULL, 0.00, 92279.00, 85551.00, 'SQUERY_LINK_SQUERY', 'SYS_95E6B354-CA68-4453-9E1E-D098C0AE8A32', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (93109.00, '', 2691.00, 'SYS_31E3094A-5B3C-466A-85EC-E8F7493DC98D', NULL, 0.00, 92944.00, 90584.00, 'SQUERY_LINK_SOURCE', 'SYS_9389491A-2EC8-4F4E-B235-010AC3694457', 'SYS_2452328_0LV0IV4AF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (93110.00, '', 2695.00, 'SYS_88E7347D-338B-4B1E-8AB2-A07CF7543B6D', NULL, 0.00, 92944.00, 85551.00, 'SQUERY_LINK_SQUERY', 'SYS_9389491A-2EC8-4F4E-B235-010AC3694457', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (93111.00, '', 2693.00, 'SYS_3A167A52-15B2-4451-AB21-5EADC09E378B', NULL, 0.00, 92944.00, 90584.00, 'SQUERY_LINK_BASE', 'SYS_9389491A-2EC8-4F4E-B235-010AC3694457', 'SYS_2452328_0LV0IV4AF', 1)

GO

		CREATE TABLE #T_OVV (LINK_UP int, PROPERTY int, USERS VARCHAR(85), ORDERS int, VALUE varchar(8000), CODE_UP varchar(60), CODE_PROP varchar(30))
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (85551.00, 324.00, NULL, NULL, '', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SQUERY_CHANGED')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (85551.00, 346.00, NULL, NULL, '', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SQUERY_GENERATOR')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (85551.00, 360.00, NULL, NULL, '', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SQUERY_PATH')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (85551.00, 361.00, NULL, NULL, '', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SQUERY_REPORT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (85551.00, 363.00, NULL, 8.00, '
	UPDATE #T_RES
	SET	S_24944 = (select p.birthdate from person p where p.link=(SELECT PERS_LINK FROM EMPL WHERE LINK = S_37028)) /*Дата рождения*/ FROM #T_RES T 
', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (85551.00, 363.00, NULL, 9.00, '
	SELECT S_24944 AS S_24944 /*Дата рождения*/,
		S_37037 AS S_37037 /*Таб. №*/,
		S_37041 AS S_37041 /*ФИО*/,
		S_37045 AS S_37045 /*Пол (сокр.)*/,
		S_37028 AS S_37028 /*Лицо*/,
		S_42535 AS S_42535 /*Организация - ключ*/
	INTO #T_RES2
	FROM #T_RES T
	GROUP BY S_24944, S_37037, S_37041, S_37045, S_37028, S_42535


', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (85551.00, 363.00, NULL, 1.00, 'CREATE PROCEDURE #P_SQUERY
		@dDate_1 DATETIME /*Дата формирования*/,
		@varKScTableInto varchar(20) = ''''
AS
BEGIN

	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (85551.00, 363.00, NULL, 2.00, '
	CREATE TABLE  #WORKERS (FACE INT, START_DATE DATETIME, END_DATE DATETIME, STAFF INT,  LINK_DEP INT)
EXEC K_FILL_T_WORKERS @dDate_1

', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (85551.00, 363.00, NULL, 12.00, '
	DROP TABLE #WORKERS

	SET TRANSACTION ISOLATION LEVEL READ COMMITTED

END', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (85551.00, 363.00, NULL, 5.00, '
	UPDATE #T_RES
	SET	S_37037 = (SELECT TAB FROM EMPL WHERE LINK=S_37028) /*Таб. №*/ FROM #T_RES T 
', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (85551.00, 363.00, NULL, 10.00, '	
SELECT * FROM #T_RES2 

', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (85551.00, 363.00, NULL, 3.00, '
	CREATE TABLE #T_RES (S_37028 INT /*Лицо*/,
		S_37037 VARCHAR(15) /*Таб. №*/,
		S_37041 VARCHAR(150) /*ФИО*/,
		S_37045 CHAR(1) /*Пол (сокр.)*/,
		S_42535 INT /*Организация - ключ*/,
		S_24944 DATETIME /*Дата рождения*/, SQUERY int)
', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (85551.00, 363.00, NULL, 4.00, '
	INSERT #T_RES (S_37028, S_42535, SQUERY) /*Организация - ключ*/
	SELECT #workers.face, DEP.LINK, 37027
	FROM #WORKERS, DICTIONARY_DEPARTMENT DEP
	WHERE #WORKERS.LINK_DEP=DEP.LINK
		AND DEP.LINK=isnull(dbo.BK_getDepZB(), dbo.getowndeplink())
', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (85551.00, 363.00, NULL, 7.00, '
	UPDATE #T_RES
	SET	S_37045 = CASE CAST( 
	isnull( (SELECT P.SEX FROM PERSON P  WHERE P.LINK=(SELECT PERS_LINK FROM EMPL WHERE LINK = S_37028)), 3) AS INTEGER)
WHEN 1 THEN ''М''
WHEN 2 THEN ''Ж''
WHEN 3 THEN ''-''
END /*Пол (сокр.)*/ FROM #T_RES T 
', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (85551.00, 363.00, NULL, 6.00, '
	UPDATE #T_RES
	SET	S_37041 = (SELECT ( rtrim(P.FM) +'' '' +rtrim(substring( (P.IM),1,1))+''. ''+ rtrim(substring((P.OT),1,1) )+''. ''  ) FROM PERSON P WHERE P.LINK=(SELECT PERS_LINK FROM EMPL WHERE LINK = S_37028)) /*ФИО*/ FROM #T_RES T 
', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (85551.00, 363.00, NULL, 11.00, '
	DROP TABLE #T_RES
', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (85551.00, 552.00, NULL, NULL, '', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'QUERY_ADD_MODULE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (86571.00, 326.00, NULL, NULL, 'S_42535', 'SYS_E4FCCF6C-6DE7-4DEB-A269-BC57AA99BDEB', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (86571.00, 335.00, NULL, NULL, '0', 'SYS_E4FCCF6C-6DE7-4DEB-A269-BC57AA99BDEB', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (86571.00, 342.00, NULL, NULL, '1', 'SYS_E4FCCF6C-6DE7-4DEB-A269-BC57AA99BDEB', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92275.00, 326.00, NULL, NULL, 'S_37028', 'SYS_7B59C7F0-80A5-4860-B938-1284B40E14AE', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92275.00, 327.00, NULL, NULL, '0', 'SYS_7B59C7F0-80A5-4860-B938-1284B40E14AE', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92275.00, 331.00, NULL, NULL, '0', 'SYS_7B59C7F0-80A5-4860-B938-1284B40E14AE', 'SQUERY_FIELD_GROUP_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92275.00, 335.00, NULL, NULL, '0', 'SYS_7B59C7F0-80A5-4860-B938-1284B40E14AE', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92275.00, 342.00, NULL, NULL, '1', 'SYS_7B59C7F0-80A5-4860-B938-1284B40E14AE', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92276.00, 355.00, NULL, NULL, 'Текущая дата', 'SYS_9064763_547885910', 'SQUERY_NASTR_VALUE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92279.00, 326.00, NULL, NULL, 'S_37041', 'SYS_95E6B354-CA68-4453-9E1E-D098C0AE8A32', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92279.00, 327.00, NULL, NULL, '3', 'SYS_95E6B354-CA68-4453-9E1E-D098C0AE8A32', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92279.00, 329.00, NULL, NULL, '@', 'SYS_95E6B354-CA68-4453-9E1E-D098C0AE8A32', 'SQUERY_FIELD_FORMAT_D_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92279.00, 331.00, NULL, NULL, '0', 'SYS_95E6B354-CA68-4453-9E1E-D098C0AE8A32', 'SQUERY_FIELD_GROUP_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92279.00, 335.00, NULL, NULL, '3', 'SYS_95E6B354-CA68-4453-9E1E-D098C0AE8A32', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92279.00, 338.00, NULL, NULL, '2', 'SYS_95E6B354-CA68-4453-9E1E-D098C0AE8A32', 'SQUERY_FIELD_SORT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92279.00, 342.00, NULL, NULL, '3', 'SYS_95E6B354-CA68-4453-9E1E-D098C0AE8A32', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92280.00, 326.00, NULL, NULL, 'S_37037', 'SYS_5F3F3614-BCB8-4E68-810C-97A7DB251574', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92280.00, 327.00, NULL, NULL, '3', 'SYS_5F3F3614-BCB8-4E68-810C-97A7DB251574', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92280.00, 328.00, NULL, NULL, '', 'SYS_5F3F3614-BCB8-4E68-810C-97A7DB251574', 'SQUERY_FIELD_FORMAT_C_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92280.00, 329.00, NULL, NULL, '@', 'SYS_5F3F3614-BCB8-4E68-810C-97A7DB251574', 'SQUERY_FIELD_FORMAT_D_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92280.00, 331.00, NULL, NULL, '0', 'SYS_5F3F3614-BCB8-4E68-810C-97A7DB251574', 'SQUERY_FIELD_GROUP_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92280.00, 335.00, NULL, NULL, '1', 'SYS_5F3F3614-BCB8-4E68-810C-97A7DB251574', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92280.00, 338.00, NULL, NULL, '1', 'SYS_5F3F3614-BCB8-4E68-810C-97A7DB251574', 'SQUERY_FIELD_SORT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92280.00, 342.00, NULL, NULL, '3', 'SYS_5F3F3614-BCB8-4E68-810C-97A7DB251574', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92281.00, 326.00, NULL, NULL, 'S_37045', 'SYS_415A5E71-291E-4618-AC29-172FB562C7A9', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92281.00, 327.00, NULL, NULL, '3', 'SYS_415A5E71-291E-4618-AC29-172FB562C7A9', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92281.00, 329.00, NULL, NULL, '@', 'SYS_415A5E71-291E-4618-AC29-172FB562C7A9', 'SQUERY_FIELD_FORMAT_D_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92281.00, 331.00, NULL, NULL, '0', 'SYS_415A5E71-291E-4618-AC29-172FB562C7A9', 'SQUERY_FIELD_GROUP_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92281.00, 335.00, NULL, NULL, '2', 'SYS_415A5E71-291E-4618-AC29-172FB562C7A9', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92281.00, 342.00, NULL, NULL, '3', 'SYS_415A5E71-291E-4618-AC29-172FB562C7A9', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92715.00, 342.00, NULL, NULL, '3', 'SYS_5908125A-8479-4C9D-A520-98D260D5B29C', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92944.00, 326.00, NULL, NULL, 'S_24944', 'SYS_9389491A-2EC8-4F4E-B235-010AC3694457', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92944.00, 327.00, NULL, NULL, '3', 'SYS_9389491A-2EC8-4F4E-B235-010AC3694457', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92944.00, 329.00, NULL, NULL, 'ДД.ММ.ГГГГ', 'SYS_9389491A-2EC8-4F4E-B235-010AC3694457', 'SQUERY_FIELD_FORMAT_D_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92944.00, 331.00, NULL, NULL, '0', 'SYS_9389491A-2EC8-4F4E-B235-010AC3694457', 'SQUERY_FIELD_GROUP_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92944.00, 335.00, NULL, NULL, '4', 'SYS_9389491A-2EC8-4F4E-B235-010AC3694457', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92944.00, 339.00, NULL, NULL, '', 'SYS_9389491A-2EC8-4F4E-B235-010AC3694457', 'SQUERY_FIELD_SQLTYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92944.00, 342.00, NULL, NULL, '3', 'SYS_9389491A-2EC8-4F4E-B235-010AC3694457', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92944.00, 345.00, NULL, NULL, '', 'SYS_9389491A-2EC8-4F4E-B235-010AC3694457', 'SQUERY_FORMULA')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92944.00, 349.00, NULL, NULL, '', 'SYS_9389491A-2EC8-4F4E-B235-010AC3694457', 'SQUERY_KEY')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92944.00, 428.00, NULL, NULL, 'S_24944', 'SYS_9389491A-2EC8-4F4E-B235-010AC3694457', 'QUERY_CONDITION_DICT_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92944.00, 429.00, NULL, NULL, 'Дата рождения', 'SYS_9389491A-2EC8-4F4E-B235-010AC3694457', 'QUERY_CONDITION_DICT_FIELD')

GO

		CREATE TABLE #T_NAVIGATOR (CODE VARCHAR(50), NAME VARCHAR(254), ORDERS INT, SYS INT, CODE_SELF VARCHAR(50), CODE_OBJ VARCHAR(30), SQ_CODE VARCHAR(60), IMAGE_KEY VARCHAR(30) )
		INSERT INTO #T_NAVIGATOR(CODE,  NAME,  ORDERS,  SYS,  CODE_SELF,  CODE_OBJ,  SQ_CODE,  IMAGE_KEY) VALUES ('STANDART_REPORT', 'Список с датами рождения', 18.00, 1, 'KADRY_FREE_PERSONS', 'SQUERY_USER', 'SYS_73F38721-F8AD-49C8-9549-48AC4D3C5D6E', 'REPORT_QUERY')

GO

		exec KIR_UPGRADE_OV 0 
GO

		DROP TABLE #T_OV
GO

		DROP TABLE #T_OVV
GO

		DROP TABLE #T_NAVIGATOR
GO


GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (мар  5 2014 10:26:39:323AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0503373GSV (Сведения об изменении остатков валюты баланса (средства во временном распоряжении))
-- Дата ввода : 20120101
-- Дата окончания действия :
-- Версия : 2014-03-05 10:26:39.323
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : нет
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

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] = '0503373GSV' AND [START_DATE] = '20120101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-03-05 10:26:39.323',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_' + '0503373GSV',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 = '0503373GSV'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20120101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. 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,7,1,1,1,18186,'RO_EXPORT_FORM_373#RO_IMPORT_FORM_373',0,1,'19000101',NULL,'191н'
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, '','SV_0503373_20111231.BAS','','KirRepMakerMultiSheet.xls','SV_0503373GSV_20120101.XLT','',NULL,'RO_EXPORT_FORM_373#RO_IMPORT_FORM_373',0,'COL2 + ''|'' + STR(COL3) + ''|'' + STR(COL4) + ''|'' + STR(COL5) + ''|''# ''000|0|''  + SUBSTRING(COL1,2,5) + ''|'' + SUBSTRING(COL1,7,3) + ''|'' + dbo.RO_EXP(COL3) + ''|'' + dbo.RO_EXP(COL4) + ''|'' + STR(COL2) + ''|'' + dbo.RO_EXP(COL5) + ''|''','C1+''|'' +C2 +''|'' +C3+''|'' +C4+''|'' #C2+C3+C4+''|'' +C7 +''|'' +C5+''|'' +C6+''|'' +C8+''|'' + C2+C3+C4+C5+C6+''|''',NULL,'473sv     ','',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,1,0,256,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,3,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,'Остаток на начало отчетного финансового года',@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,'Сумма расхождения, руб',@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


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,1,1,1,0,9,1,'R_SPR_173_2011','COL1','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, 2,'Сумма расхождения, руб',@iLINK_TABLE,1,0,2,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, 3,'Реквизиты контрагента. Код главы по БК',@iLINK_TABLE,1,1,3,0,3,1,'R_SPR_ADM_2011','COL3','CODE','NNN',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,8,1,'R_SPR_OKATO_173_373','COL4','OKATO','NNNNNNNN',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,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, 6,'Составной ключ',@iLINK_TABLE,1,1,6,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
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Причина изменений', @iLINK_FORM,2, @iLINK_CODE_COL,1,'KEY_FOX=PADR(RTRIM(COL1),9,''0'')+LEFT(COL3+''    '',3)+LEFT(COL4+''        '',8)
KEY_WEB=LEFT(RTRIM(isnull(COL1,''''))+''000000000'',9)+LEFT(RTRIM(ISNULL(COL3,''''))+''   '',3)+LEFT(RTRIM(ISNULL(COL4,''''))+''        '',8)
SPLIT=COL1=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',1,9)#COL3=SUBSTRING(RTRIM(CODE_ROW)+'''',10,3)#COL4=SUBSTRING(RTRIM(CODE_ROW)+'''',13,8)','-1#LEFT(CODE,9)=''888888888''
1#LEFT(CODE,9)=''999999999''
2#SUBSTRING(CODE,2,5) in (''30100'',''30200'',''30300'',''30400'',''40100'',''40200'')',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,2,1)
INSERT #R VALUES (3,1,3,1)
INSERT #R VALUES (4,1,4,1)
INSERT #R VALUES (5,1,5,1)
INSERT #R VALUES (6,1,6,1)
INSERT #R VALUES (7,1,7,1)
INSERT #R VALUES (8,1,8,1)
INSERT #R VALUES (9,1,9,1)
INSERT #R VALUES (10,1,10,1)
INSERT #R VALUES (11,1,11,1)
INSERT #R VALUES (12,1,12,1)
INSERT #R VALUES (13,1,13,1)
INSERT #R VALUES (14,1,14,1)
INSERT #R VALUES (15,1,15,1)
INSERT #R VALUES (16,1,16,1)
INSERT #R VALUES (17,1,17,1)
INSERT #R VALUES (18,1,18,1)
INSERT #R VALUES (19,1,19,1)
INSERT #R VALUES (20,1,20,1)
INSERT #R VALUES (21,1,21,1)
INSERT #R VALUES (22,1,22,1)
INSERT #R VALUES (23,1,23,1)
INSERT #R VALUES (24,1,24,1)
INSERT #R VALUES (25,1,25,1)
INSERT #R VALUES (26,1,26,1)
INSERT #R VALUES (27,1,27,1)
INSERT #R VALUES (28,1,28,1)
INSERT #R VALUES (29,1,29,1)
INSERT #R VALUES (30,1,30,1)
INSERT #R VALUES (31,1,31,1)
INSERT #R VALUES (32,1,32,1)
INSERT #R VALUES (33,1,33,1)
INSERT #R VALUES (34,1,34,1)
INSERT #R VALUES (35,1,35,1)
INSERT #R VALUES (36,1,36,1)
INSERT #R VALUES (37,1,37,1)
INSERT #R VALUES (38,1,38,1)
INSERT #R VALUES (39,1,39,1)
INSERT #R VALUES (40,1,40,1)
INSERT #R VALUES (41,1,41,1)
INSERT #R VALUES (42,1,42,1)
INSERT #R VALUES (43,1,43,1)
INSERT #R VALUES (44,1,44,1)
INSERT #R VALUES (45,1,45,1)
INSERT #R VALUES (46,1,46,1)
INSERT #R VALUES (47,1,47,1)
INSERT #R VALUES (48,1,48,1)
INSERT #R VALUES (49,1,49,1)
INSERT #R VALUES (50,1,50,1)
INSERT #R VALUES (51,1,51,1)
INSERT #R VALUES (52,1,52,1)
INSERT #R VALUES (53,1,53,1)
INSERT #R VALUES (54,1,54,1)
INSERT #R VALUES (55,1,55,1)
INSERT #R VALUES (56,1,56,1)
INSERT #R VALUES (57,1,57,1)
INSERT #R VALUES (58,1,58,1)
INSERT #R VALUES (59,1,59,1)
INSERT #R VALUES (60,1,60,1)
INSERT #R VALUES (61,1,61,1)
INSERT #R VALUES (62,1,62,1)
INSERT #R VALUES (63,1,63,1)
INSERT #R VALUES (64,1,64,1)
INSERT #R VALUES (65,1,65,1)
INSERT #R VALUES (66,1,66,1)
INSERT #R VALUES (67,1,67,1)
INSERT #R VALUES (68,1,68,1)
INSERT #R VALUES (69,1,69,1)
INSERT #R VALUES (70,1,70,1)
INSERT #R VALUES (71,1,71,1)
INSERT #R VALUES (72,1,72,1)
INSERT #R VALUES (73,1,73,1)
INSERT #R VALUES (74,1,74,1)
INSERT #R VALUES (75,1,75,1)
INSERT #R VALUES (76,1,76,1)
INSERT #R VALUES (77,1,77,1)
INSERT #R VALUES (78,1,78,1)
INSERT #R VALUES (79,1,79,1)
INSERT #R VALUES (80,1,80,1)
INSERT #R VALUES (81,1,81,1)
INSERT #R VALUES (82,1,82,1)
INSERT #R VALUES (83,1,83,1)
INSERT #R VALUES (84,1,84,1)
INSERT #R VALUES (85,1,85,1)
INSERT #R VALUES (86,1,86,1)
INSERT #R VALUES (87,1,87,1)
INSERT #R VALUES (88,1,88,1)
INSERT #R VALUES (89,1,89,1)
INSERT #R VALUES (90,1,90,1)
INSERT #R VALUES (91,1,91,1)
INSERT #R VALUES (92,1,92,1)
INSERT #R VALUES (93,1,93,1)
INSERT #R VALUES (94,1,94,1)
INSERT #R VALUES (95,1,95,1)
INSERT #R VALUES (96,1,96,1)
INSERT #R VALUES (97,1,97,1)
INSERT #R VALUES (98,1,98,1)
INSERT #R VALUES (99,1,99,1)
INSERT #R VALUES (100,1,103,1)
INSERT #R VALUES (101,1,99,1)
INSERT #R VALUES (102,1,100,1)
INSERT #R VALUES (103,1,101,1)
INSERT #R VALUES (104,1,104,1)
INSERT #R VALUES (105,1,106,1)
INSERT #R VALUES (106,1,102,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 106
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,' Основные средства (балансовая стоимость, 010100000), всего                                                                                      ')
INSERT #F VALUES (1,2,1,'    в том числе: недвижимое имущество учреждения (010110000) ')
INSERT #F VALUES (1,3,1,'    иное движимое имущество учреждения (010130000)')
INSERT #F VALUES (1,4,1,'    предметы лизинга (010140000) ')
INSERT #F VALUES (1,5,1,' Амортизация основных средств')
INSERT #F VALUES (1,6,1,'    в том числе: Амортизация недвижимого имущества учреждения (010410000) ')
INSERT #F VALUES (1,7,1,' Амортизация иного движимого имущества учреждения (010430000) ')
INSERT #F VALUES (1,8,1,' Амортизация предметов лизинга (010440000)')
INSERT #F VALUES (1,9,1,' Основные средства (остаточная стоимость, стр.010 -  стр.020)                                                                                             ')
INSERT #F VALUES (1,10,1,'    из них: недвижимое имущество учреждения (остаточная стоимость, стр.011 -  стр.021)                                                                                             ')
INSERT #F VALUES (1,11,1,'    иное движимое имущество учреждения (остаточная стоимость, стр.013 -  стр.023)                                                                                             ')
INSERT #F VALUES (1,12,1,'    предметы лизинга (остаточная стоимость, стр.014 -  стр.024)                                                                                             ')
INSERT #F VALUES (1,13,1,' Нематериальные активы (балансовая стоимость, 010200000)*, всего                                                           ')
INSERT #F VALUES (1,14,1,'    из них: иное движимое имущество учреждения (010230000) *')
INSERT #F VALUES (1,15,1,'    предметы лизинга  (010240000) *')
INSERT #F VALUES (1,16,1,' Амортизация нематериальных активов *')
INSERT #F VALUES (1,17,1,'    из них: иного движимого имущества учреждения (010439000) *')
INSERT #F VALUES (1,18,1,'    предметов лизинга  (010449000) *')
INSERT #F VALUES (1,19,1,' Нематериальные активы (остаточная стоимость, стр. 040 -  стр.050)                                                                                              ')
INSERT #F VALUES (1,20,1,'    из них: иное движимое имущество учреждения (остаточная стоимость, стр. 042 -  стр.052)                                                                                              ')
INSERT #F VALUES (1,21,1,'    предметы лизинга (остаточная стоимость, стр. 043 -  стр.053)                                                                                              ')
INSERT #F VALUES (1,22,1,' Непроизведенные активы (балансовая стоимость, 010300000)                                                                                             ')
INSERT #F VALUES (1,23,1,' Материальные запасы (010500000)')
INSERT #F VALUES (1,24,1,' Вложения в нефинансовые активы (010600000)')
INSERT #F VALUES (1,25,1,'    из них: в недвижимое имущество учреждения (010610000)')
INSERT #F VALUES (1,26,1,'    в иное движимое имущество учреждения (010630000)')
INSERT #F VALUES (1,27,1,'    в предметы лизинга (010640000)')
INSERT #F VALUES (1,28,1,' Нефинансовые активы в пути (010700000)')
INSERT #F VALUES (1,29,1,'    из них: недвижимое имущество учреждения в пути (010710000)')
INSERT #F VALUES (1,30,1,'    иное движимое имущество учреждения в пути (010730000)')
INSERT #F VALUES (1,31,1,'    предметы лизинга в пути (010740000)')
INSERT #F VALUES (1,32,1,' Нефинансовые активы имущества казны (балансовая стоимость, 010800000)*')
INSERT #F VALUES (1,33,1,' Амортизация имущества, составляющего казну  (010450000) *                                                                                      ')
INSERT #F VALUES (1,34,1,' Нефинансовые активы имущества казны (остаточная стоимость, стр. 110 - стр. 120)')
INSERT #F VALUES (1,35,1,' Затраты на изготовление готовой продукции, выполнение работ, услуг (010900000)')
INSERT #F VALUES (1,36,1,' Итого по разделу I (стр.030 + стр.060 + стр.070 + стр.080 + стр.090 + стр.100 + стр.130 + стр. 140)')
INSERT #F VALUES (1,37,1,' Денежные средства учреждения (020100000)')
INSERT #F VALUES (1,38,1,'    в том числе: денежные средства учреждения на лицевых счетах в органе казначейства (020111000)')
INSERT #F VALUES (1,39,1,'    денежные средства учреждения в органе казначейства в пути (020113000)')
INSERT #F VALUES (1,40,1,'    денежные средства учреждения на счетах в кредитной организации (020121000)')
INSERT #F VALUES (1,41,1,'    денежные средства учреждения в кредитной организации в пути (020123000)')
INSERT #F VALUES (1,42,1,'    аккредитивы на счетах учреждения в кредитной организации (020126000)')
INSERT #F VALUES (1,43,1,'    денежные средства учреждения в иностранной валюте на счетах в кредитной организации (020127000)')
INSERT #F VALUES (1,44,1,'    касса (020134000)')
INSERT #F VALUES (1,45,1,'    денежные документы (020135000)')
INSERT #F VALUES (1,46,1,'    денежные средства учреждения, размещенные на депозиты в кредитной организации (020122000)')
INSERT #F VALUES (1,47,1,' Средства на счетах бюджета в органе Федерального казначейства (020210000)')
INSERT #F VALUES (1,48,1,'    в том числе: средства на счетах бюджета в рублях в органе Федерального казначейства (020211000)')
INSERT #F VALUES (1,49,1,'    средства на счетах бюджета в органе Федерального казначейства в пути (020212000)')
INSERT #F VALUES (1,50,1,'    средства на счетах бюджета в иностранной валюте в органах Федерального казначейства (020213000)')
INSERT #F VALUES (1,51,1,' Средства на счетах бюджета в кредитной организации (020220000)')
INSERT #F VALUES (1,52,1,'    в том числе: средства на счетах бюджета в рублях в кредитной организации (020221000)')
INSERT #F VALUES (1,53,1,'    средства на счетах бюджета в кредитной организации в пути (020222000)')
INSERT #F VALUES (1,54,1,'    средства на счетах бюджета в иностранной валюте в кредитной организации (020223000)')
INSERT #F VALUES (1,55,1,' Средства бюджета на депозитных счетах (020230000)')
INSERT #F VALUES (1,56,1,'    в том числе: средства бюджета на депозитных счетах в рублях (020231000)')
INSERT #F VALUES (1,57,1,'    средства бюджета на депозитных счетах в пути (020232000)')
INSERT #F VALUES (1,58,1,'    средства бюджета на депозитных счетах в иностранной валюте (020233000)')
INSERT #F VALUES (1,59,1,' Финансовые вложения (020400000)')
INSERT #F VALUES (1,60,1,'    в том числе: ценные бумаги, кроме акций  (020420000)')
INSERT #F VALUES (1,61,1,'    акции и иные формы участия в капитале (020430000)')
INSERT #F VALUES (1,62,1,'    иные финансовые активы (020450000)')
INSERT #F VALUES (1,63,1,' Расчеты по доходам (020500000)')
INSERT #F VALUES (1,64,1,' Расчеты по выданным авансам (020600000)')
INSERT #F VALUES (1,65,1,' Расчеты по кредитам, займам, ссудам (020700000)')
INSERT #F VALUES (1,66,1,'    в том числе: по предоставленным кредитам, ссудам, займам (020710000)')
INSERT #F VALUES (1,67,1,'    в рамках целевых иностранных кредитов (заимствований) (020720000)')
INSERT #F VALUES (1,68,1,'    с дебиторами по государственным (муниципальным) гарантиям (020730000)')
INSERT #F VALUES (1,69,1,' Расчеты с подотчетными лицами (020800000)')
INSERT #F VALUES (1,70,1,' Расчеты по ущербу имуществу (020900000)')
INSERT #F VALUES (1,71,1,' Прочие расчеты с дебиторами (021000000)')
INSERT #F VALUES (1,72,1,'    из них: расчеты по НДС по приобретенным материальным ценностям, работам, услугам (021001000)')
INSERT #F VALUES (1,73,1,'    расчеты с финансовым органом по наличным денежным средствам (021003000)')
INSERT #F VALUES (1,74,1,' Вложения в финансовые активы (021500000)')
INSERT #F VALUES (1,75,1,'    в том числе: ценные бумаги, кроме акций  (021520000)')
INSERT #F VALUES (1,76,1,'    акции и иные формы участия в капитале (021530000)')
INSERT #F VALUES (1,77,1,'    иные финансовые активы (021550000)')
INSERT #F VALUES (1,78,1,' Итого по разделу II (стр.170 + стр.180 + стр.190 + стр.200 + стр.210 + стр.230 + стр.260 + стр.290 + стр.310 + стр.320 + стр. 330 + стр.370)')
INSERT #F VALUES (1,79,1,' БАЛАНС (стр.150 + стр. 400)')
INSERT #F VALUES (1,80,1,' Расчеты с кредиторами по долговым обязательствам (030100000)')
INSERT #F VALUES (1,81,1,'    в том числе: по долговым обязательствам в рублях (030110000)')
INSERT #F VALUES (1,82,1,'    по долговым обязательствам по целевым иностранныи кредитам (заимствованиям) (030120000)')
INSERT #F VALUES (1,83,1,'    по государственным (муниципальным) гарантиям (03013000)')
INSERT #F VALUES (1,84,1,'    по долговым обязательствам в иностранной валюте (030140000)')
INSERT #F VALUES (1,85,1,' Расчеты по принятым обязательствам (030200000)')
INSERT #F VALUES (1,86,1,' Расчеты по платежам в бюджеты (030300000)')
INSERT #F VALUES (1,87,1,'    из них: расчеты по налогу на доходы физических лиц (030301000)')
INSERT #F VALUES (1,88,1,'    расчеты по страховым взносам на обязательное социальное страхование (030302000, 030306000)')
INSERT #F VALUES (1,89,1,'    расчеты по налогу на прибыль организаций (030303000)')
INSERT #F VALUES (1,90,1,'    расчеты по налогу на добавленную стоимость (030304000)')
INSERT #F VALUES (1,91,1,'    расчеты по иным платежам в бюджет (030305000, 030312000, 030313000)')
INSERT #F VALUES (1,92,1,'    расчеты по страховым взносам на медицинское и пенисонное страхование (030307000, 030308000, 030309000, 030310000, 030311000)')
INSERT #F VALUES (1,93,1,' Прочие расчеты с кредиторами (030400000)')
INSERT #F VALUES (1,94,1,'    из них: расчеты по средствам, полученным во временное распоряжение (030401000)')
INSERT #F VALUES (1,95,1,'    расчеты с депонентами (030402000)')
INSERT #F VALUES (1,96,1,'    расчеты по удержаниям из выплат по оплате труда (030403000)')
INSERT #F VALUES (1,97,1,'    внутриведомственные  расчеты (030404000)')
INSERT #F VALUES (1,98,1,' Итого по разделу III (стр.470+ стр.490 + стр. 510 + стр.530)')
INSERT #F VALUES (1,99,1,'Финансовый результат(040000000)  (стр.620+стр.690)')
INSERT #F VALUES (1,100,1,'Финансовый результат хозяйствующего субъекта (040100000)')
INSERT #F VALUES (1,101,1,'    из них: финансовый результат прошлых отчетных периодов (040130000)')
INSERT #F VALUES (1,102,1,'    доходы будущих периодов (040140000)')
INSERT #F VALUES (1,103,1,'    расходы будущих периодов (040150000)')
INSERT #F VALUES (1,104,1,'Результат по кассовым операциям бюджета (040200000)')
INSERT #F VALUES (1,105,1,'Результат прошлых отчетных периодов по кассовому исполнению бюджета (040230000)')
INSERT #F VALUES (1,106,1,' БАЛАНС (стр.600 + стр. 610)')
INSERT #F VALUES (1,1,2,'010')
INSERT #F VALUES (1,2,2,'011')
INSERT #F VALUES (1,3,2,'013')
INSERT #F VALUES (1,4,2,'014')
INSERT #F VALUES (1,5,2,'020')
INSERT #F VALUES (1,6,2,'021')
INSERT #F VALUES (1,7,2,'023')
INSERT #F VALUES (1,8,2,'024')
INSERT #F VALUES (1,9,2,'030')
INSERT #F VALUES (1,10,2,'031')
INSERT #F VALUES (1,11,2,'033')
INSERT #F VALUES (1,12,2,'034')
INSERT #F VALUES (1,13,2,'040')
INSERT #F VALUES (1,14,2,'042')
INSERT #F VALUES (1,15,2,'043')
INSERT #F VALUES (1,16,2,'050')
INSERT #F VALUES (1,17,2,'052')
INSERT #F VALUES (1,18,2,'053')
INSERT #F VALUES (1,19,2,'060')
INSERT #F VALUES (1,20,2,'062')
INSERT #F VALUES (1,21,2,'063')
INSERT #F VALUES (1,22,2,'070')
INSERT #F VALUES (1,23,2,'080')
INSERT #F VALUES (1,24,2,'090')
INSERT #F VALUES (1,25,2,'091')
INSERT #F VALUES (1,26,2,'093')
INSERT #F VALUES (1,27,2,'094')
INSERT #F VALUES (1,28,2,'100')
INSERT #F VALUES (1,29,2,'101')
INSERT #F VALUES (1,30,2,'103')
INSERT #F VALUES (1,31,2,'104')
INSERT #F VALUES (1,32,2,'110')
INSERT #F VALUES (1,33,2,'120')
INSERT #F VALUES (1,34,2,'130')
INSERT #F VALUES (1,35,2,'140')
INSERT #F VALUES (1,36,2,'150')
INSERT #F VALUES (1,37,2,'170')
INSERT #F VALUES (1,38,2,'171')
INSERT #F VALUES (1,39,2,'172                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,40,2,'173')
INSERT #F VALUES (1,41,2,'174')
INSERT #F VALUES (1,42,2,'175')
INSERT #F VALUES (1,43,2,'176')
INSERT #F VALUES (1,44,2,'177')
INSERT #F VALUES (1,45,2,'178')
INSERT #F VALUES (1,46,2,'179')
INSERT #F VALUES (1,47,2,'180')
INSERT #F VALUES (1,48,2,'181')
INSERT #F VALUES (1,49,2,'182')
INSERT #F VALUES (1,50,2,'183')
INSERT #F VALUES (1,51,2,'190')
INSERT #F VALUES (1,52,2,'191')
INSERT #F VALUES (1,53,2,'192')
INSERT #F VALUES (1,54,2,'193')
INSERT #F VALUES (1,55,2,'200')
INSERT #F VALUES (1,56,2,'201')
INSERT #F VALUES (1,57,2,'202')
INSERT #F VALUES (1,58,2,'203')
INSERT #F VALUES (1,59,2,'210')
INSERT #F VALUES (1,60,2,'211')
INSERT #F VALUES (1,61,2,'212')
INSERT #F VALUES (1,62,2,'213')
INSERT #F VALUES (1,63,2,'230')
INSERT #F VALUES (1,64,2,'260')
INSERT #F VALUES (1,65,2,'290')
INSERT #F VALUES (1,66,2,'291                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,67,2,'292')
INSERT #F VALUES (1,68,2,'293')
INSERT #F VALUES (1,69,2,'310')
INSERT #F VALUES (1,70,2,'320')
INSERT #F VALUES (1,71,2,'330')
INSERT #F VALUES (1,72,2,'331')
INSERT #F VALUES (1,73,2,'333')
INSERT #F VALUES (1,74,2,'370')
INSERT #F VALUES (1,75,2,'371')
INSERT #F VALUES (1,76,2,'372')
INSERT #F VALUES (1,77,2,'373')
INSERT #F VALUES (1,78,2,'400                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,79,2,'410')
INSERT #F VALUES (1,80,2,'470')
INSERT #F VALUES (1,81,2,'471')
INSERT #F VALUES (1,82,2,'472')
INSERT #F VALUES (1,83,2,'473')
INSERT #F VALUES (1,84,2,'474')
INSERT #F VALUES (1,85,2,'490')
INSERT #F VALUES (1,86,2,'510')
INSERT #F VALUES (1,87,2,'511')
INSERT #F VALUES (1,88,2,'512                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,89,2,'513')
INSERT #F VALUES (1,90,2,'514')
INSERT #F VALUES (1,91,2,'515                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,92,2,'516                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,93,2,'530')
INSERT #F VALUES (1,94,2,'531                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,95,2,'532 ')
INSERT #F VALUES (1,96,2,'533')
INSERT #F VALUES (1,97,2,'534')
INSERT #F VALUES (1,98,2,'600')
INSERT #F VALUES (1,99,2,'610                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,100,2,'620                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,101,2,'623')
INSERT #F VALUES (1,102,2,'624')
INSERT #F VALUES (1,103,2,'625')
INSERT #F VALUES (1,104,2,'690                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,105,2,'800                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,106,2,'900                                                                                                                                                                                                                                                       ')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 212
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

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] = '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-03-05 10:26:39.323',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-03-05 10:26:39.323'
	BEGIN
		SELECT @vcMessage = 'Форма 0503373GSV с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0503373GSV с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-03-05 10:26:39.323. Обновление отклонено.'
	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. (мар  5 2014 10:26:30:300AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0503373G (Сведения об изменении остатков валюты баланса (бюджетная деятельность))
-- Дата ввода : 20120101
-- Дата окончания действия :
-- Версия : 2014-03-05 10:26:30.297
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : нет
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

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] = '0503373G' AND [START_DATE] = '20120101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-03-05 10:26:30.297',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_' + '0503373G',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 = '0503373G'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20120101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. 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,7,1,1,1,18186,'RO_EXPORT_FORM_373#RO_IMPORT_FORM_373',0,1,'19000101',NULL,'191н'
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, '','SV_0503373_20111231.BAS','','KirRepMakerMultiSheet.xls','SV_0503373G_20120101.XLT','',NULL,'RO_EXPORT_FORM_373#RO_IMPORT_FORM_373',0,'COL2 + ''|'' + STR(COL3) + ''|'' + STR(COL4) + ''|'' + STR(COL5) + ''|''# ''000|0|''  + SUBSTRING(COL1,2,5) + ''|'' + SUBSTRING(COL1,7,3) + ''|'' + dbo.RO_EXP(COL3) + ''|'' + dbo.RO_EXP(COL4) + ''|'' + STR(COL2) + ''|'' + dbo.RO_EXP(COL5) + ''|''','C1+''|'' +C2 +''|'' +C3+''|'' +C4+''|'' #C2+C3+C4+''|'' +C7 +''|'' +C5+''|'' +C6+''|'' +C8+''|'' + C2+C3+C4+C5+C6+''|''',NULL,'473       ','',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,1,0,256,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,3,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,'Остаток на начало отчетного финансового года',@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,'Сумма расхождения, руб',@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


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,1,1,1,0,9,1,'R_SPR_173_2011','COL1','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, 2,'Сумма расхождения, руб',@iLINK_TABLE,1,0,2,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, 3,'Реквизиты контрагента. Код главы по БК',@iLINK_TABLE,1,1,3,0,3,1,'R_SPR_ADM_2011','COL3','CODE','NNN',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,14,1,'R_SPR_OKATO_173_373','COL4','OKATO','NNNNNNNNNNNNNN',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,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, 6,'Составной ключ',@iLINK_TABLE,1,1,6,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
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Причина изменений', @iLINK_FORM,2, @iLINK_CODE_COL,1,'KEY_FOX=PADR(RTRIM(COL1),9,''0'')+LEFT(COL3+''    '',3)+LEFT(COL4+''        '',8)
KEY_WEB=LEFT(RTRIM(isnull(COL1,''''))+''000000000'',9)+LEFT(RTRIM(ISNULL(COL3,''''))+''   '',3)+LEFT(RTRIM(ISNULL(COL4,''''))+''        '',8)
SPLIT=COL1=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',1,9)#COL3=SUBSTRING(RTRIM(CODE_ROW)+'''',10,3)#COL4=SUBSTRING(RTRIM(CODE_ROW)+'''',13,8)','-1#LEFT(CODE,9)=''888888888''
1#LEFT(CODE,9)=''999999999''
2#SUBSTRING(CODE,2,5) in (''30100'',''30200'',''30300'',''30400'',''40100'',''40200'')',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,2,1)
INSERT #R VALUES (3,1,3,1)
INSERT #R VALUES (4,1,4,1)
INSERT #R VALUES (5,1,5,1)
INSERT #R VALUES (6,1,6,1)
INSERT #R VALUES (7,1,7,1)
INSERT #R VALUES (8,1,8,1)
INSERT #R VALUES (9,1,9,1)
INSERT #R VALUES (10,1,10,1)
INSERT #R VALUES (11,1,11,1)
INSERT #R VALUES (12,1,12,1)
INSERT #R VALUES (13,1,13,1)
INSERT #R VALUES (14,1,14,1)
INSERT #R VALUES (15,1,15,1)
INSERT #R VALUES (16,1,16,1)
INSERT #R VALUES (17,1,17,1)
INSERT #R VALUES (18,1,18,1)
INSERT #R VALUES (19,1,19,1)
INSERT #R VALUES (20,1,20,1)
INSERT #R VALUES (21,1,21,1)
INSERT #R VALUES (22,1,22,1)
INSERT #R VALUES (23,1,23,1)
INSERT #R VALUES (24,1,24,1)
INSERT #R VALUES (25,1,25,1)
INSERT #R VALUES (26,1,26,1)
INSERT #R VALUES (27,1,27,1)
INSERT #R VALUES (28,1,28,1)
INSERT #R VALUES (29,1,29,1)
INSERT #R VALUES (30,1,30,1)
INSERT #R VALUES (31,1,31,1)
INSERT #R VALUES (32,1,32,1)
INSERT #R VALUES (33,1,33,1)
INSERT #R VALUES (34,1,34,1)
INSERT #R VALUES (35,1,35,1)
INSERT #R VALUES (36,1,36,1)
INSERT #R VALUES (37,1,37,1)
INSERT #R VALUES (38,1,38,1)
INSERT #R VALUES (39,1,39,1)
INSERT #R VALUES (40,1,40,1)
INSERT #R VALUES (41,1,41,1)
INSERT #R VALUES (42,1,42,1)
INSERT #R VALUES (43,1,43,1)
INSERT #R VALUES (44,1,44,1)
INSERT #R VALUES (45,1,45,1)
INSERT #R VALUES (46,1,46,1)
INSERT #R VALUES (47,1,47,1)
INSERT #R VALUES (48,1,48,1)
INSERT #R VALUES (49,1,49,1)
INSERT #R VALUES (50,1,50,1)
INSERT #R VALUES (51,1,51,1)
INSERT #R VALUES (52,1,52,1)
INSERT #R VALUES (53,1,53,1)
INSERT #R VALUES (54,1,54,1)
INSERT #R VALUES (55,1,55,1)
INSERT #R VALUES (56,1,56,1)
INSERT #R VALUES (57,1,57,1)
INSERT #R VALUES (58,1,58,1)
INSERT #R VALUES (59,1,59,1)
INSERT #R VALUES (60,1,60,1)
INSERT #R VALUES (61,1,61,1)
INSERT #R VALUES (62,1,62,1)
INSERT #R VALUES (63,1,63,1)
INSERT #R VALUES (64,1,64,1)
INSERT #R VALUES (65,1,65,1)
INSERT #R VALUES (66,1,66,1)
INSERT #R VALUES (67,1,67,1)
INSERT #R VALUES (68,1,68,1)
INSERT #R VALUES (69,1,69,1)
INSERT #R VALUES (70,1,70,1)
INSERT #R VALUES (71,1,71,1)
INSERT #R VALUES (72,1,72,1)
INSERT #R VALUES (73,1,73,1)
INSERT #R VALUES (74,1,74,1)
INSERT #R VALUES (75,1,75,1)
INSERT #R VALUES (76,1,76,1)
INSERT #R VALUES (77,1,77,1)
INSERT #R VALUES (78,1,78,1)
INSERT #R VALUES (79,1,79,1)
INSERT #R VALUES (80,1,80,1)
INSERT #R VALUES (81,1,81,1)
INSERT #R VALUES (82,1,82,1)
INSERT #R VALUES (83,1,83,1)
INSERT #R VALUES (84,1,84,1)
INSERT #R VALUES (85,1,85,1)
INSERT #R VALUES (86,1,86,1)
INSERT #R VALUES (87,1,87,1)
INSERT #R VALUES (88,1,88,1)
INSERT #R VALUES (89,1,89,1)
INSERT #R VALUES (90,1,90,1)
INSERT #R VALUES (91,1,91,1)
INSERT #R VALUES (92,1,92,1)
INSERT #R VALUES (93,1,93,1)
INSERT #R VALUES (94,1,94,1)
INSERT #R VALUES (95,1,95,1)
INSERT #R VALUES (96,1,96,1)
INSERT #R VALUES (97,1,97,1)
INSERT #R VALUES (98,1,98,1)
INSERT #R VALUES (99,1,99,1)
INSERT #R VALUES (100,1,103,1)
INSERT #R VALUES (101,1,99,1)
INSERT #R VALUES (102,1,100,1)
INSERT #R VALUES (103,1,101,1)
INSERT #R VALUES (104,1,104,1)
INSERT #R VALUES (105,1,106,1)
INSERT #R VALUES (106,1,102,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 106
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,' Основные средства (балансовая стоимость, 010100000), всего                                                                                      ')
INSERT #F VALUES (1,2,1,'    в том числе: недвижимое имущество учреждения (010110000) ')
INSERT #F VALUES (1,3,1,'    иное движимое имущество учреждения (010130000)')
INSERT #F VALUES (1,4,1,'    предметы лизинга (010140000) ')
INSERT #F VALUES (1,5,1,' Амортизация основных средств')
INSERT #F VALUES (1,6,1,'    в том числе: Амортизация недвижимого имущества учреждения (010410000) ')
INSERT #F VALUES (1,7,1,' Амортизация иного движимого имущества учреждения (010430000) ')
INSERT #F VALUES (1,8,1,' Амортизация предметов лизинга (010440000)')
INSERT #F VALUES (1,9,1,' Основные средства (остаточная стоимость, стр.010 -  стр.020)                                                                                             ')
INSERT #F VALUES (1,10,1,'    из них: недвижимое имущество учреждения (остаточная стоимость, стр.011 -  стр.021)                                                                                             ')
INSERT #F VALUES (1,11,1,'    иное движимое имущество учреждения (остаточная стоимость, стр.013 -  стр.023)                                                                                             ')
INSERT #F VALUES (1,12,1,'    предметы лизинга (остаточная стоимость, стр.014 -  стр.024)                                                                                             ')
INSERT #F VALUES (1,13,1,' Нематериальные активы (балансовая стоимость, 010200000)*, всего                                                           ')
INSERT #F VALUES (1,14,1,'    из них: иное движимое имущество учреждения (010230000) *')
INSERT #F VALUES (1,15,1,'    предметы лизинга  (010240000) *')
INSERT #F VALUES (1,16,1,' Амортизация нематериальных активов *')
INSERT #F VALUES (1,17,1,'    из них: иного движимого имущества учреждения (010439000) *')
INSERT #F VALUES (1,18,1,'    предметов лизинга  (010449000) *')
INSERT #F VALUES (1,19,1,' Нематериальные активы (остаточная стоимость, стр. 040 -  стр.050)                                                                                              ')
INSERT #F VALUES (1,20,1,'    из них: иное движимое имущество учреждения (остаточная стоимость, стр. 042 -  стр.052)                                                                                              ')
INSERT #F VALUES (1,21,1,'    предметы лизинга (остаточная стоимость, стр. 043 -  стр.053)                                                                                              ')
INSERT #F VALUES (1,22,1,' Непроизведенные активы (балансовая стоимость, 010300000)                                                                                             ')
INSERT #F VALUES (1,23,1,' Материальные запасы (010500000)')
INSERT #F VALUES (1,24,1,' Вложения в нефинансовые активы (010600000)')
INSERT #F VALUES (1,25,1,'    из них: в недвижимое имущество учреждения (010610000)')
INSERT #F VALUES (1,26,1,'    в иное движимое имущество учреждения (010630000)')
INSERT #F VALUES (1,27,1,'    в предметы лизинга (010640000)')
INSERT #F VALUES (1,28,1,' Нефинансовые активы в пути (010700000)')
INSERT #F VALUES (1,29,1,'    из них: недвижимое имущество учреждения в пути (010710000)')
INSERT #F VALUES (1,30,1,'    иное движимое имущество учреждения в пути (010730000)')
INSERT #F VALUES (1,31,1,'    предметы лизинга в пути (010740000)')
INSERT #F VALUES (1,32,1,' Нефинансовые активы имущества казны (балансовая стоимость, 010800000)*')
INSERT #F VALUES (1,33,1,' Амортизация имущества, составляющего казну  (010450000) *                                                                                      ')
INSERT #F VALUES (1,34,1,' Нефинансовые активы имущества казны (остаточная стоимость, стр. 110 - стр. 120)')
INSERT #F VALUES (1,35,1,' Затраты на изготовление готовой продукции, выполнение работ, услуг (010900000)')
INSERT #F VALUES (1,36,1,' Итого по разделу I (стр.030 + стр.060 + стр.070 + стр.080 + стр.090 + стр.100 + стр.130 + стр. 140)')
INSERT #F VALUES (1,37,1,' Денежные средства учреждения (020100000)')
INSERT #F VALUES (1,38,1,'    в том числе: денежные средства учреждения на лицевых счетах в органе казначейства (020111000)')
INSERT #F VALUES (1,39,1,'    денежные средства учреждения в органе казначейства в пути (020113000)')
INSERT #F VALUES (1,40,1,'    денежные средства учреждения на счетах в кредитной организации (020121000)')
INSERT #F VALUES (1,41,1,'    денежные средства учреждения в кредитной организации в пути (020123000)')
INSERT #F VALUES (1,42,1,'    аккредитивы на счетах учреждения в кредитной организации (020126000)')
INSERT #F VALUES (1,43,1,'    денежные средства учреждения в иностранной валюте на счетах в кредитной организации (020127000)')
INSERT #F VALUES (1,44,1,'    касса (020134000)')
INSERT #F VALUES (1,45,1,'    денежные документы (020135000)')
INSERT #F VALUES (1,46,1,'    денежные средства учреждения, размещенные на депозиты в кредитной организации (020122000)')
INSERT #F VALUES (1,47,1,' Средства на счетах бюджета в органе Федерального казначейства (020210000)')
INSERT #F VALUES (1,48,1,'    в том числе: средства на счетах бюджета в рублях в органе Федерального казначейства (020211000)')
INSERT #F VALUES (1,49,1,'    средства на счетах бюджета в органе Федерального казначейства в пути (020212000)')
INSERT #F VALUES (1,50,1,'    средства на счетах бюджета в иностранной валюте в органах Федерального казначейства (020213000)')
INSERT #F VALUES (1,51,1,' Средства на счетах бюджета в кредитной организации (020220000)')
INSERT #F VALUES (1,52,1,'    в том числе: средства на счетах бюджета в рублях в кредитной организации (020221000)')
INSERT #F VALUES (1,53,1,'    средства на счетах бюджета в кредитной организации в пути (020222000)')
INSERT #F VALUES (1,54,1,'    средства на счетах бюджета в иностранной валюте в кредитной организации (020223000)')
INSERT #F VALUES (1,55,1,' Средства бюджета на депозитных счетах (020230000)')
INSERT #F VALUES (1,56,1,'    в том числе: средства бюджета на депозитных счетах в рублях (020231000)')
INSERT #F VALUES (1,57,1,'    средства бюджета на депозитных счетах в пути (020232000)')
INSERT #F VALUES (1,58,1,'    средства бюджета на депозитных счетах в иностранной валюте (020233000)')
INSERT #F VALUES (1,59,1,' Финансовые вложения (020400000)')
INSERT #F VALUES (1,60,1,'    в том числе: ценные бумаги, кроме акций  (020420000)')
INSERT #F VALUES (1,61,1,'    акции и иные формы участия в капитале (020430000)')
INSERT #F VALUES (1,62,1,'    иные финансовые активы (020450000)')
INSERT #F VALUES (1,63,1,' Расчеты по доходам (020500000)')
INSERT #F VALUES (1,64,1,' Расчеты по выданным авансам (020600000)')
INSERT #F VALUES (1,65,1,' Расчеты по кредитам, займам, ссудам (020700000)')
INSERT #F VALUES (1,66,1,'    в том числе: по предоставленным кредитам, ссудам, займам (020710000)')
INSERT #F VALUES (1,67,1,'    в рамках целевых иностранных кредитов (заимствований) (020720000)')
INSERT #F VALUES (1,68,1,'    с дебиторами по государственным (муниципальным) гарантиям (020730000)')
INSERT #F VALUES (1,69,1,' Расчеты с подотчетными лицами (020800000)')
INSERT #F VALUES (1,70,1,' Расчеты по ущербу имуществу (020900000)')
INSERT #F VALUES (1,71,1,' Прочие расчеты с дебиторами (021000000)')
INSERT #F VALUES (1,72,1,'    из них: расчеты по НДС по приобретенным материальным ценностям, работам, услугам (021001000)')
INSERT #F VALUES (1,73,1,'    расчеты с финансовым органом по наличным денежным средствам (021003000)')
INSERT #F VALUES (1,74,1,' Вложения в финансовые активы (021500000)')
INSERT #F VALUES (1,75,1,'    в том числе: ценные бумаги, кроме акций  (021520000)')
INSERT #F VALUES (1,76,1,'    акции и иные формы участия в капитале (021530000)')
INSERT #F VALUES (1,77,1,'    иные финансовые активы (021550000)')
INSERT #F VALUES (1,78,1,'Итого по разделу II (стр.170 + стр.180 + стр.190 + стр.200 + стр.210 + стр.230 + стр.260 + стр.290 + стр.310 + стр.320 + стр. 330 + стр.370)')
INSERT #F VALUES (1,79,1,' БАЛАНС (стр.150 + стр. 400)')
INSERT #F VALUES (1,80,1,' Расчеты с кредиторами по долговым обязательствам (030100000)')
INSERT #F VALUES (1,81,1,'    в том числе: по долговым обязательствам в рублях (030110000)')
INSERT #F VALUES (1,82,1,'    по долговым обязательствам по целевым иностранныи кредитам (заимствованиям) (030120000)')
INSERT #F VALUES (1,83,1,'    по государственным (муниципальным) гарантиям (03013000)')
INSERT #F VALUES (1,84,1,'    по долговым обязательствам в иностранной валюте (030140000)')
INSERT #F VALUES (1,85,1,' Расчеты по принятым обязательствам (030200000)')
INSERT #F VALUES (1,86,1,' Расчеты по платежам в бюджеты (030300000)')
INSERT #F VALUES (1,87,1,'    из них: расчеты по налогу на доходы физических лиц (030301000)')
INSERT #F VALUES (1,88,1,'    расчеты по страховым взносам на обязательное социальное страхование (030302000, 030306000)')
INSERT #F VALUES (1,89,1,'    расчеты по налогу на прибыль организаций (030303000)')
INSERT #F VALUES (1,90,1,'    расчеты по налогу на добавленную стоимость (030304000)')
INSERT #F VALUES (1,91,1,'    расчеты по иным платежам в бюджет (030305000, 030312000, 030313000)')
INSERT #F VALUES (1,92,1,'    расчеты по страховым взносам на медицинское и пенисонное страхование (030307000, 030308000, 030309000, 030310000, 030311000)')
INSERT #F VALUES (1,93,1,' Прочие расчеты с кредиторами (030400000)')
INSERT #F VALUES (1,94,1,'    из них: расчеты по средствам, полученным во временное распоряжение (030401000)')
INSERT #F VALUES (1,95,1,'    расчеты с депонентами (030402000)')
INSERT #F VALUES (1,96,1,'    расчеты по удержаниям из выплат по оплате труда (030403000)')
INSERT #F VALUES (1,97,1,'    внутриведомственные  расчеты (030404000)')
INSERT #F VALUES (1,98,1,' Итого по разделу III (стр.470+ стр.490 + стр. 510 + стр.530)')
INSERT #F VALUES (1,99,1,'Финансовый результат(040000000)  (стр.620+стр.690)')
INSERT #F VALUES (1,100,1,'Финансовый результат хозяйствующего субъекта (040100000)')
INSERT #F VALUES (1,101,1,'    из них: финансовый результат прошлых отчетных периодов (040130000)')
INSERT #F VALUES (1,102,1,'    доходы будущих периодов (040140000)')
INSERT #F VALUES (1,103,1,'    расходы будущих периодов (040150000)')
INSERT #F VALUES (1,104,1,'Результат по кассовым операциям бюджета (040200000)')
INSERT #F VALUES (1,105,1,'Результат прошлых отчетных периодов по кассовому исполнению бюджета (040230000)')
INSERT #F VALUES (1,106,1,' БАЛАНС (стр.600 + стр. 610)')
INSERT #F VALUES (1,1,2,'010')
INSERT #F VALUES (1,2,2,'011')
INSERT #F VALUES (1,3,2,'013')
INSERT #F VALUES (1,4,2,'014')
INSERT #F VALUES (1,5,2,'020')
INSERT #F VALUES (1,6,2,'021')
INSERT #F VALUES (1,7,2,'023')
INSERT #F VALUES (1,8,2,'024')
INSERT #F VALUES (1,9,2,'030')
INSERT #F VALUES (1,10,2,'031')
INSERT #F VALUES (1,11,2,'033')
INSERT #F VALUES (1,12,2,'034')
INSERT #F VALUES (1,13,2,'040')
INSERT #F VALUES (1,14,2,'042')
INSERT #F VALUES (1,15,2,'043')
INSERT #F VALUES (1,16,2,'050')
INSERT #F VALUES (1,17,2,'052')
INSERT #F VALUES (1,18,2,'053')
INSERT #F VALUES (1,19,2,'060')
INSERT #F VALUES (1,20,2,'062')
INSERT #F VALUES (1,21,2,'063')
INSERT #F VALUES (1,22,2,'070')
INSERT #F VALUES (1,23,2,'080')
INSERT #F VALUES (1,24,2,'090')
INSERT #F VALUES (1,25,2,'091')
INSERT #F VALUES (1,26,2,'093')
INSERT #F VALUES (1,27,2,'094')
INSERT #F VALUES (1,28,2,'100')
INSERT #F VALUES (1,29,2,'101')
INSERT #F VALUES (1,30,2,'103')
INSERT #F VALUES (1,31,2,'104')
INSERT #F VALUES (1,32,2,'110')
INSERT #F VALUES (1,33,2,'120')
INSERT #F VALUES (1,34,2,'130')
INSERT #F VALUES (1,35,2,'140')
INSERT #F VALUES (1,36,2,'150')
INSERT #F VALUES (1,37,2,'170')
INSERT #F VALUES (1,38,2,'171')
INSERT #F VALUES (1,39,2,'172                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,40,2,'173')
INSERT #F VALUES (1,41,2,'174')
INSERT #F VALUES (1,42,2,'175')
INSERT #F VALUES (1,43,2,'176')
INSERT #F VALUES (1,44,2,'177')
INSERT #F VALUES (1,45,2,'178')
INSERT #F VALUES (1,46,2,'179')
INSERT #F VALUES (1,47,2,'180')
INSERT #F VALUES (1,48,2,'181')
INSERT #F VALUES (1,49,2,'182')
INSERT #F VALUES (1,50,2,'183')
INSERT #F VALUES (1,51,2,'190')
INSERT #F VALUES (1,52,2,'191')
INSERT #F VALUES (1,53,2,'192')
INSERT #F VALUES (1,54,2,'193')
INSERT #F VALUES (1,55,2,'200')
INSERT #F VALUES (1,56,2,'201')
INSERT #F VALUES (1,57,2,'202')
INSERT #F VALUES (1,58,2,'203')
INSERT #F VALUES (1,59,2,'210')
INSERT #F VALUES (1,60,2,'211')
INSERT #F VALUES (1,61,2,'212')
INSERT #F VALUES (1,62,2,'213')
INSERT #F VALUES (1,63,2,'230')
INSERT #F VALUES (1,64,2,'260')
INSERT #F VALUES (1,65,2,'290')
INSERT #F VALUES (1,66,2,'291                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,67,2,'292')
INSERT #F VALUES (1,68,2,'293')
INSERT #F VALUES (1,69,2,'310')
INSERT #F VALUES (1,70,2,'320')
INSERT #F VALUES (1,71,2,'330')
INSERT #F VALUES (1,72,2,'331')
INSERT #F VALUES (1,73,2,'333')
INSERT #F VALUES (1,74,2,'370')
INSERT #F VALUES (1,75,2,'371')
INSERT #F VALUES (1,76,2,'372')
INSERT #F VALUES (1,77,2,'373')
INSERT #F VALUES (1,78,2,'400                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,79,2,'410')
INSERT #F VALUES (1,80,2,'470')
INSERT #F VALUES (1,81,2,'471')
INSERT #F VALUES (1,82,2,'472')
INSERT #F VALUES (1,83,2,'473')
INSERT #F VALUES (1,84,2,'474')
INSERT #F VALUES (1,85,2,'490')
INSERT #F VALUES (1,86,2,'510')
INSERT #F VALUES (1,87,2,'511')
INSERT #F VALUES (1,88,2,'512                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,89,2,'513')
INSERT #F VALUES (1,90,2,'514')
INSERT #F VALUES (1,91,2,'515                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,92,2,'516                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,93,2,'530')
INSERT #F VALUES (1,94,2,'531                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,95,2,'532 ')
INSERT #F VALUES (1,96,2,'533')
INSERT #F VALUES (1,97,2,'534')
INSERT #F VALUES (1,98,2,'600')
INSERT #F VALUES (1,99,2,'610                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,100,2,'620                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,101,2,'623')
INSERT #F VALUES (1,102,2,'624')
INSERT #F VALUES (1,103,2,'625')
INSERT #F VALUES (1,104,2,'690                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,105,2,'800                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,106,2,'900                                                                                                                                                                                                                                                       ')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 212
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

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] = '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-03-05 10:26:30.297',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-03-05 10:26:30.297'
	BEGIN
		SELECT @vcMessage = 'Форма 0503373G с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0503373G с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-03-05 10:26:30.297. Обновление отклонено.'
	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. (мар  5 2014 11:42:38:153AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0503773G (Сведения об изменении остатков валюты баланса учреждения)
-- Дата ввода : 20121231
-- Дата окончания действия :
-- Версия : 2014-03-05 11:42:38.150
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

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] = '0503773G' AND [START_DATE] = '20121231'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-03-05 11:42:38.150',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_' + '0503773G',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 = '0503773G'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20121231')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. 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,'RO_EXPORT_FORM_33#RO_IMPORT_FORM_773',0,1,'19000101',NULL,'33н'
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, '','SV_0503773_20121231.BAS','','KirRepMakerMultiSheet.xls','SV_0503773G_20121231.XLT','',NULL,'RO_EXPORT_FORM_33#RO_IMPORT_FORM_773',0,'LEFT(RTRIM(COL2) + ''0000'',4) + ''|'' + STR(COL3) + ''|'' + STR(COL4) + ''|'' + STR(COL5) + ''|''  # LEFT(COL1,1) + ''|'' + SUBSTRING(COL1,2,5) + ''|'' + SUBSTRING(COL1,7,3) + ''|'' + dbo.RO_EXP(COL3) +''|'' + dbo.RO_EXP(COL4) + ''|'' + STR(COL2) + ''|'' + dbo.RO_EXP(COL5) + ''|''','LEFT(C1,3) + ''|'' + C2 + ''|'' + C3 + ''|'' + C4 # C1 + C2 + C3 + ''|'' + C6 + ''|'' + C4 + ''| '' + C5 + ''|'' + C7 + ''|''  +  C1 + C2 + C3 + C4 + C5',NULL,'373       ','REPORTS_ATR_TYPE_ORG,REPORTS_ATR_VID_773,REPORTS_ATR_VID_NAME_773',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,1,0,256,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,4,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,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,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, 5,'Сумма расхождения, руб.',@iLINK_TABLE,1,0,5,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, 'Изменение остатков валюты баланса', @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,1,1,1,0,9,1,'R_SPR_173_2011','COL1','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, 2,'Сумма расхождения, руб.',@iLINK_TABLE,1,0,2,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, 3,'Реквизиты контрагента  код главы по БК',@iLINK_TABLE,1,1,3,0,3,1,'R_SPR_ADM_2011','COL3','CODE',NULL,NULL,NULL,'%date%>=begin_date and %date%<=end_date'
IF @iERROR <> 0
BEGIN
   INSERT #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,14,1,'R_SPR_OKATO_173_373','COL4','OKATO',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,256,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,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
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Причина изменений', @iLINK_FORM,2, @iLINK_CODE_COL,1,'KEY_FOX=PADR(RTRIM(COL1),9,''0'')+LEFT(COL3+''    '',3)+LEFT(COL4+''        '',8)
KEY_WEB=LEFT(RTRIM(isnull(COL1,''''))+''000000000'',9)+LEFT(RTRIM(ISNULL(COL3,''''))+''   '',3)+LEFT(RTRIM(ISNULL(COL4,''''))+''        '',8)
SPLIT=COL1=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',1,9)#COL3=SUBSTRING(RTRIM(CODE_ROW)+'''',10,3)#COL4=SUBSTRING(RTRIM(CODE_ROW)+'''',13,8)','-1#LEFT(CODE,9)=''888888888''
1#LEFT(CODE,9)=''999999999''
2#SUBSTRING(CODE,2,5) in (''30100'',''30200'',''30300'',''30400'',''40100'',''40200'')',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,2,1)
INSERT #R VALUES (3,1,3,1)
INSERT #R VALUES (4,1,4,1)
INSERT #R VALUES (5,1,5,1)
INSERT #R VALUES (6,1,6,1)
INSERT #R VALUES (7,1,7,1)
INSERT #R VALUES (8,1,8,1)
INSERT #R VALUES (9,1,9,1)
INSERT #R VALUES (10,1,10,1)
INSERT #R VALUES (11,1,11,1)
INSERT #R VALUES (12,1,12,1)
INSERT #R VALUES (13,1,13,1)
INSERT #R VALUES (14,1,14,1)
INSERT #R VALUES (15,1,15,1)
INSERT #R VALUES (16,1,16,1)
INSERT #R VALUES (17,1,17,1)
INSERT #R VALUES (18,1,18,1)
INSERT #R VALUES (19,1,19,1)
INSERT #R VALUES (20,1,20,1)
INSERT #R VALUES (21,1,21,1)
INSERT #R VALUES (22,1,22,1)
INSERT #R VALUES (23,1,23,1)
INSERT #R VALUES (24,1,24,1)
INSERT #R VALUES (25,1,25,1)
INSERT #R VALUES (26,1,26,1)
INSERT #R VALUES (27,1,27,1)
INSERT #R VALUES (28,1,28,1)
INSERT #R VALUES (29,1,29,1)
INSERT #R VALUES (30,1,30,1)
INSERT #R VALUES (31,1,31,1)
INSERT #R VALUES (32,1,32,1)
INSERT #R VALUES (33,1,33,1)
INSERT #R VALUES (34,1,34,1)
INSERT #R VALUES (35,1,35,1)
INSERT #R VALUES (36,1,36,1)
INSERT #R VALUES (37,1,37,1)
INSERT #R VALUES (38,1,38,1)
INSERT #R VALUES (39,1,39,1)
INSERT #R VALUES (40,1,40,1)
INSERT #R VALUES (41,1,41,1)
INSERT #R VALUES (42,1,42,1)
INSERT #R VALUES (43,1,43,1)
INSERT #R VALUES (44,1,44,1)
INSERT #R VALUES (45,1,45,1)
INSERT #R VALUES (46,1,46,1)
INSERT #R VALUES (47,1,47,1)
INSERT #R VALUES (48,1,48,1)
INSERT #R VALUES (49,1,49,1)
INSERT #R VALUES (50,1,50,1)
INSERT #R VALUES (51,1,51,1)
INSERT #R VALUES (52,1,52,1)
INSERT #R VALUES (53,1,53,1)
INSERT #R VALUES (54,1,54,1)
INSERT #R VALUES (55,1,55,1)
INSERT #R VALUES (56,1,56,1)
INSERT #R VALUES (57,1,57,1)
INSERT #R VALUES (58,1,58,1)
INSERT #R VALUES (59,1,59,1)
INSERT #R VALUES (60,1,60,1)
INSERT #R VALUES (61,1,61,1)
INSERT #R VALUES (62,1,62,1)
INSERT #R VALUES (63,1,63,1)
INSERT #R VALUES (64,1,64,1)
INSERT #R VALUES (65,1,65,1)
INSERT #R VALUES (66,1,66,1)
INSERT #R VALUES (67,1,67,1)
INSERT #R VALUES (68,1,68,1)
INSERT #R VALUES (69,1,69,1)
INSERT #R VALUES (70,1,70,1)
INSERT #R VALUES (71,1,69,1)
INSERT #R VALUES (72,1,70,1)
INSERT #R VALUES (73,1,71,1)
INSERT #R VALUES (74,1,72,1)
INSERT #R VALUES (75,1,73,1)
INSERT #R VALUES (76,1,74,1)
INSERT #R VALUES (77,1,75,1)
INSERT #R VALUES (78,1,76,1)
INSERT #R VALUES (79,1,77,1)
INSERT #R VALUES (80,1,78,1)
INSERT #R VALUES (81,1,79,1)
INSERT #R VALUES (82,1,80,1)
INSERT #R VALUES (83,1,81,1)
INSERT #R VALUES (84,1,82,1)
INSERT #R VALUES (85,1,83,1)
INSERT #R VALUES (86,1,84,1)
INSERT #R VALUES (87,1,85,1)
INSERT #R VALUES (88,1,86,1)
INSERT #R VALUES (89,1,87,1)
INSERT #R VALUES (90,1,88,1)
INSERT #R VALUES (91,1,89,1)
INSERT #R VALUES (92,1,90,1)
INSERT #R VALUES (93,1,91,1)
INSERT #R VALUES (94,1,92,1)
INSERT #R VALUES (95,1,93,1)
INSERT #R VALUES (96,1,94,1)
INSERT #R VALUES (97,1,95,1)
INSERT #R VALUES (98,1,98,1)
INSERT #R VALUES (99,1,96,1)
INSERT #R VALUES (100,1,97,1)
INSERT #R VALUES (101,1,98,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 101
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,' Основные средства (балансовая стоимость, 010100000), всего                                                                                      ')
INSERT #F VALUES (1,2,1,'    в том числе: недвижимое имущество учреждения (010110000)')
INSERT #F VALUES (1,3,1,'    особо ценное движимое имущество учреждения (010120000)')
INSERT #F VALUES (1,4,1,'    иное движимое имущество учреждения (010130000)')
INSERT #F VALUES (1,5,1,'    предметы лизинга (010140000) ')
INSERT #F VALUES (1,6,1,' Амортизация основных средств')
INSERT #F VALUES (1,7,1,'    в том числе: Амортизация недвижимого имущества учреждения (010410000)')
INSERT #F VALUES (1,8,1,' Амортизация особо ценного движимого имущества учреждения (010420000) ')
INSERT #F VALUES (1,9,1,' Амортизация иного движимого имущества учреждения (010430000) ')
INSERT #F VALUES (1,10,1,' Амортизация предметов лизинга (010440000)')
INSERT #F VALUES (1,11,1,' Основные средства (остаточная стоимость, стр.010 -  стр.020)                                                                                             ')
INSERT #F VALUES (1,12,1,'    из них: недвижимое имущество учреждения (остаточная стоимость, стр.011 -  стр.021)                                                                                             ')
INSERT #F VALUES (1,13,1,'    особо ценное движимое имущество учреждения (остаточная стоимость, стр.012 -  стр.022)                                                                                             ')
INSERT #F VALUES (1,14,1,'    иное движимое имущество учреждения (остаточная стоимость, стр.013 -  стр.023)                                                                                             ')
INSERT #F VALUES (1,15,1,'    предметы лизинга (остаточная стоимость, стр.014 -  стр.024)                                                                                             ')
INSERT #F VALUES (1,16,1,' Нематериальные активы (балансовая стоимость, 010200000)*, всего                                                           ')
INSERT #F VALUES (1,17,1,'    из них: особо ценное движимое имущество учреждения (010220000)*')
INSERT #F VALUES (1,18,1,'    иное движимое имущество учреждения (010230000)*')
INSERT #F VALUES (1,19,1,'    предметы лизинга  (010240000) *')
INSERT #F VALUES (1,20,1,' Амортизация нематериальных активов *')
INSERT #F VALUES (1,21,1,'    из них: особо ценного движимого имущества учреждения  (010429000)*')
INSERT #F VALUES (1,22,1,'    иного движимого имущества учреждения (010439000) *')
INSERT #F VALUES (1,23,1,'    предметов лизинга  (010449000) *')
INSERT #F VALUES (1,24,1,' Нематериальные активы (остаточная стоимость, стр. 040 -  стр.050)                                                                                              ')
INSERT #F VALUES (1,25,1,'    из них: особо ценное движимое имущество учреждения (остаточная стоимость, стр. 041 -  стр.051)')
INSERT #F VALUES (1,26,1,'    иное движимое имущество учреждения (остаточная стоимость, стр. 042 -  стр.052)                                                                                              ')
INSERT #F VALUES (1,27,1,'    предметы лизинга (остаточная стоимость, стр. 043 -  стр.053)                                                                                              ')
INSERT #F VALUES (1,28,1,' Непроизведенные активы (балансовая стоимость, 010300000)                                                                                             ')
INSERT #F VALUES (1,29,1,' Материальные запасы (010500000)')
INSERT #F VALUES (1,30,1,'    из них: особо ценное движимое имущество учреждения (010520000)')
INSERT #F VALUES (1,31,1,' Вложения в нефинансовые активы (010600000)')
INSERT #F VALUES (1,32,1,'    из них: в недвижимое имущество учреждения (010610000)')
INSERT #F VALUES (1,33,1,'    в особо ценное движимое имущество учреждения (010620000)')
INSERT #F VALUES (1,34,1,'    в иное движимое имущество учреждения (010630000)')
INSERT #F VALUES (1,35,1,'    в предметы лизинга (010640000)')
INSERT #F VALUES (1,36,1,' Нефинансовые активы в пути (010700000)')
INSERT #F VALUES (1,37,1,'    из них: недвижимое имущество учреждения в пути (010710000)')
INSERT #F VALUES (1,38,1,'    особо ценное движимое имущество учреждения в пути (010720000)')
INSERT #F VALUES (1,39,1,'    иное движимое имущество учреждения в пути (010730000)')
INSERT #F VALUES (1,40,1,'    предметы лизинга в пути (010740000)')
INSERT #F VALUES (1,41,1,' Затраты на изготовление готовой продукции, выполнение работ, услуг (010900000)')
INSERT #F VALUES (1,42,1,' Итого по разделу I (стр.030 + стр.060 + стр.070 + стр.080 + стр.090 + стр.100  + стр. 140)')
INSERT #F VALUES (1,43,1,' Денежные средства учреждения (020100000)')
INSERT #F VALUES (1,44,1,'    в том числе: денежные средства учреждения на лицевых счетах в органе казначейства (020111000')
INSERT #F VALUES (1,45,1,'    денежные средства учреждения в пути в органе казначейства (020113000)')
INSERT #F VALUES (1,46,1,'    денежные средства учреждения на счетах в кредитной организации (020121000)')
INSERT #F VALUES (1,47,1,'    денежные средства учреждения в кредитной организации в пути (020123000)')
INSERT #F VALUES (1,48,1,'    аккредитивы на счетах учреждения в кредитной организации (020126000)')
INSERT #F VALUES (1,49,1,'    денежные средства учреждения в иностранной валюте на счетах в кредитной организации (020127000)')
INSERT #F VALUES (1,50,1,'    касса (020134000)')
INSERT #F VALUES (1,51,1,'    денежные документы (020135000)')
INSERT #F VALUES (1,52,1,'   денежные средства учреждения, размещенные на депозиты в кредитной организации (020122000)')
INSERT #F VALUES (1,53,1,' Финансовые вложения (020400000)')
INSERT #F VALUES (1,54,1,'    в том числе: ценные бумаги, кроме акций  (020420000)')
INSERT #F VALUES (1,55,1,'    акции и иные формы участия в капитале (020430000)')
INSERT #F VALUES (1,56,1,'    иные финансовые активы (020450000)')
INSERT #F VALUES (1,57,1,' Расчеты по доходам (020500000)')
INSERT #F VALUES (1,58,1,' Расчеты по выданным авансам (020600000)')
INSERT #F VALUES (1,59,1,' Расчеты по кредитам, займам (ссудам) (020700000)')
INSERT #F VALUES (1,60,1,'    в том числе: по представленным кредитам, ссудам, займам (020710000')
INSERT #F VALUES (1,61,1,'    в рамках целевых иностранных кредитов (заимствований) (020720000)')
INSERT #F VALUES (1,62,1,' Расчеты с подотчетными лицами (020800000)')
INSERT #F VALUES (1,63,1,' Расчеты по ущербу имуществу (020900000)')
INSERT #F VALUES (1,64,1,' Прочие расчеты с дебиторами (021000000)')
INSERT #F VALUES (1,65,1,'    из них: расчеты по НДС по приобретенным материальным ценностям, работам, услугам (021001000)')
INSERT #F VALUES (1,66,1,'    расчеты с финансовым органом по наличным денежным средствам (021003000)')
INSERT #F VALUES (1,67,1,'    расчеты с прочими дебиторами (021005000)')
INSERT #F VALUES (1,68,1,'    расчеты с учредителем (021006000)*')
INSERT #F VALUES (1,69,1,'    показатель уменьшения балансовой стоимости ОЦИ*')
INSERT #F VALUES (1,70,1,'   чистая стоимость ОЦИ (стр. 336 + стр.337)')
INSERT #F VALUES (1,71,1,' Вложения в финансовые активы (021500000)')
INSERT #F VALUES (1,72,1,'    в том числе: ценные бумаги, кроме акций  (021520000)')
INSERT #F VALUES (1,73,1,'    акции и иные формы участия в капитале (021530000)')
INSERT #F VALUES (1,74,1,'    иные финансовые активы (021550000)')
INSERT #F VALUES (1,75,1,' Итого по разделу II (стр.170  + стр.210 + стр.230 + стр.260 + стр.290 + стр.310 + стр.320 + стр. 330 + стр.370 )')
INSERT #F VALUES (1,76,1,' БАЛАНС (стр.150 + стр. 400)')
INSERT #F VALUES (1,77,1,' Расчеты с кредиторами по долговым обязательствам (030100000)')
INSERT #F VALUES (1,78,1,'    в том числе: по долговым обязательствам в рублях (030110000)')
INSERT #F VALUES (1,79,1,'    по долговым обязательствам по целевым иностранныи кредитам (заимствованиям) (030120000)')
INSERT #F VALUES (1,80,1,'    по долговым обязательствам в иностранной валюте (030140000)')
INSERT #F VALUES (1,81,1,' Расчеты по принятым обязательствам (030200000)')
INSERT #F VALUES (1,82,1,' Расчеты по платежам в бюджеты (030300000)')
INSERT #F VALUES (1,83,1,'    из них: расчеты по налогу на доходы физических лиц (030301000)')
INSERT #F VALUES (1,84,1,'    расчеты по страховым взносам на обязательное социальное страхование (030302000, 030306000)')
INSERT #F VALUES (1,85,1,'    расчеты по налогу на прибыль организаций (030303000)')
INSERT #F VALUES (1,86,1,'    расчеты по налогу на добавленную стоимость (030304000)')
INSERT #F VALUES (1,87,1,'    расчеты по иным платежам в бюджет (030305000, 030312000, 030313000)')
INSERT #F VALUES (1,88,1,'   расчеты по страховым взносам на медицинское и пенсионное страхование (030307000, 030308000, 030309000, 030310000, 030311000)')
INSERT #F VALUES (1,89,1,' Прочие расчеты с кредиторами (030400000)')
INSERT #F VALUES (1,90,1,'    из них: расчеты по средствам, полученным во временное распоряжение (030401000)')
INSERT #F VALUES (1,91,1,'    расчеты с депонентами (030402000)')
INSERT #F VALUES (1,92,1,'    расчеты по удержаниям из выплат по оплате труда (030403000)')
INSERT #F VALUES (1,93,1,'    внутриведомственные  расчеты (030404000)')
INSERT #F VALUES (1,94,1,'    расчеты с прочими кредиторами (030406000)')
INSERT #F VALUES (1,95,1,' Итого по разделу III (стр.470+ стр.490 + стр. 510 + стр.530)')
INSERT #F VALUES (1,96,1,' Финансовый результат хозяйствующего субъекта (040100000) (стр. 623 + стр.6231+ стр.624 +стр.625)')
INSERT #F VALUES (1,97,1,'    из них: финансовый результат прошлых отчетных периодов (040130000)')
INSERT #F VALUES (1,98,1,'    финансовый результат по начислению амортизации ОЦИ')
INSERT #F VALUES (1,99,1,'    доходы будущих периодов (040140000)')
INSERT #F VALUES (1,100,1,'    расходы будущих периодов (040150000)')
INSERT #F VALUES (1,101,1,' БАЛАНС (стр.600 + стр. 620)')
INSERT #F VALUES (1,1,2,'010                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,2,2,'011                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,3,2,'012                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,4,2,'013                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,5,2,'014                                                                                                                                                                                                                                                       ')
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,'030')
INSERT #F VALUES (1,12,2,'031')
INSERT #F VALUES (1,13,2,'032')
INSERT #F VALUES (1,14,2,'033')
INSERT #F VALUES (1,15,2,'034')
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,'051                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,22,2,'052')
INSERT #F VALUES (1,23,2,'053')
INSERT #F VALUES (1,24,2,'060')
INSERT #F VALUES (1,25,2,'061                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,26,2,'062')
INSERT #F VALUES (1,27,2,'063')
INSERT #F VALUES (1,28,2,'070')
INSERT #F VALUES (1,29,2,'080')
INSERT #F VALUES (1,30,2,'081                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,31,2,'090')
INSERT #F VALUES (1,32,2,'091')
INSERT #F VALUES (1,33,2,'092')
INSERT #F VALUES (1,34,2,'093')
INSERT #F VALUES (1,35,2,'094')
INSERT #F VALUES (1,36,2,'100')
INSERT #F VALUES (1,37,2,'101')
INSERT #F VALUES (1,38,2,'102                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,39,2,'103')
INSERT #F VALUES (1,40,2,'104')
INSERT #F VALUES (1,41,2,'140')
INSERT #F VALUES (1,42,2,'150')
INSERT #F VALUES (1,43,2,'170')
INSERT #F VALUES (1,44,2,'171                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,45,2,'172                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,46,2,'173                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,47,2,'174                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,48,2,'175')
INSERT #F VALUES (1,49,2,'176                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,50,2,'177')
INSERT #F VALUES (1,51,2,'178')
INSERT #F VALUES (1,52,2,'179                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,53,2,'210')
INSERT #F VALUES (1,54,2,'211')
INSERT #F VALUES (1,55,2,'212')
INSERT #F VALUES (1,56,2,'213')
INSERT #F VALUES (1,57,2,'230')
INSERT #F VALUES (1,58,2,'260')
INSERT #F VALUES (1,59,2,'290')
INSERT #F VALUES (1,60,2,'291                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,61,2,'292')
INSERT #F VALUES (1,62,2,'310')
INSERT #F VALUES (1,63,2,'320')
INSERT #F VALUES (1,64,2,'330')
INSERT #F VALUES (1,65,2,'331                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,66,2,'333')
INSERT #F VALUES (1,67,2,'335')
INSERT #F VALUES (1,68,2,'336                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,69,2,'337                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,70,2,'338                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,71,2,'370')
INSERT #F VALUES (1,72,2,'371')
INSERT #F VALUES (1,73,2,'372')
INSERT #F VALUES (1,74,2,'373')
INSERT #F VALUES (1,75,2,'400')
INSERT #F VALUES (1,76,2,'410')
INSERT #F VALUES (1,77,2,'470')
INSERT #F VALUES (1,78,2,'471')
INSERT #F VALUES (1,79,2,'472')
INSERT #F VALUES (1,80,2,'474')
INSERT #F VALUES (1,81,2,'490')
INSERT #F VALUES (1,82,2,'510')
INSERT #F VALUES (1,83,2,'511')
INSERT #F VALUES (1,84,2,'512                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,85,2,'513')
INSERT #F VALUES (1,86,2,'514')
INSERT #F VALUES (1,87,2,'515                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,88,2,'516                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,89,2,'530')
INSERT #F VALUES (1,90,2,'531')
INSERT #F VALUES (1,91,2,'532 ')
INSERT #F VALUES (1,92,2,'533')
INSERT #F VALUES (1,93,2,'534')
INSERT #F VALUES (1,94,2,'536                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,95,2,'600')
INSERT #F VALUES (1,96,2,'620                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,97,2,'623')
INSERT #F VALUES (1,98,2,'6231                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (1,99,2,'624')
INSERT #F VALUES (1,100,2,'625')
INSERT #F VALUES (1,101,2,'900                                                                                                                                                                                                                                                       ')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 202
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,'т.1стр.032 =  т.1стр.012 -  т.1стр.022',1,0,1,'20110725','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(2,NULL,0,NULL,2,7,0,0,0,'т.1стр.061 =  т.1стр.041 -  т.1стр.051',1,0,1,'20110725','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(3,NULL,0,NULL,3,7,0,0,0,'т.1стр.150 =  т.1стр.030 +  т.1стр.060 +  т.1стр.070 +  т.1стр.080 +  т.1стр.090 +  т.1стр.100 +  т.1стр.140',1,2,1,'20111226','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(4,NULL,0,NULL,4,7,0,0,0,'т.1стр.900 =  т.1стр.600 +  т.1стр.620',1,5,1,'20120126','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(5,NULL,0,NULL,5,7,0,0,0,'т.1стр.030 =  т.1стр.010 -  т.1стр.020',1,1,1,'20110812','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(6,NULL,0,NULL,6,7,0,0,0,'т.1стр.031 =  т.1стр.011 -  т.1стр.021',1,1,1,'20110812','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(7,NULL,0,NULL,7,7,0,0,0,'т.1стр.033 =  т.1стр.013 -  т.1стр.023',1,1,1,'20110812','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(8,NULL,0,NULL,8,7,0,0,0,'т.1стр.034 =  т.1стр.014 -  т.1стр.024',1,1,1,'20110812','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(9,NULL,0,NULL,9,7,0,0,0,'т.1стр.060 =  т.1стр.040 -  т.1стр.050',1,1,1,'20110812','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(10,NULL,0,NULL,10,7,0,0,0,'т.1стр.062 =  т.1стр.042 -  т.1стр.052',1,1,1,'20110812','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(11,NULL,0,NULL,11,7,0,0,0,'т.1стр.063 =  т.1стр.043 -  т.1стр.053',1,1,1,'20110812','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(12,NULL,0,NULL,12,7,0,0,0,'т.1стр.400 =  т.1стр.170 +  т.1стр.210 +  т.1стр.230 +  т.1стр.260 +  т.1стр.290 +  т.1стр.310 +  т.1стр.320 +  т.1стр.330 +  т.1стр.370',1,2,1,'20111227','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(13,NULL,0,NULL,13,7,0,0,0,'т.1стр.410 =  т.1стр.150 +  т.1стр.400',1,3,1,'20110812','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(14,NULL,0,NULL,14,7,0,0,0,'т.1стр.600 =  т.1стр.470 +  т.1стр.490 +  т.1стр.510 +  т.1стр.530',1,2,1,'20110812','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(15,NULL,0,NULL,15,7,0,0,0,'т.1гр.5 =  т.1гр.4 -  т.1гр.3',1,4,1,'20120118','CODE not in (''900'')','','','0503773G','20121231','','=',4,'','')
INSERT #A VALUES(16,NULL,0,NULL,16,7,0,0,0,'т.1стр.010 =  т.1стр.011 +  т.1стр.013 +  т.1стр.014 +  т.1стр.012',1,0,1,'20121017','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(17,NULL,0,NULL,17,7,0,0,0,'т.1стр.020 =  т.1стр.021 +  т.1стр.023 +  т.1стр.024 +  т.1стр.022',1,0,1,'20121017','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(18,NULL,0,NULL,18,7,0,0,0,'т.1стр.040 =  т.1стр.042 +  т.1стр.043 +  т.1стр.041',1,0,1,'20121017','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(19,NULL,0,NULL,19,7,0,0,0,'т.1стр.050 =  т.1стр.052 +  т.1стр.053 +  т.1стр.051',1,0,1,'20121017','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(20,NULL,0,NULL,20,7,0,0,0,'т.1стр.090 =  т.1стр.091 +  т.1стр.093 +  т.1стр.094 +  т.1стр.092 Дипазон колонок:3,4,5',1,0,1,'20121018','','3,4,5','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(21,NULL,0,NULL,21,7,0,0,0,'т.1стр.100 =  т.1стр.101 +  т.1стр.103 +  т.1стр.104 +  т.1стр.102',1,0,1,'20121017','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(22,NULL,0,NULL,22,7,0,0,0,'т.1стр.170 =  т.1стр.171 +  т.1стр.172 +  т.1стр.173 +  т.1стр.174 +  т.1стр.175 +  т.1стр.176 +  т.1стр.177 +  т.1стр.178 +  т.1стр.179',1,0,1,'20121017','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(23,NULL,0,NULL,23,7,0,0,0,'т.1стр.210 =  т.1стр.211 +  т.1стр.212 +  т.1стр.213',1,0,1,'20121017','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(24,NULL,0,NULL,24,7,0,0,0,'т.1стр.290 =  т.1стр.291 +  т.1стр.292',1,0,1,'20121017','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(25,NULL,0,NULL,25,7,0,0,0,'т.1стр.330 =  т.1стр.331 +  т.1стр.333 +  т.1стр.335 +  т.1стр.338',1,1,1,'20121212','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(26,NULL,0,NULL,26,7,0,0,0,'т.1стр.370 =  т.1стр.371 +  т.1стр.372 +  т.1стр.373',1,0,1,'20121017','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(27,NULL,0,NULL,27,7,0,0,0,'т.1стр.470 =  т.1стр.471 +  т.1стр.472 +  т.1стр.474',1,0,1,'20121017','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(28,NULL,0,NULL,28,7,0,0,0,'т.1стр.530 =  т.1стр.531 +  т.1стр.532 +  т.1стр.533 +  т.1стр.534 +  т.1стр.536',1,0,1,'20111226','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(29,NULL,0,NULL,29,7,0,0,0,'т.1стр.620 =  т.1стр.623 +  т.1стр.624 +  т.1стр.625 +  т.1стр.6231',1,0,1,'20121212','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(30,NULL,0,NULL,30,7,0,0,0,'т.1стр.410гр.5 =  т.1стр.900гр.5',0,0,1,'20110919','','','','0503773G','20121231','','=',1,'','')
INSERT #A VALUES(31,NULL,0,NULL,31,7,0,0,0,'т.2стр.99999999999999999999гр.2 =  т.2стр.88888888888888888888гр.2',0,0,1,'20111223','','','','0503773G','20121231','','=',1,'','')
INSERT #A VALUES(32,NULL,0,NULL,32,7,0,0,0,'т.2стр.88888888888888888888гр.2 =  т.1стр.410гр.5',0,0,1,'20111223','','','','0503773G','20121231','','=',1,'','')
INSERT #A VALUES(33,NULL,0,NULL,33,7,0,0,0,'т.2стр.99999999999999999999гр.2 =  т.1стр.900гр.5',0,0,1,'20111223','','','','0503773G','20121231','','=',1,'','')
INSERT #A VALUES(34,NULL,0,NULL,34,7,0,0,0,'т.2стр.88888888888888888888гр.2 =  т.2гр.2Фильтр:101, 102,103,105,106,107,108,109 +  т.2гр.2Фильтр:201, 204, 205, 206, 207, 208, 209 счета +  т.2гр.2Фильтр:210, 215 счета -  т.2гр.2Фильтр:104 счет',1,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(35,NULL,0,NULL,35,7,0,0,0,'т.2стр.99999999999999999999гр.2 =  т.2гр.2Фильтр:301, 302, 303, 304 счета +  т.2гр.2Фильтр:401, 402 счета',1,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(36,NULL,0,NULL,36,7,0,0,0,'т.1стр.010гр.5 =  т.2гр.2Фильтр:010100000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(37,NULL,0,NULL,37,7,0,0,0,'т.1стр.020гр.5 +  т.1стр.050гр.5 =  т.2гр.2Фильтр:010400000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(38,NULL,0,NULL,38,7,0,0,0,'т.1стр.040гр.5 =  т.2гр.2Фильтр:010200000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(39,NULL,0,NULL,39,7,0,0,0,'т.1стр.070гр.5 =  т.2гр.2Фильтр:010300000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(40,NULL,0,NULL,40,7,0,0,0,'т.1стр.080гр.5 =  т.2гр.2Фильтр:010500000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(41,NULL,0,NULL,41,7,0,0,0,'т.1стр.090гр.5 =  т.2гр.2Фильтр:010600000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(42,NULL,0,NULL,42,7,0,0,0,'т.1стр.100гр.5 =  т.2гр.2Фильтр:010700000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(43,NULL,0,NULL,43,7,0,0,0,'т.1стр.140гр.5 =  т.2гр.2Фильтр:010900000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(44,NULL,0,NULL,44,7,0,0,0,'т.1стр.170гр.5 =  т.2гр.2Фильтр:020100000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(45,NULL,0,NULL,45,7,0,0,0,'т.1стр.210гр.5 =  т.2гр.2Фильтр:020400000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(46,NULL,0,NULL,46,7,0,0,0,'т.1стр.230гр.5 =  т.2гр.2Фильтр:020500000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(47,NULL,0,NULL,47,7,0,0,0,'т.1стр.260гр.5 =  т.2гр.2Фильтр:020600000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(48,NULL,0,NULL,48,7,0,0,0,'т.1стр.290гр.5 =  т.2гр.2Фильтр:020700000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(49,NULL,0,NULL,49,7,0,0,0,'т.1стр.310гр.5 =  т.2гр.2Фильтр:020800000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(50,NULL,0,NULL,50,7,0,0,0,'т.1стр.320гр.5 =  т.2гр.2Фильтр:020900000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(51,NULL,0,NULL,51,7,0,0,0,'т.1стр.330гр.5 =  т.2гр.2Фильтр:021000000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(52,NULL,0,NULL,52,7,0,0,0,'т.1стр.370гр.5 =  т.2гр.2Фильтр:021500000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(53,NULL,0,NULL,53,7,0,0,0,'т.1стр.470гр.5 =  т.2гр.2Фильтр:030100000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(54,NULL,0,NULL,54,7,0,0,0,'т.1стр.490гр.5 =  т.2гр.2Фильтр:030200000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(55,NULL,0,NULL,55,7,0,0,0,'т.1стр.510гр.5 =  т.2гр.2Фильтр:030300000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(56,NULL,0,NULL,56,7,0,0,0,'т.1стр.530гр.5 =  т.2гр.2Фильтр:030400000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(57,NULL,0,NULL,57,7,0,0,0,'т.1стр.620гр.5 =  т.2гр.2Фильтр:040100000',0,0,1,'20120327','','','','0503773G','20121231','','=',0,'','')
INSERT #A VALUES(58,NULL,0,NULL,58,7,0,0,0,'т.1стр.030 =  т.1стр.031 +  т.1стр.032 +  т.1стр.033 +  т.1стр.034',0,5,1,'20121017','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(59,NULL,0,NULL,59,7,0,0,0,'т.1стр.060 =  т.1стр.061 +  т.1стр.062 +  т.1стр.063',0,5,1,'20121017','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(60,NULL,0,NULL,60,7,0,0,0,'т.1стр.080 >=  т.1стр.081',0,5,1,'20121017','','','','0503773G','20121231','','>=',2,'','')
INSERT #A VALUES(61,NULL,0,NULL,61,7,0,0,0,'т.1стр.338 =  т.1стр.336 +  т.1стр.337',1,0,1,'20121212','','','','0503773G','20121231','','=',2,'','')
INSERT #A VALUES(62,NULL,0,NULL,62,7,0,0,0,'т.1стр.510 =  т.1стр.511 +  т.1стр.512 +  т.1стр.513 +  т.1стр.514 +  т.1стр.515 +  т.1стр.516',1,0,1,'20130104','','','','0503773G','20121231','','=',2,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 62
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,'','','','','','','','','','032','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','012','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','022','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','061','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','041','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','051','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','150','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','030','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','060','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','070','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','080','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','090','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','100','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','140','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','900','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(4,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','600','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','620','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','030','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(5,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','010','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','020','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','031','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','011','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','021','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','033','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','013','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','023','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','034','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(8,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','014','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','024','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','060','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(9,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','040','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','050','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','062','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(10,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','042','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','052','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','063','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(11,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','043','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','053','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','400','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(12,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','170','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','210','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','230','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','260','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','290','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','310','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','320','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,9,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','330','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,10,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','370','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','410','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(13,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','150','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','400','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','600','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(14,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','470','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','490','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','510','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','530','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(15,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','010','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(16,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','011','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','013','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','014','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','012','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','020','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(17,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','021','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','023','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','024','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','022','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','040','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(18,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','042','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','043','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','041','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','050','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(19,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','052','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','053','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','051','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','090','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(20,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','091','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','093','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','094','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','092','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','100','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(21,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','101','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','103','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','104','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','102','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','170','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(22,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','171','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','172','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','173','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','174','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','175','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','176','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','177','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,9,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','178','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,10,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','179','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','210','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(23,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','211','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','212','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','213','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','290','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(24,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','291','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','292','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','330','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(25,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','331','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','333','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','335','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','338','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','370','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(26,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','371','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','372','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','373','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','470','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(27,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','471','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','472','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','474','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','530','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(28,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','531','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','532','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','533','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','534','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','536','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','620','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(29,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','623','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','624','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','625','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','6231','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','410','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(30,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','900','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','99999999999999999999','','','','','','2','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(31,2,3,'+',NULL,NULL,NULL,NULL,0,0,'','','88888888888888888888','','','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','88888888888888888888','','','','','','2','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(32,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','410','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','99999999999999999999','','','','','','2','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(33,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','900','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','88888888888888888888','','','','','','2','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(34,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,2,5) like ''10[1,2,3,5,6,7,9,8]00''','101, 102,103,105,106,107,108,109','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,3,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,2,5) like ''20[1,4,5,6,7,8,9]00''','201, 204, 205, 206, 207, 208, 209 счета','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,4,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,2,5) like ''21[0,5]00''','210, 215 счета','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,5,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,2,5) like ''10400''','104 счет','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,1,3,'+',NULL,NULL,NULL,NULL,0,0,'','','99999999999999999999','','','','','','2','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(35,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,2,5) like ''30[1,2,3,4]00''','301, 302, 303, 304 счета','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,3,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,2,5) like ''40[1,2]00''','401, 402 счета','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','010','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(36,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''010100000''','010100000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','020','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(37,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','050','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(37,3,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''010400000''','010400000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','040','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(38,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''010200000''','010200000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','070','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(39,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''010300000''','010300000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','080','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(40,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''010500000''','010500000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','090','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(41,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''010600000''','010600000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','100','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(42,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''010700000''','010700000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','140','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(43,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''010900000''','010900000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','170','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(44,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''020100000''','020100000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','210','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(45,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''020400000''','020400000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','230','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(46,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''020500000''','020500000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','260','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(47,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''020600000''','020600000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','290','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(48,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''020700000''','020700000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','310','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(49,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''020800000''','020800000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','320','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(50,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''020900000''','020900000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','330','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(51,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''021000000''','021000000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','370','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(52,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''021500000''','021500000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','470','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(53,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''030100000''','030100000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','490','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(54,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''030200000''','030200000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','510','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(55,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''030300000''','030300000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','530','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(56,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''030400000''','030400000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','620','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(57,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','SUBSTRING(CODE,1,9)=''040100000''','040100000','','','','2','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','030','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(58,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','031','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','032','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','033','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','034','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','060','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(59,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','061','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','062','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','063','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','080','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(60,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','081','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','338','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(61,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','336','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','337','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','510','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(62,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','511','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','512','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','513','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','514','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','515','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','516','1',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) <> 210
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] = '447       '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'447','Отчеты АУ, БУ по приказу 33Н',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-03-05 11:42:38.150',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-03-05 11:42:38.150'
	BEGIN
		SELECT @vcMessage = 'Форма 0503773G с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0503773G с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-03-05 11:42:38.150. Обновление отклонено.'
	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. (фев 27 2014 10:51:41:073AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0606045 (Сведения о численности и оплате труда работников сферы здравоохранения по категориям персонала)
-- Дата ввода : 20130601
-- Дата окончания действия :
-- Версия : 2014-02-27 10:51:41.053
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

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] = '0606045' AND [START_DATE] = '20130601'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-02-27 10:51:41.053',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_' + '0606045',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 = '0606045'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20130601')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. 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,6,1,1,1,2291,'RA_EXPORT_FORM',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, '','sv_0606049_20130101.bas','','KirRepMakerMultiSheet.xls','sv_0606045_20130101.xlt','',NULL,'RA_EXPORT_FORM',0,NULL,NULL,NULL,'          ','REPORTS_ATR_TYPE_ORG,REPORTS_FILTER_SUBDIV,REPORTS_ATR_INCR_ITOG',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,1,0,2000,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,3,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, 3,'№ строки',@iLINK_TABLE,1,1,3,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, 4,'Средняя численность работников, человек: списочного состава',@iLINK_TABLE,1,0,4,0,1,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,0,1,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,1,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,0,7,0,1,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,1,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,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр. 3) ОМС',@iLINK_TABLE,1,0,10,0,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр.3) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,11,0,1,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, 12,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) за счет средств бюджетов всех уровней',@iLINK_TABLE,1,0,12,0,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ОМС',@iLINK_TABLE,1,0,13,0,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,14,0,1,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

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,4,1)
INSERT #R VALUES (3,1,5,1)
INSERT #R VALUES (4,1,6,1)
INSERT #R VALUES (5,1,7,1)
INSERT #R VALUES (6,1,8,1)
INSERT #R VALUES (7,1,9,1)
INSERT #R VALUES (8,1,10,1)
INSERT #R VALUES (9,1,11,1)
INSERT #R VALUES (10,1,12,1)
INSERT #R VALUES (11,1,13,1)
INSERT #R VALUES (12,1,14,1)
INSERT #R VALUES (13,1,14,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 13
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,'Всего работников (сумма строк 02 - 04, 06 - 08, 10 - 13)')
INSERT #F VALUES (1,2,1,'в том числе: руководитель организации')
INSERT #F VALUES (1,3,1,'заместители руководителя и руководители структурных подразделений (кроме врачей - руководителей структурных подразделений), иные руководители')
INSERT #F VALUES (1,4,1,'педагогические работники')
INSERT #F VALUES (1,5,1,'из них преподаватели')
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,'младший медицинский (фармацевтический) персонал (персонал, обеспечивающий предоставление медицинских услуг)')
INSERT #F VALUES (1,12,1,'работники, имеющие высшее фармацевтическое или иное высшее образование, предоставляющие медицинские услуги (обеспечивающие предоставление медицинских услуг)')
INSERT #F VALUES (1,13,1,'прочий персонал')
INSERT #F VALUES (1,1,2,'100                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,2,2,'101                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,3,2,'102                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,4,2,'281                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,5,2,'282                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,6,2,'401                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,7,2,'501                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,8,2,'301                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,9,2,'311                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,10,2,'411                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,11,2,'421                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,12,2,'431                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,13,2,'103                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,1,3,'01                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,2,3,'02                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,3,3,'03                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,4,3,'04                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,5,3,'05                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,6,3,'06                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,7,3,'07                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,8,3,'08                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,9,3,'09                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,10,3,'10                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,11,3,'11                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,12,3,'12                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,13,3,'13                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,1,4,'НЗП_УСТАНОВКА() + НЗП_ЗНАЧЕНИЕ(''100'',4)')
INSERT #F VALUES (1,2,4,'НЗП_ЗНАЧЕНИЕ(''101'',4)')
INSERT #F VALUES (1,3,4,'НЗП_ЗНАЧЕНИЕ(''102'',4)')
INSERT #F VALUES (1,4,4,'НЗП_ЗНАЧЕНИЕ(''281'',4)')
INSERT #F VALUES (1,5,4,'НЗП_ЗНАЧЕНИЕ(''282'',4)')
INSERT #F VALUES (1,6,4,'НЗП_ЗНАЧЕНИЕ(''401'',4)')
INSERT #F VALUES (1,7,4,'НЗП_ЗНАЧЕНИЕ(''501'',4)')
INSERT #F VALUES (1,8,4,'НЗП_ЗНАЧЕНИЕ(''3013'',4)')
INSERT #F VALUES (1,9,4,'НЗП_ЗНАЧЕНИЕ(''3113'',4)')
INSERT #F VALUES (1,10,4,'НЗП_ЗНАЧЕНИЕ(''411'',4)')
INSERT #F VALUES (1,11,4,'НЗП_ЗНАЧЕНИЕ(''421'',4)')
INSERT #F VALUES (1,12,4,'НЗП_ЗНАЧЕНИЕ(''431'',4)')
INSERT #F VALUES (1,13,4,'НЗП_ЗНАЧЕНИЕ(''103'',4)')
INSERT #F VALUES (1,2,5,'НЗП_ЗНАЧЕНИЕ(''101'',5)')
INSERT #F VALUES (1,3,5,'НЗП_ЗНАЧЕНИЕ(''102'',5)')
INSERT #F VALUES (1,4,5,'НЗП_ЗНАЧЕНИЕ(''281'',5)')
INSERT #F VALUES (1,5,5,'НЗП_ЗНАЧЕНИЕ(''282'',5)')
INSERT #F VALUES (1,6,5,'НЗП_ЗНАЧЕНИЕ(''401'',5)')
INSERT #F VALUES (1,7,5,'НЗП_ЗНАЧЕНИЕ(''501'',5)')
INSERT #F VALUES (1,8,5,'НЗП_ЗНАЧЕНИЕ(''3013'',5)')
INSERT #F VALUES (1,9,5,'НЗП_ЗНАЧЕНИЕ(''3113'',5)')
INSERT #F VALUES (1,10,5,'НЗП_ЗНАЧЕНИЕ(''411'',5)')
INSERT #F VALUES (1,11,5,'НЗП_ЗНАЧЕНИЕ(''421'',5)')
INSERT #F VALUES (1,12,5,'НЗП_ЗНАЧЕНИЕ(''431'',5)')
INSERT #F VALUES (1,13,5,'НЗП_ЗНАЧЕНИЕ(''103'',5)')
INSERT #F VALUES (1,2,6,'НЗП_ЗНАЧЕНИЕ(''101'',6)')
INSERT #F VALUES (1,3,6,'НЗП_ЗНАЧЕНИЕ(''102'',6)')
INSERT #F VALUES (1,4,6,'НЗП_ЗНАЧЕНИЕ(''281'',6)')
INSERT #F VALUES (1,5,6,'НЗП_ЗНАЧЕНИЕ(''282'',6)')
INSERT #F VALUES (1,6,6,'НЗП_ЗНАЧЕНИЕ(''401'',6)')
INSERT #F VALUES (1,7,6,'НЗП_ЗНАЧЕНИЕ(''501'',6)')
INSERT #F VALUES (1,8,6,'НЗП_ЗНАЧЕНИЕ(''3013'',6)')
INSERT #F VALUES (1,9,6,'НЗП_ЗНАЧЕНИЕ(''3113'',6)')
INSERT #F VALUES (1,10,6,'НЗП_ЗНАЧЕНИЕ(''411'',6)')
INSERT #F VALUES (1,11,6,'НЗП_ЗНАЧЕНИЕ(''421'',6)')
INSERT #F VALUES (1,12,6,'НЗП_ЗНАЧЕНИЕ(''431'',6)')
INSERT #F VALUES (1,13,6,'НЗП_ЗНАЧЕНИЕ(''103'',6)')
INSERT #F VALUES (1,2,7,'НЗП_ЗНАЧЕНИЕ(''101'',7)')
INSERT #F VALUES (1,3,7,'НЗП_ЗНАЧЕНИЕ(''102'',7)')
INSERT #F VALUES (1,4,7,'НЗП_ЗНАЧЕНИЕ(''281'',7)')
INSERT #F VALUES (1,5,7,'НЗП_ЗНАЧЕНИЕ(''282'',7)')
INSERT #F VALUES (1,6,7,'НЗП_ЗНАЧЕНИЕ(''401'',7)')
INSERT #F VALUES (1,7,7,'НЗП_ЗНАЧЕНИЕ(''501'',7)')
INSERT #F VALUES (1,8,7,'НЗП_ЗНАЧЕНИЕ(''3013'',7)')
INSERT #F VALUES (1,9,7,'НЗП_ЗНАЧЕНИЕ(''3113'',7)')
INSERT #F VALUES (1,10,7,'НЗП_ЗНАЧЕНИЕ(''411'',7)')
INSERT #F VALUES (1,11,7,'НЗП_ЗНАЧЕНИЕ(''421'',7)')
INSERT #F VALUES (1,12,7,'НЗП_ЗНАЧЕНИЕ(''431'',7)')
INSERT #F VALUES (1,13,7,'НЗП_ЗНАЧЕНИЕ(''103'',7)')
INSERT #F VALUES (1,2,8,'НЗП_ЗНАЧЕНИЕ(''101'',8)')
INSERT #F VALUES (1,3,8,'НЗП_ЗНАЧЕНИЕ(''102'',8)')
INSERT #F VALUES (1,4,8,'НЗП_ЗНАЧЕНИЕ(''281'',8)')
INSERT #F VALUES (1,5,8,'НЗП_ЗНАЧЕНИЕ(''282'',8)')
INSERT #F VALUES (1,6,8,'НЗП_ЗНАЧЕНИЕ(''401'',8)')
INSERT #F VALUES (1,7,8,'НЗП_ЗНАЧЕНИЕ(''501'',8)')
INSERT #F VALUES (1,8,8,'НЗП_ЗНАЧЕНИЕ(''3013'',8)')
INSERT #F VALUES (1,9,8,'НЗП_ЗНАЧЕНИЕ(''3113'',8)')
INSERT #F VALUES (1,10,8,'НЗП_ЗНАЧЕНИЕ(''411'',8)')
INSERT #F VALUES (1,11,8,'НЗП_ЗНАЧЕНИЕ(''421'',8)')
INSERT #F VALUES (1,12,8,'НЗП_ЗНАЧЕНИЕ(''431'',8)')
INSERT #F VALUES (1,13,8,'НЗП_ЗНАЧЕНИЕ(''103'',8)')
INSERT #F VALUES (1,2,9,'НЗП_ЗНАЧЕНИЕ(''101'',9)')
INSERT #F VALUES (1,3,9,'НЗП_ЗНАЧЕНИЕ(''102'',9)')
INSERT #F VALUES (1,4,9,'НЗП_ЗНАЧЕНИЕ(''281'',9)')
INSERT #F VALUES (1,5,9,'НЗП_ЗНАЧЕНИЕ(''282'',9)')
INSERT #F VALUES (1,6,9,'НЗП_ЗНАЧЕНИЕ(''401'',9)')
INSERT #F VALUES (1,7,9,'НЗП_ЗНАЧЕНИЕ(''501'',9)')
INSERT #F VALUES (1,8,9,'НЗП_ЗНАЧЕНИЕ(''3013'',9)')
INSERT #F VALUES (1,9,9,'НЗП_ЗНАЧЕНИЕ(''3113'',9)')
INSERT #F VALUES (1,10,9,'НЗП_ЗНАЧЕНИЕ(''411'',9)')
INSERT #F VALUES (1,11,9,'НЗП_ЗНАЧЕНИЕ(''421'',9)')
INSERT #F VALUES (1,12,9,'НЗП_ЗНАЧЕНИЕ(''431'',9)')
INSERT #F VALUES (1,13,9,'НЗП_ЗНАЧЕНИЕ(''103'',9)')
INSERT #F VALUES (1,2,10,'НЗП_ЗНАЧЕНИЕ(''101'',10)')
INSERT #F VALUES (1,3,10,'НЗП_ЗНАЧЕНИЕ(''102'',10)')
INSERT #F VALUES (1,4,10,'НЗП_ЗНАЧЕНИЕ(''281'',10)')
INSERT #F VALUES (1,5,10,'НЗП_ЗНАЧЕНИЕ(''282'',10)')
INSERT #F VALUES (1,6,10,'НЗП_ЗНАЧЕНИЕ(''401'',10)')
INSERT #F VALUES (1,7,10,'НЗП_ЗНАЧЕНИЕ(''501'',10)')
INSERT #F VALUES (1,8,10,'НЗП_ЗНАЧЕНИЕ(''3013'',10)')
INSERT #F VALUES (1,9,10,'НЗП_ЗНАЧЕНИЕ(''3113'',10)')
INSERT #F VALUES (1,10,10,'НЗП_ЗНАЧЕНИЕ(''411'',10)')
INSERT #F VALUES (1,11,10,'НЗП_ЗНАЧЕНИЕ(''421'',10)')
INSERT #F VALUES (1,12,10,'НЗП_ЗНАЧЕНИЕ(''431'',10)')
INSERT #F VALUES (1,13,10,'НЗП_ЗНАЧЕНИЕ(''103'',10)')
INSERT #F VALUES (1,2,11,'НЗП_ЗНАЧЕНИЕ(''101'',11)')
INSERT #F VALUES (1,3,11,'НЗП_ЗНАЧЕНИЕ(''102'',11)')
INSERT #F VALUES (1,4,11,'НЗП_ЗНАЧЕНИЕ(''281'',11)')
INSERT #F VALUES (1,5,11,'НЗП_ЗНАЧЕНИЕ(''282'',11)')
INSERT #F VALUES (1,6,11,'НЗП_ЗНАЧЕНИЕ(''401'',11)')
INSERT #F VALUES (1,7,11,'НЗП_ЗНАЧЕНИЕ(''501'',11)')
INSERT #F VALUES (1,8,11,'НЗП_ЗНАЧЕНИЕ(''3013'',11)')
INSERT #F VALUES (1,9,11,'НЗП_ЗНАЧЕНИЕ(''3113'',11)')
INSERT #F VALUES (1,10,11,'НЗП_ЗНАЧЕНИЕ(''411'',11)')
INSERT #F VALUES (1,11,11,'НЗП_ЗНАЧЕНИЕ(''421'',11)')
INSERT #F VALUES (1,12,11,'НЗП_ЗНАЧЕНИЕ(''431'',11)')
INSERT #F VALUES (1,13,11,'НЗП_ЗНАЧЕНИЕ(''103'',11)')
INSERT #F VALUES (1,2,12,'НЗП_ЗНАЧЕНИЕ(''101'',12)')
INSERT #F VALUES (1,3,12,'НЗП_ЗНАЧЕНИЕ(''102'',12)')
INSERT #F VALUES (1,4,12,'НЗП_ЗНАЧЕНИЕ(''281'',12)')
INSERT #F VALUES (1,5,12,'НЗП_ЗНАЧЕНИЕ(''282'',12)')
INSERT #F VALUES (1,6,12,'НЗП_ЗНАЧЕНИЕ(''401'',12)')
INSERT #F VALUES (1,7,12,'НЗП_ЗНАЧЕНИЕ(''501'',12)')
INSERT #F VALUES (1,8,12,'НЗП_ЗНАЧЕНИЕ(''3013'',12)')
INSERT #F VALUES (1,9,12,'НЗП_ЗНАЧЕНИЕ(''3113'',12)')
INSERT #F VALUES (1,10,12,'НЗП_ЗНАЧЕНИЕ(''411'',12)')
INSERT #F VALUES (1,11,12,'НЗП_ЗНАЧЕНИЕ(''421'',12)')
INSERT #F VALUES (1,12,12,'НЗП_ЗНАЧЕНИЕ(''431'',12)')
INSERT #F VALUES (1,13,12,'НЗП_ЗНАЧЕНИЕ(''103'',12)')
INSERT #F VALUES (1,2,13,'НЗП_ЗНАЧЕНИЕ(''101'',13)')
INSERT #F VALUES (1,3,13,'НЗП_ЗНАЧЕНИЕ(''102'',13)')
INSERT #F VALUES (1,4,13,'НЗП_ЗНАЧЕНИЕ(''281'',13)')
INSERT #F VALUES (1,5,13,'НЗП_ЗНАЧЕНИЕ(''282'',13)')
INSERT #F VALUES (1,6,13,'НЗП_ЗНАЧЕНИЕ(''401'',13)')
INSERT #F VALUES (1,7,13,'НЗП_ЗНАЧЕНИЕ(''501'',13)')
INSERT #F VALUES (1,8,13,'НЗП_ЗНАЧЕНИЕ(''3013'',13)')
INSERT #F VALUES (1,9,13,'НЗП_ЗНАЧЕНИЕ(''3113'',13)')
INSERT #F VALUES (1,10,13,'НЗП_ЗНАЧЕНИЕ(''411'',13)')
INSERT #F VALUES (1,11,13,'НЗП_ЗНАЧЕНИЕ(''421'',13)')
INSERT #F VALUES (1,12,13,'НЗП_ЗНАЧЕНИЕ(''431'',13)')
INSERT #F VALUES (1,13,13,'НЗП_ЗНАЧЕНИЕ(''103'',13)')
INSERT #F VALUES (1,2,14,'НЗП_ЗНАЧЕНИЕ(''101'',14)')
INSERT #F VALUES (1,3,14,'НЗП_ЗНАЧЕНИЕ(''102'',14)')
INSERT #F VALUES (1,4,14,'НЗП_ЗНАЧЕНИЕ(''281'',14)')
INSERT #F VALUES (1,5,14,'НЗП_ЗНАЧЕНИЕ(''282'',14)')
INSERT #F VALUES (1,6,14,'НЗП_ЗНАЧЕНИЕ(''401'',14)')
INSERT #F VALUES (1,7,14,'НЗП_ЗНАЧЕНИЕ(''501'',14)')
INSERT #F VALUES (1,8,14,'НЗП_ЗНАЧЕНИЕ(''3013'',14)')
INSERT #F VALUES (1,9,14,'НЗП_ЗНАЧЕНИЕ(''3113'',14)')
INSERT #F VALUES (1,10,14,'НЗП_ЗНАЧЕНИЕ(''411'',14)')
INSERT #F VALUES (1,11,14,'НЗП_ЗНАЧЕНИЕ(''421'',14)')
INSERT #F VALUES (1,12,14,'НЗП_ЗНАЧЕНИЕ(''431'',14)')
INSERT #F VALUES (1,13,14,'НЗП_ЗНАЧЕНИЕ(''103'',14)')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 172
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,'т.1стр.01 =  т.1стр.02 +  т.1стр.03 +  т.1стр.04 +  т.1стр.06 +  т.1стр.07 +  т.1стр.08 +  т.1стр.10 +  т.1стр.11 +  т.1стр.12 +  т.1стр.13',1,5,1,'20130912','','','','0606045','20130601','','=',2,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 1
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,'','','','','','','','','','01','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','02','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','03','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','04','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','06','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','07','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','08','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','10','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,9,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','11','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,10,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','12','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,11,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','13','1',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) <> 11
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] = '451       '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'451','Республика Коми',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] = '606       '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'606','Заработная плата',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-02-27 10:51:41.053',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-02-27 10:51:41.053'
	BEGIN
		SELECT @vcMessage = 'Форма 0606045 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0606045 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-02-27 10:51:41.053. Обновление отклонено.'
	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. (фев 27 2014 10:51:52:300AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0606046 (Сведения о численности и оплате труда работников сферы культуры по категориям персонала)
-- Дата ввода : 20130601
-- Дата окончания действия :
-- Версия : 2014-02-27 10:51:52.290
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

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] = '0606046' AND [START_DATE] = '20130601'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-02-27 10:51:52.290',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_' + '0606046',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 = '0606046'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20130601')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. 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,6,1,1,1,2291,'RA_EXPORT_FORM',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, '','sv_0606049_20130101.bas','','KirRepMakerMultiSheet.xls','sv_0606046_20130101.xlt','',NULL,'RA_EXPORT_FORM',0,NULL,NULL,NULL,'          ','REPORTS_ATR_TYPE_ORG,REPORTS_FILTER_SUBDIV,REPORTS_ATR_INCR_ITOG',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,1,0,2000,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,3,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, 3,'№ строки',@iLINK_TABLE,1,1,3,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, 4,'Средняя численность работников, человек: списочного состава',@iLINK_TABLE,1,0,4,0,1,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,0,1,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,1,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,0,7,0,1,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,1,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,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр. 3) ОМС',@iLINK_TABLE,1,0,10,0,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр.3) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,11,0,1,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, 12,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) за счет средств бюджетов всех уровней',@iLINK_TABLE,1,0,12,0,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ОМС',@iLINK_TABLE,1,0,13,0,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,14,0,1,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

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,4,1)
INSERT #R VALUES (3,1,15,1)
INSERT #R VALUES (4,1,19,1)
INSERT #R VALUES (5,1,5,1)
INSERT #R VALUES (6,1,6,1)
INSERT #R VALUES (7,1,17,1)
INSERT #R VALUES (8,1,8,1)
INSERT #R VALUES (9,1,9,1)
INSERT #R VALUES (10,1,10,1)
INSERT #R VALUES (11,1,11,1)
INSERT #R VALUES (12,1,12,1)
INSERT #R VALUES (13,1,13,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 13
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,'Всего работников (сумма строк 02-06 ,11-13)')
INSERT #F VALUES (1,2,1,'в том числе: руководитель организации')
INSERT #F VALUES (1,3,1,'заместители руководителя и руководители структурных подразделений и их заместители')
INSERT #F VALUES (1,4,1,'артистический персонал')
INSERT #F VALUES (1,5,1,'художественный персонал')
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,'средний медицинский персонал (персонал,обеспечивающий условия для предоставления медицинских услуг)')
INSERT #F VALUES (1,12,1,'младший медицинский персонал (персонал,обеспечивающий условия для предоставления медицинских услуг)')
INSERT #F VALUES (1,13,1,'прочий персонал')
INSERT #F VALUES (1,1,2,'100                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,2,2,'101                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,3,2,'102                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,4,2,'601                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,5,2,'611                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,6,2,'621                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,7,2,'301                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,8,2,'311                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,9,2,'291                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,10,2,'401                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,11,2,'411                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,12,2,'421                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,13,2,'103                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,1,3,'01                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,2,3,'02                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,3,3,'03                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,4,3,'04                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,5,3,'05                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,6,3,'06                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,7,3,'07                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,8,3,'08                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,9,3,'09                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,10,3,'10                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,11,3,'11                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,12,3,'12                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,13,3,'13                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,1,4,'НЗП_УСТАНОВКА() + НЗП_ЗНАЧЕНИЕ(''100'',4)')
INSERT #F VALUES (1,2,4,'НЗП_ЗНАЧЕНИЕ(''101'',4)')
INSERT #F VALUES (1,3,4,'НЗП_ЗНАЧЕНИЕ(''102'',4)')
INSERT #F VALUES (1,4,4,'НЗП_ЗНАЧЕНИЕ(''601'',4)')
INSERT #F VALUES (1,5,4,'НЗП_ЗНАЧЕНИЕ(''611'',4)')
INSERT #F VALUES (1,6,4,'НЗП_ЗНАЧЕНИЕ(''621'',4)')
INSERT #F VALUES (1,7,4,'НЗП_ЗНАЧЕНИЕ(''3013'',4)')
INSERT #F VALUES (1,8,4,'НЗП_ЗНАЧЕНИЕ(''3113'',4)')
INSERT #F VALUES (1,9,4,'НЗП_ЗНАЧЕНИЕ(''291'',4)')
INSERT #F VALUES (1,10,4,'НЗП_ЗНАЧЕНИЕ(''401'',4)')
INSERT #F VALUES (1,11,4,'НЗП_ЗНАЧЕНИЕ(''411'',4)')
INSERT #F VALUES (1,12,4,'НЗП_ЗНАЧЕНИЕ(''421'',4)')
INSERT #F VALUES (1,13,4,'НЗП_ЗНАЧЕНИЕ(''103'',4)')
INSERT #F VALUES (1,2,5,'НЗП_ЗНАЧЕНИЕ(''101'',5)')
INSERT #F VALUES (1,3,5,'НЗП_ЗНАЧЕНИЕ(''102'',5)')
INSERT #F VALUES (1,4,5,'НЗП_ЗНАЧЕНИЕ(''601'',5)')
INSERT #F VALUES (1,5,5,'НЗП_ЗНАЧЕНИЕ(''611'',5)')
INSERT #F VALUES (1,6,5,'НЗП_ЗНАЧЕНИЕ(''621'',5)')
INSERT #F VALUES (1,7,5,'НЗП_ЗНАЧЕНИЕ(''3013'',5)')
INSERT #F VALUES (1,8,5,'НЗП_ЗНАЧЕНИЕ(''3113'',5)')
INSERT #F VALUES (1,9,5,'НЗП_ЗНАЧЕНИЕ(''291'',5)')
INSERT #F VALUES (1,10,5,'НЗП_ЗНАЧЕНИЕ(''401'',4)')
INSERT #F VALUES (1,11,5,'НЗП_ЗНАЧЕНИЕ(''411'',5)')
INSERT #F VALUES (1,12,5,'НЗП_ЗНАЧЕНИЕ(''421'',5)')
INSERT #F VALUES (1,13,5,'НЗП_ЗНАЧЕНИЕ(''103'',5)')
INSERT #F VALUES (1,2,6,'НЗП_ЗНАЧЕНИЕ(''101'',6)')
INSERT #F VALUES (1,3,6,'НЗП_ЗНАЧЕНИЕ(''102'',6)')
INSERT #F VALUES (1,4,6,'НЗП_ЗНАЧЕНИЕ(''601'',6)')
INSERT #F VALUES (1,5,6,'НЗП_ЗНАЧЕНИЕ(''611'',6)')
INSERT #F VALUES (1,6,6,'НЗП_ЗНАЧЕНИЕ(''621'',6)')
INSERT #F VALUES (1,7,6,'НЗП_ЗНАЧЕНИЕ(''3013'',6)')
INSERT #F VALUES (1,8,6,'НЗП_ЗНАЧЕНИЕ(''3113'',6)')
INSERT #F VALUES (1,9,6,'НЗП_ЗНАЧЕНИЕ(''291'',6)')
INSERT #F VALUES (1,10,6,'НЗП_ЗНАЧЕНИЕ(''401'',6)')
INSERT #F VALUES (1,11,6,'НЗП_ЗНАЧЕНИЕ(''411'',6)')
INSERT #F VALUES (1,12,6,'НЗП_ЗНАЧЕНИЕ(''421'',6)')
INSERT #F VALUES (1,13,6,'НЗП_ЗНАЧЕНИЕ(''103'',6)')
INSERT #F VALUES (1,2,7,'НЗП_ЗНАЧЕНИЕ(''101'',7)')
INSERT #F VALUES (1,3,7,'НЗП_ЗНАЧЕНИЕ(''102'',7)')
INSERT #F VALUES (1,4,7,'НЗП_ЗНАЧЕНИЕ(''601'',7)')
INSERT #F VALUES (1,5,7,'НЗП_ЗНАЧЕНИЕ(''611'',7)')
INSERT #F VALUES (1,6,7,'НЗП_ЗНАЧЕНИЕ(''621'',7)')
INSERT #F VALUES (1,7,7,'НЗП_ЗНАЧЕНИЕ(''3013'',7)')
INSERT #F VALUES (1,8,7,'НЗП_ЗНАЧЕНИЕ(''3113'',7)')
INSERT #F VALUES (1,9,7,'НЗП_ЗНАЧЕНИЕ(''291'',7)')
INSERT #F VALUES (1,10,7,'НЗП_ЗНАЧЕНИЕ(''401'',7)')
INSERT #F VALUES (1,11,7,'НЗП_ЗНАЧЕНИЕ(''411'',7)')
INSERT #F VALUES (1,12,7,'НЗП_ЗНАЧЕНИЕ(''421'',7)')
INSERT #F VALUES (1,13,7,'НЗП_ЗНАЧЕНИЕ(''103'',7)')
INSERT #F VALUES (1,2,8,'НЗП_ЗНАЧЕНИЕ(''101'',8)')
INSERT #F VALUES (1,3,8,'НЗП_ЗНАЧЕНИЕ(''102'',8)')
INSERT #F VALUES (1,4,8,'НЗП_ЗНАЧЕНИЕ(''601'',8)')
INSERT #F VALUES (1,5,8,'НЗП_ЗНАЧЕНИЕ(''611'',8)')
INSERT #F VALUES (1,6,8,'НЗП_ЗНАЧЕНИЕ(''621'',8)')
INSERT #F VALUES (1,7,8,'НЗП_ЗНАЧЕНИЕ(''3013'',8)')
INSERT #F VALUES (1,8,8,'НЗП_ЗНАЧЕНИЕ(''3113'',8)')
INSERT #F VALUES (1,9,8,'НЗП_ЗНАЧЕНИЕ(''291'',8)')
INSERT #F VALUES (1,10,8,'НЗП_ЗНАЧЕНИЕ(''401'',8)')
INSERT #F VALUES (1,11,8,'НЗП_ЗНАЧЕНИЕ(''411'',8)')
INSERT #F VALUES (1,12,8,'НЗП_ЗНАЧЕНИЕ(''421'',8)')
INSERT #F VALUES (1,13,8,'НЗП_ЗНАЧЕНИЕ(''103'',8)')
INSERT #F VALUES (1,2,9,'НЗП_ЗНАЧЕНИЕ(''101'',9)')
INSERT #F VALUES (1,3,9,'НЗП_ЗНАЧЕНИЕ(''102'',9)')
INSERT #F VALUES (1,4,9,'НЗП_ЗНАЧЕНИЕ(''601'',9)')
INSERT #F VALUES (1,5,9,'НЗП_ЗНАЧЕНИЕ(''611'',9)')
INSERT #F VALUES (1,6,9,'НЗП_ЗНАЧЕНИЕ(''621'',9)')
INSERT #F VALUES (1,7,9,'НЗП_ЗНАЧЕНИЕ(''3013'',9)')
INSERT #F VALUES (1,8,9,'НЗП_ЗНАЧЕНИЕ(''3113'',9)')
INSERT #F VALUES (1,9,9,'НЗП_ЗНАЧЕНИЕ(''291'',9)')
INSERT #F VALUES (1,10,9,'НЗП_ЗНАЧЕНИЕ(''401'',9)')
INSERT #F VALUES (1,11,9,'НЗП_ЗНАЧЕНИЕ(''411'',9)')
INSERT #F VALUES (1,12,9,'НЗП_ЗНАЧЕНИЕ(''421'',9)')
INSERT #F VALUES (1,13,9,'НЗП_ЗНАЧЕНИЕ(''103'',9)')
INSERT #F VALUES (1,2,10,'НЗП_ЗНАЧЕНИЕ(''101'',10)')
INSERT #F VALUES (1,3,10,'НЗП_ЗНАЧЕНИЕ(''102'',10)')
INSERT #F VALUES (1,4,10,'НЗП_ЗНАЧЕНИЕ(''601'',10)')
INSERT #F VALUES (1,5,10,'НЗП_ЗНАЧЕНИЕ(''611'',10)')
INSERT #F VALUES (1,6,10,'НЗП_ЗНАЧЕНИЕ(''621'',10)')
INSERT #F VALUES (1,7,10,'НЗП_ЗНАЧЕНИЕ(''3013'',10)')
INSERT #F VALUES (1,8,10,'НЗП_ЗНАЧЕНИЕ(''3113'',10)')
INSERT #F VALUES (1,9,10,'НЗП_ЗНАЧЕНИЕ(''291'',10)')
INSERT #F VALUES (1,10,10,'НЗП_ЗНАЧЕНИЕ(''401'',10)')
INSERT #F VALUES (1,11,10,'НЗП_ЗНАЧЕНИЕ(''411'',10)')
INSERT #F VALUES (1,12,10,'НЗП_ЗНАЧЕНИЕ(''421'',10)')
INSERT #F VALUES (1,13,10,'НЗП_ЗНАЧЕНИЕ(''103'',10)')
INSERT #F VALUES (1,2,11,'НЗП_ЗНАЧЕНИЕ(''101'',11)')
INSERT #F VALUES (1,3,11,'НЗП_ЗНАЧЕНИЕ(''102'',11)')
INSERT #F VALUES (1,4,11,'НЗП_ЗНАЧЕНИЕ(''601'',11)')
INSERT #F VALUES (1,5,11,'НЗП_ЗНАЧЕНИЕ(''611'',11)')
INSERT #F VALUES (1,6,11,'НЗП_ЗНАЧЕНИЕ(''621'',11)')
INSERT #F VALUES (1,7,11,'НЗП_ЗНАЧЕНИЕ(''3013'',11)')
INSERT #F VALUES (1,8,11,'НЗП_ЗНАЧЕНИЕ(''3113'',11)')
INSERT #F VALUES (1,9,11,'НЗП_ЗНАЧЕНИЕ(''291'',11)')
INSERT #F VALUES (1,10,11,'НЗП_ЗНАЧЕНИЕ(''401'',11)')
INSERT #F VALUES (1,11,11,'НЗП_ЗНАЧЕНИЕ(''411'',11)')
INSERT #F VALUES (1,12,11,'НЗП_ЗНАЧЕНИЕ(''421'',11)')
INSERT #F VALUES (1,13,11,'НЗП_ЗНАЧЕНИЕ(''103'',11)')
INSERT #F VALUES (1,2,12,'НЗП_ЗНАЧЕНИЕ(''101'',12)')
INSERT #F VALUES (1,3,12,'НЗП_ЗНАЧЕНИЕ(''102'',12)')
INSERT #F VALUES (1,4,12,'НЗП_ЗНАЧЕНИЕ(''601'',12)')
INSERT #F VALUES (1,5,12,'НЗП_ЗНАЧЕНИЕ(''611'',12)')
INSERT #F VALUES (1,6,12,'НЗП_ЗНАЧЕНИЕ(''621'',12)')
INSERT #F VALUES (1,7,12,'НЗП_ЗНАЧЕНИЕ(''3013'',12)')
INSERT #F VALUES (1,8,12,'НЗП_ЗНАЧЕНИЕ(''3113'',12)')
INSERT #F VALUES (1,9,12,'НЗП_ЗНАЧЕНИЕ(''291'',12)')
INSERT #F VALUES (1,10,12,'НЗП_ЗНАЧЕНИЕ(''401'',12)')
INSERT #F VALUES (1,11,12,'НЗП_ЗНАЧЕНИЕ(''411'',12)')
INSERT #F VALUES (1,12,12,'НЗП_ЗНАЧЕНИЕ(''421'',12)')
INSERT #F VALUES (1,13,12,'НЗП_ЗНАЧЕНИЕ(''103'',12)')
INSERT #F VALUES (1,2,13,'НЗП_ЗНАЧЕНИЕ(''101'',13)')
INSERT #F VALUES (1,3,13,'НЗП_ЗНАЧЕНИЕ(''102'',13)')
INSERT #F VALUES (1,4,13,'НЗП_ЗНАЧЕНИЕ(''601'',13)')
INSERT #F VALUES (1,5,13,'НЗП_ЗНАЧЕНИЕ(''611'',13)')
INSERT #F VALUES (1,6,13,'НЗП_ЗНАЧЕНИЕ(''621'',13)')
INSERT #F VALUES (1,7,13,'НЗП_ЗНАЧЕНИЕ(''3013'',13)')
INSERT #F VALUES (1,8,13,'НЗП_ЗНАЧЕНИЕ(''3113'',13)')
INSERT #F VALUES (1,9,13,'НЗП_ЗНАЧЕНИЕ(''291'',13)')
INSERT #F VALUES (1,10,13,'НЗП_ЗНАЧЕНИЕ(''401'',13)')
INSERT #F VALUES (1,11,13,'НЗП_ЗНАЧЕНИЕ(''411'',13)')
INSERT #F VALUES (1,12,13,'НЗП_ЗНАЧЕНИЕ(''421'',13)')
INSERT #F VALUES (1,13,13,'НЗП_ЗНАЧЕНИЕ(''103'',13)')
INSERT #F VALUES (1,2,14,'НЗП_ЗНАЧЕНИЕ(''101'',14)')
INSERT #F VALUES (1,3,14,'НЗП_ЗНАЧЕНИЕ(''102'',14)')
INSERT #F VALUES (1,4,14,'НЗП_ЗНАЧЕНИЕ(''601'',14)')
INSERT #F VALUES (1,5,14,'НЗП_ЗНАЧЕНИЕ(''611'',14)')
INSERT #F VALUES (1,6,14,'НЗП_ЗНАЧЕНИЕ(''621'',14)')
INSERT #F VALUES (1,7,14,'НЗП_ЗНАЧЕНИЕ(''3013'',14)')
INSERT #F VALUES (1,8,14,'НЗП_ЗНАЧЕНИЕ(''3113'',14)')
INSERT #F VALUES (1,9,14,'НЗП_ЗНАЧЕНИЕ(''291'',14)')
INSERT #F VALUES (1,10,14,'НЗП_ЗНАЧЕНИЕ(''401'',14)')
INSERT #F VALUES (1,11,14,'НЗП_ЗНАЧЕНИЕ(''411'',14)')
INSERT #F VALUES (1,12,14,'НЗП_ЗНАЧЕНИЕ(''421'',14)')
INSERT #F VALUES (1,13,14,'НЗП_ЗНАЧЕНИЕ(''103'',14)')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 172
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,'т.1стр.01 =  т.1стр.02 +  т.1стр.03 +  т.1стр.12 +  т.1стр.13 +  т.1стр.04 +  т.1стр.05 +  т.1стр.11 +  т.1стр.06',1,3,1,'20130912','','','','0606046','20130601','','=',2,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 1
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,'','','','','','','','','','01','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','02','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','03','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','12','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','13','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','04','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','05','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','11','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,9,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','06','1',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) <> 9
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] = '451       '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'451','Республика Коми',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] = '606       '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'606','Заработная плата',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-02-27 10:51:52.290',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-02-27 10:51:52.290'
	BEGIN
		SELECT @vcMessage = 'Форма 0606046 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0606046 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-02-27 10:51:52.290. Обновление отклонено.'
	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. (фев 27 2014 10:52:02:680AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0606047 (Сведения о численности и оплате труда работников организаций, осуществляющих научные исследования и разработки,по категориям персонала)
-- Дата ввода : 20130601
-- Дата окончания действия :
-- Версия : 2014-02-27 10:52:02.667
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

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] = '0606047' AND [START_DATE] = '20130601'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-02-27 10:52:02.667',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_' + '0606047',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 = '0606047'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20130601')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. 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,6,1,1,1,2291,'RA_EXPORT_FORM',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, '','sv_0606049_20130101.bas','','KirRepMakerMultiSheet.xls','sv_0606047_20130101.xlt','',NULL,'RA_EXPORT_FORM',0,NULL,NULL,NULL,'          ','REPORTS_ATR_TYPE_ORG,REPORTS_FILTER_SUBDIV,REPORTS_ATR_INCR_ITOG',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,1,0,2000,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,3,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, 3,'№ строки',@iLINK_TABLE,1,1,3,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, 4,'Средняя численность работников, человек: списочного состава',@iLINK_TABLE,1,0,4,0,1,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,0,1,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,1,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,0,7,0,1,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,1,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,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр. 3) ОМС',@iLINK_TABLE,1,0,10,0,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр.3) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,11,0,1,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, 12,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) за счет средств бюджетов всех уровней',@iLINK_TABLE,1,0,12,0,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ОМС',@iLINK_TABLE,1,0,13,0,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,14,0,1,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

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,4,1)
INSERT #R VALUES (3,1,19,1)
INSERT #R VALUES (4,1,5,1)
INSERT #R VALUES (5,1,6,1)
INSERT #R VALUES (6,1,17,1)
INSERT #R VALUES (7,1,8,1)
INSERT #R VALUES (8,1,9,1)
INSERT #R VALUES (9,1,10,1)
INSERT #R VALUES (10,1,11,1)
INSERT #R VALUES (11,1,12,1)
INSERT #R VALUES (12,1,13,1)
INSERT #R VALUES (13,1,14,1)
INSERT #R VALUES (14,1,20,1)
INSERT #R VALUES (15,1,18,1)
INSERT #R VALUES (16,1,20,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 16
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,'Всего работников (сумма строк 02 ,09-14)')
INSERT #F VALUES (1,2,1,'в том числе: научные работники (исследователи) (сумма строк 03, 04, 05, 08)')
INSERT #F VALUES (1,3,1,'в том числе: руководитель организации')
INSERT #F VALUES (1,4,1,'заместители руководителя и руководители структурных подразделений и их заместителей')
INSERT #F VALUES (1,5,1,'научные работники')
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,'врачи')
INSERT #F VALUES (1,12,1,'средний медицинский персонал (персонал,обеспечивающий условия для предоставления медицинских услуг)')
INSERT #F VALUES (1,13,1,'младший медицинский персонал (персонал,обеспечивающий условия для предоставления медицинских услуг)')
INSERT #F VALUES (1,14,1,'прочий персонал')
INSERT #F VALUES (1,15,1,'Из строки 01 фонд начисленной заработной платы работников: за счет средств  федерального бюджета')
INSERT #F VALUES (1,16,1,'конкурсное (программное) финансирование')
INSERT #F VALUES (1,1,2,'100                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,2,2,'301                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,3,2,'101                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,4,2,'102                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,5,2,'311                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,6,2,'312                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,7,2,'313                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,8,2,'302                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,9,2,'321                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,10,2,'331                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,11,2,'401                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,12,2,'411                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,13,2,'421                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,14,2,'103                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,15,2,'100                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,16,2,'100                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,1,3,'01                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,2,3,'02                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,3,3,'03                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,4,3,'04                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,5,3,'05                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,6,3,'06                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,7,3,'07                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,8,3,'08                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,9,3,'09                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,10,3,'10                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,11,3,'11                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,12,3,'12                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,13,3,'13                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,14,3,'14                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,15,3,'15                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,16,3,'16                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,1,4,'НЗП_УСТАНОВКА() + НЗП_ЗНАЧЕНИЕ(''100'',4)')
INSERT #F VALUES (1,2,4,'НЗП_ЗНАЧЕНИЕ(''3014'',4)')
INSERT #F VALUES (1,3,4,'НЗП_ЗНАЧЕНИЕ(''101'',4)')
INSERT #F VALUES (1,4,4,'НЗП_ЗНАЧЕНИЕ(''102'',4)')
INSERT #F VALUES (1,5,4,'НЗП_ЗНАЧЕНИЕ(''3113'',4)')
INSERT #F VALUES (1,6,4,'НЗП_ЗНАЧЕНИЕ(''312'',4)')
INSERT #F VALUES (1,7,4,'НЗП_ЗНАЧЕНИЕ(''313'',4)')
INSERT #F VALUES (1,8,4,'НЗП_ЗНАЧЕНИЕ(''302'',4)')
INSERT #F VALUES (1,9,4,'НЗП_ЗНАЧЕНИЕ(''321'',4)')
INSERT #F VALUES (1,10,4,'НЗП_ЗНАЧЕНИЕ(''331'',4)')
INSERT #F VALUES (1,11,4,'НЗП_ЗНАЧЕНИЕ(''401'',4)')
INSERT #F VALUES (1,12,4,'НЗП_ЗНАЧЕНИЕ(''411'',4)')
INSERT #F VALUES (1,13,4,'НЗП_ЗНАЧЕНИЕ(''421'',4)')
INSERT #F VALUES (1,14,4,'НЗП_ЗНАЧЕНИЕ(''103'',4)')
INSERT #F VALUES (1,15,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,2,5,'НЗП_ЗНАЧЕНИЕ(''3014'',5)')
INSERT #F VALUES (1,3,5,'НЗП_ЗНАЧЕНИЕ(''101'',5)')
INSERT #F VALUES (1,4,5,'НЗП_ЗНАЧЕНИЕ(''102'',5)')
INSERT #F VALUES (1,5,5,'НЗП_ЗНАЧЕНИЕ(''3113'',5)')
INSERT #F VALUES (1,6,5,'НЗП_ЗНАЧЕНИЕ(''312'',5)')
INSERT #F VALUES (1,7,5,'НЗП_ЗНАЧЕНИЕ(''313'',5)')
INSERT #F VALUES (1,8,5,'НЗП_ЗНАЧЕНИЕ(''302'',5)')
INSERT #F VALUES (1,9,5,'НЗП_ЗНАЧЕНИЕ(''321'',5)')
INSERT #F VALUES (1,10,5,'НЗП_ЗНАЧЕНИЕ(''331'',5)')
INSERT #F VALUES (1,11,5,'НЗП_ЗНАЧЕНИЕ(''401'',5)')
INSERT #F VALUES (1,12,5,'НЗП_ЗНАЧЕНИЕ(''411'',5)')
INSERT #F VALUES (1,13,5,'НЗП_ЗНАЧЕНИЕ(''421'',5)')
INSERT #F VALUES (1,14,5,'НЗП_ЗНАЧЕНИЕ(''103'',5)')
INSERT #F VALUES (1,15,5,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,5,'ЗАПРЕТ()')
INSERT #F VALUES (1,2,6,'НЗП_ЗНАЧЕНИЕ(''3014'',6)')
INSERT #F VALUES (1,3,6,'НЗП_ЗНАЧЕНИЕ(''101'',6)')
INSERT #F VALUES (1,4,6,'НЗП_ЗНАЧЕНИЕ(''102'',6)')
INSERT #F VALUES (1,5,6,'НЗП_ЗНАЧЕНИЕ(''3113'',6)')
INSERT #F VALUES (1,6,6,'НЗП_ЗНАЧЕНИЕ(''312'',6)')
INSERT #F VALUES (1,7,6,'НЗП_ЗНАЧЕНИЕ(''313'',6)')
INSERT #F VALUES (1,8,6,'НЗП_ЗНАЧЕНИЕ(''302'',6)')
INSERT #F VALUES (1,9,6,'НЗП_ЗНАЧЕНИЕ(''321'',6)')
INSERT #F VALUES (1,10,6,'НЗП_ЗНАЧЕНИЕ(''331'',6)')
INSERT #F VALUES (1,11,6,'НЗП_ЗНАЧЕНИЕ(''401'',6)')
INSERT #F VALUES (1,12,6,'НЗП_ЗНАЧЕНИЕ(''411'',6)')
INSERT #F VALUES (1,13,6,'НЗП_ЗНАЧЕНИЕ(''421'',6)')
INSERT #F VALUES (1,14,6,'НЗП_ЗНАЧЕНИЕ(''103'',6)')
INSERT #F VALUES (1,15,6,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,6,'ЗАПРЕТ()')
INSERT #F VALUES (1,2,7,'НЗП_ЗНАЧЕНИЕ(''3014'',7)')
INSERT #F VALUES (1,3,7,'НЗП_ЗНАЧЕНИЕ(''101'',7)')
INSERT #F VALUES (1,4,7,'НЗП_ЗНАЧЕНИЕ(''102'',7)')
INSERT #F VALUES (1,5,7,'НЗП_ЗНАЧЕНИЕ(''3113'',7)')
INSERT #F VALUES (1,6,7,'НЗП_ЗНАЧЕНИЕ(''312'',7)')
INSERT #F VALUES (1,7,7,'НЗП_ЗНАЧЕНИЕ(''313'',7)')
INSERT #F VALUES (1,8,7,'НЗП_ЗНАЧЕНИЕ(''302'',7)')
INSERT #F VALUES (1,9,7,'НЗП_ЗНАЧЕНИЕ(''321'',7)')
INSERT #F VALUES (1,10,7,'НЗП_ЗНАЧЕНИЕ(''331'',7)')
INSERT #F VALUES (1,11,7,'НЗП_ЗНАЧЕНИЕ(''401'',7)')
INSERT #F VALUES (1,12,7,'НЗП_ЗНАЧЕНИЕ(''411'',7)')
INSERT #F VALUES (1,13,7,'НЗП_ЗНАЧЕНИЕ(''421'',7)')
INSERT #F VALUES (1,14,7,'НЗП_ЗНАЧЕНИЕ(''103'',7)')
INSERT #F VALUES (1,15,7,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,7,'ЗАПРЕТ()')
INSERT #F VALUES (1,2,8,'НЗП_ЗНАЧЕНИЕ(''3014'',8)')
INSERT #F VALUES (1,3,8,'НЗП_ЗНАЧЕНИЕ(''101'',8)')
INSERT #F VALUES (1,4,8,'НЗП_ЗНАЧЕНИЕ(''102'',8)')
INSERT #F VALUES (1,5,8,'НЗП_ЗНАЧЕНИЕ(''3113'',8)')
INSERT #F VALUES (1,6,8,'НЗП_ЗНАЧЕНИЕ(''312'',8)')
INSERT #F VALUES (1,7,8,'НЗП_ЗНАЧЕНИЕ(''313'',8)')
INSERT #F VALUES (1,8,8,'НЗП_ЗНАЧЕНИЕ(''302'',8)')
INSERT #F VALUES (1,9,8,'НЗП_ЗНАЧЕНИЕ(''321'',8)')
INSERT #F VALUES (1,10,8,'НЗП_ЗНАЧЕНИЕ(''331'',8)')
INSERT #F VALUES (1,11,8,'НЗП_ЗНАЧЕНИЕ(''401'',8)')
INSERT #F VALUES (1,12,8,'НЗП_ЗНАЧЕНИЕ(''411'',8)')
INSERT #F VALUES (1,13,8,'НЗП_ЗНАЧЕНИЕ(''421'',8)')
INSERT #F VALUES (1,14,8,'НЗП_ЗНАЧЕНИЕ(''103'',8)')
INSERT #F VALUES (1,15,8,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,8,'ЗАПРЕТ()')
INSERT #F VALUES (1,2,9,'НЗП_ЗНАЧЕНИЕ(''3014'',9)')
INSERT #F VALUES (1,3,9,'НЗП_ЗНАЧЕНИЕ(''101'',9)')
INSERT #F VALUES (1,4,9,'НЗП_ЗНАЧЕНИЕ(''102'',9)')
INSERT #F VALUES (1,5,9,'НЗП_ЗНАЧЕНИЕ(''3113'',9)')
INSERT #F VALUES (1,6,9,'НЗП_ЗНАЧЕНИЕ(''312'',9)')
INSERT #F VALUES (1,7,9,'НЗП_ЗНАЧЕНИЕ(''313'',9)')
INSERT #F VALUES (1,8,9,'НЗП_ЗНАЧЕНИЕ(''302'',9)')
INSERT #F VALUES (1,9,9,'НЗП_ЗНАЧЕНИЕ(''321'',9)')
INSERT #F VALUES (1,10,9,'НЗП_ЗНАЧЕНИЕ(''331'',9)')
INSERT #F VALUES (1,11,9,'НЗП_ЗНАЧЕНИЕ(''401'',9)')
INSERT #F VALUES (1,12,9,'НЗП_ЗНАЧЕНИЕ(''411'',9)')
INSERT #F VALUES (1,13,9,'НЗП_ЗНАЧЕНИЕ(''421'',9)')
INSERT #F VALUES (1,14,9,'НЗП_ЗНАЧЕНИЕ(''103'',9)')
INSERT #F VALUES (1,2,10,'НЗП_ЗНАЧЕНИЕ(''3014'',10)')
INSERT #F VALUES (1,3,10,'НЗП_ЗНАЧЕНИЕ(''101'',10)')
INSERT #F VALUES (1,4,10,'НЗП_ЗНАЧЕНИЕ(''102'',10)')
INSERT #F VALUES (1,5,10,'НЗП_ЗНАЧЕНИЕ(''3113'',10)')
INSERT #F VALUES (1,6,10,'НЗП_ЗНАЧЕНИЕ(''312'',10)')
INSERT #F VALUES (1,7,10,'НЗП_ЗНАЧЕНИЕ(''313'',10)')
INSERT #F VALUES (1,8,10,'НЗП_ЗНАЧЕНИЕ(''302'',10)')
INSERT #F VALUES (1,9,10,'НЗП_ЗНАЧЕНИЕ(''321'',10)')
INSERT #F VALUES (1,10,10,'НЗП_ЗНАЧЕНИЕ(''331'',10)')
INSERT #F VALUES (1,11,10,'НЗП_ЗНАЧЕНИЕ(''401'',10)')
INSERT #F VALUES (1,12,10,'НЗП_ЗНАЧЕНИЕ(''411'',10)')
INSERT #F VALUES (1,13,10,'НЗП_ЗНАЧЕНИЕ(''421'',10)')
INSERT #F VALUES (1,14,10,'НЗП_ЗНАЧЕНИЕ(''103'',10)')
INSERT #F VALUES (1,15,10,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,10,'ЗАПРЕТ()')
INSERT #F VALUES (1,2,11,'НЗП_ЗНАЧЕНИЕ(''3014'',11)')
INSERT #F VALUES (1,3,11,'НЗП_ЗНАЧЕНИЕ(''101'',11)')
INSERT #F VALUES (1,4,11,'НЗП_ЗНАЧЕНИЕ(''102'',11)')
INSERT #F VALUES (1,5,11,'НЗП_ЗНАЧЕНИЕ(''3113'',11)')
INSERT #F VALUES (1,6,11,'НЗП_ЗНАЧЕНИЕ(''312'',11)')
INSERT #F VALUES (1,7,11,'НЗП_ЗНАЧЕНИЕ(''313'',11)')
INSERT #F VALUES (1,8,11,'НЗП_ЗНАЧЕНИЕ(''302'',11)')
INSERT #F VALUES (1,9,11,'НЗП_ЗНАЧЕНИЕ(''321'',11)')
INSERT #F VALUES (1,10,11,'НЗП_ЗНАЧЕНИЕ(''331'',11)')
INSERT #F VALUES (1,11,11,'НЗП_ЗНАЧЕНИЕ(''401'',11)')
INSERT #F VALUES (1,12,11,'НЗП_ЗНАЧЕНИЕ(''411'',11)')
INSERT #F VALUES (1,13,11,'НЗП_ЗНАЧЕНИЕ(''421'',11)')
INSERT #F VALUES (1,14,11,'НЗП_ЗНАЧЕНИЕ(''103'',11)')
INSERT #F VALUES (1,2,12,'НЗП_ЗНАЧЕНИЕ(''3014'',12)')
INSERT #F VALUES (1,3,12,'НЗП_ЗНАЧЕНИЕ(''101'',12)')
INSERT #F VALUES (1,4,12,'НЗП_ЗНАЧЕНИЕ(''102'',12)')
INSERT #F VALUES (1,5,12,'НЗП_ЗНАЧЕНИЕ(''3113'',12)')
INSERT #F VALUES (1,6,12,'НЗП_ЗНАЧЕНИЕ(''312'',12)')
INSERT #F VALUES (1,7,12,'НЗП_ЗНАЧЕНИЕ(''313'',12)')
INSERT #F VALUES (1,8,12,'НЗП_ЗНАЧЕНИЕ(''302'',12)')
INSERT #F VALUES (1,9,12,'НЗП_ЗНАЧЕНИЕ(''321'',12)')
INSERT #F VALUES (1,10,12,'НЗП_ЗНАЧЕНИЕ(''331'',12)')
INSERT #F VALUES (1,11,12,'НЗП_ЗНАЧЕНИЕ(''401'',12)')
INSERT #F VALUES (1,12,12,'НЗП_ЗНАЧЕНИЕ(''411'',12)')
INSERT #F VALUES (1,13,12,'НЗП_ЗНАЧЕНИЕ(''421'',12)')
INSERT #F VALUES (1,14,12,'НЗП_ЗНАЧЕНИЕ(''103'',12)')
INSERT #F VALUES (1,2,13,'НЗП_ЗНАЧЕНИЕ(''3014'',13)')
INSERT #F VALUES (1,3,13,'НЗП_ЗНАЧЕНИЕ(''101'',13)')
INSERT #F VALUES (1,4,13,'НЗП_ЗНАЧЕНИЕ(''102'',13)')
INSERT #F VALUES (1,5,13,'НЗП_ЗНАЧЕНИЕ(''3113'',13)')
INSERT #F VALUES (1,6,13,'НЗП_ЗНАЧЕНИЕ(''312'',13)')
INSERT #F VALUES (1,7,13,'НЗП_ЗНАЧЕНИЕ(''313'',13)')
INSERT #F VALUES (1,8,13,'НЗП_ЗНАЧЕНИЕ(''302'',13)')
INSERT #F VALUES (1,9,13,'НЗП_ЗНАЧЕНИЕ(''321'',13)')
INSERT #F VALUES (1,10,13,'НЗП_ЗНАЧЕНИЕ(''331'',13)')
INSERT #F VALUES (1,11,13,'НЗП_ЗНАЧЕНИЕ(''401'',13)')
INSERT #F VALUES (1,12,13,'НЗП_ЗНАЧЕНИЕ(''411'',13)')
INSERT #F VALUES (1,13,13,'НЗП_ЗНАЧЕНИЕ(''421'',13)')
INSERT #F VALUES (1,14,13,'НЗП_ЗНАЧЕНИЕ(''103'',13)')
INSERT #F VALUES (1,15,13,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,13,'ЗАПРЕТ()')
INSERT #F VALUES (1,2,14,'НЗП_ЗНАЧЕНИЕ(''3014'',14)')
INSERT #F VALUES (1,3,14,'НЗП_ЗНАЧЕНИЕ(''101'',14)')
INSERT #F VALUES (1,4,14,'НЗП_ЗНАЧЕНИЕ(''102'',14)')
INSERT #F VALUES (1,5,14,'НЗП_ЗНАЧЕНИЕ(''3113'',14)')
INSERT #F VALUES (1,6,14,'НЗП_ЗНАЧЕНИЕ(''312'',14)')
INSERT #F VALUES (1,7,14,'НЗП_ЗНАЧЕНИЕ(''313'',14)')
INSERT #F VALUES (1,8,14,'НЗП_ЗНАЧЕНИЕ(''302'',14)')
INSERT #F VALUES (1,9,14,'НЗП_ЗНАЧЕНИЕ(''321'',14)')
INSERT #F VALUES (1,10,14,'НЗП_ЗНАЧЕНИЕ(''331'',14)')
INSERT #F VALUES (1,11,14,'НЗП_ЗНАЧЕНИЕ(''401'',14)')
INSERT #F VALUES (1,12,14,'НЗП_ЗНАЧЕНИЕ(''411'',14)')
INSERT #F VALUES (1,13,14,'НЗП_ЗНАЧЕНИЕ(''421'',14)')
INSERT #F VALUES (1,14,14,'НЗП_ЗНАЧЕНИЕ(''103'',14)')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 206
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'
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 0
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'
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 0
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

-- Переформирование процедур 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-02-27 10:52:02.667',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-02-27 10:52:02.667'
	BEGIN
		SELECT @vcMessage = 'Форма 0606047 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0606047 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-02-27 10:52:02.667. Обновление отклонено.'
	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. (фев 27 2014 10:52:11:950AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0606048 (Сведения о численности и оплате труда работников сферы образования по категориям персонала)
-- Дата ввода : 20130601
-- Дата окончания действия :
-- Версия : 2014-02-27 10:52:11.940
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

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] = '0606048' AND [START_DATE] = '20130601'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-02-27 10:52:11.940',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_' + '0606048',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 = '0606048'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20130601')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. 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,6,1,1,1,2291,'RA_EXPORT_FORM',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, '','sv_0606049_20130101.bas','','KirRepMakerMultiSheet.xls','sv_0606048_20130101.xlt','',NULL,'RA_EXPORT_FORM',0,NULL,NULL,NULL,'          ','REPORTS_ATR_TYPE_ORG,REPORTS_FILTER_SUBDIV,REPORTS_ATR_INCR_ITOG',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,1,0,2000,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,3,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, 3,'№ строки',@iLINK_TABLE,1,1,3,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, 4,'Средняя численность работников, человек: списочного состава',@iLINK_TABLE,1,0,4,0,1,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,0,1,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,1,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,0,7,0,1,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,1,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,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр. 3) ОМС',@iLINK_TABLE,1,0,10,0,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр.3) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,11,0,1,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, 12,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) за счет средств бюджетов всех уровней',@iLINK_TABLE,1,0,12,0,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ОМС',@iLINK_TABLE,1,0,13,0,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,14,0,1,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

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,4,1)
INSERT #R VALUES (3,1,5,1)
INSERT #R VALUES (4,1,27,1)
INSERT #R VALUES (5,1,6,1)
INSERT #R VALUES (6,1,7,1)
INSERT #R VALUES (7,1,8,1)
INSERT #R VALUES (8,1,9,1)
INSERT #R VALUES (9,1,10,1)
INSERT #R VALUES (10,1,11,1)
INSERT #R VALUES (11,1,28,1)
INSERT #R VALUES (12,1,29,1)
INSERT #R VALUES (13,1,30,1)
INSERT #R VALUES (14,1,12,1)
INSERT #R VALUES (15,1,13,1)
INSERT #R VALUES (16,1,14,1)
INSERT #R VALUES (17,1,14,1)
INSERT #R VALUES (18,1,15,1)
INSERT #R VALUES (19,1,17,1)
INSERT #R VALUES (20,1,18,1)
INSERT #R VALUES (21,1,19,1)
INSERT #R VALUES (22,1,20,1)
INSERT #R VALUES (23,1,21,1)
INSERT #R VALUES (24,1,22,1)
INSERT #R VALUES (25,1,23,1)
INSERT #R VALUES (26,1,24,1)
INSERT #R VALUES (27,1,25,1)
INSERT #R VALUES (28,1,26,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 28
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,'Всего работников (сумма строк 02 - 05,07,08,11,14,17-19,21,23-28)')
INSERT #F VALUES (1,2,1,'в том числе: руководитель организации')
INSERT #F VALUES (1,3,1,'заместители руководителя и руководители структурных подразделений  и их заместители')
INSERT #F VALUES (1,4,1,'педагогические работники дощкольных общеобразовательных учреждений')
INSERT #F VALUES (1,5,1,'педагогические работники общеобразовательных учреждений')
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,'педагогические работники общеобразовательных учреждений СПО')
INSERT #F VALUES (1,12,1,'из них преподаватели')
INSERT #F VALUES (1,13,1,'мастера производственного обучения')
INSERT #F VALUES (1,14,1,'педагогические работники учреждений дополнительного профессионального образования, осуществляющие подготовку (повышение квалификации) специалистов, имеющих среднее профессиональное образование')
INSERT #F VALUES (1,15,1,'из них преподаватели')
INSERT #F VALUES (1,16,1,'мастера производственного обучения')
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,'научные работники учреждений дополнительного профессионального образования')
INSERT #F VALUES (1,22,1,'из них научные сотрудники')
INSERT #F VALUES (1,23,1,'врачи')
INSERT #F VALUES (1,24,1,'средний медицинский персонал')
INSERT #F VALUES (1,25,1,'младший медицинский персонал')
INSERT #F VALUES (1,26,1,'работники культуры')
INSERT #F VALUES (1,27,1,'социальные работники')
INSERT #F VALUES (1,28,1,'прочий персонал')
INSERT #F VALUES (1,1,2,'100                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,2,2,'101                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,3,2,'102                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,4,2,'201                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,5,2,'211                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,6,2,'212                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,7,2,'221                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,8,2,'231                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,9,2,'232                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,10,2,'233                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,11,2,'241                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,12,2,'242                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,13,2,'243                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,14,2,'251                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,15,2,'252                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,16,2,'253                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,17,2,'261                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,18,2,'271                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,19,2,'301                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,20,2,'311                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,21,2,'301                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,22,2,'311                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,23,2,'401                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,24,2,'411                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,25,2,'421                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,26,2,'631                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,27,2,'501                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,28,2,'103                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,1,3,'01                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,2,3,'02                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,3,3,'03                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,4,3,'04                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,5,3,'05                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,6,3,'06                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,7,3,'07                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,8,3,'08                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,9,3,'09                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,10,3,'10                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,11,3,'11                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,12,3,'12                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,13,3,'13                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,14,3,'14                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,15,3,'15                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,16,3,'16                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,17,3,'17                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,18,3,'18                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,19,3,'19                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,20,3,'20                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,21,3,'21                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,22,3,'22                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,23,3,'23                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,24,3,'24                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,25,3,'25                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,26,3,'26                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,27,3,'27                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,28,3,'28                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,1,4,'НЗП_УСТАНОВКА() + НЗП_ЗНАЧЕНИЕ(''100'',4)')
INSERT #F VALUES (1,2,4,'НЗП_ЗНАЧЕНИЕ(''101'',4)')
INSERT #F VALUES (1,3,4,'НЗП_ЗНАЧЕНИЕ(''102'',4)')
INSERT #F VALUES (1,4,4,'НЗП_ЗНАЧЕНИЕ(''201'',4)')
INSERT #F VALUES (1,5,4,'НЗП_ЗНАЧЕНИЕ(''211'',4)')
INSERT #F VALUES (1,6,4,'НЗП_ЗНАЧЕНИЕ(''212'',4)')
INSERT #F VALUES (1,7,4,'НЗП_ЗНАЧЕНИЕ(''221'',4)')
INSERT #F VALUES (1,8,4,'НЗП_ЗНАЧЕНИЕ(''231'',4)')
INSERT #F VALUES (1,9,4,'НЗП_ЗНАЧЕНИЕ(''232'',4)')
INSERT #F VALUES (1,10,4,'НЗП_ЗНАЧЕНИЕ(''233'',4)')
INSERT #F VALUES (1,11,4,'НЗП_ЗНАЧЕНИЕ(''241'',4)')
INSERT #F VALUES (1,12,4,'НЗП_ЗНАЧЕНИЕ(''242'',4)')
INSERT #F VALUES (1,13,4,'НЗП_ЗНАЧЕНИЕ(''243'',4)')
INSERT #F VALUES (1,14,4,'НЗП_ЗНАЧЕНИЕ(''251'',4)')
INSERT #F VALUES (1,15,4,'НЗП_ЗНАЧЕНИЕ(''252'',4)')
INSERT #F VALUES (1,16,4,'НЗП_ЗНАЧЕНИЕ(''253'',4)')
INSERT #F VALUES (1,17,4,'НЗП_ЗНАЧЕНИЕ(''261'',4)')
INSERT #F VALUES (1,18,4,'НЗП_ЗНАЧЕНИЕ(''271'',4)')
INSERT #F VALUES (1,19,4,'НЗП_ЗНАЧЕНИЕ(''3011'',4)')
INSERT #F VALUES (1,20,4,'НЗП_ЗНАЧЕНИЕ(''3111'',4)')
INSERT #F VALUES (1,21,4,'НЗП_ЗНАЧЕНИЕ(''3012'',4)')
INSERT #F VALUES (1,22,4,'НЗП_ЗНАЧЕНИЕ(''3112'',4)')
INSERT #F VALUES (1,23,4,'НЗП_ЗНАЧЕНИЕ(''401'',4)')
INSERT #F VALUES (1,24,4,'НЗП_ЗНАЧЕНИЕ(''411'',4)')
INSERT #F VALUES (1,25,4,'НЗП_ЗНАЧЕНИЕ(''421'',4)')
INSERT #F VALUES (1,26,4,'НЗП_ЗНАЧЕНИЕ(''631'',4)')
INSERT #F VALUES (1,27,4,'НЗП_ЗНАЧЕНИЕ(''501'',4)')
INSERT #F VALUES (1,28,4,'НЗП_ЗНАЧЕНИЕ(''103'',4)')
INSERT #F VALUES (1,2,5,'НЗП_ЗНАЧЕНИЕ(''101'',5)')
INSERT #F VALUES (1,3,5,'НЗП_ЗНАЧЕНИЕ(''102'',5)')
INSERT #F VALUES (1,4,5,'НЗП_ЗНАЧЕНИЕ(''201'',5)')
INSERT #F VALUES (1,5,5,'НЗП_ЗНАЧЕНИЕ(''211'',5)')
INSERT #F VALUES (1,6,5,'НЗП_ЗНАЧЕНИЕ(''212'',5)')
INSERT #F VALUES (1,7,5,'НЗП_ЗНАЧЕНИЕ(''221'',5)')
INSERT #F VALUES (1,8,5,'НЗП_ЗНАЧЕНИЕ(''231'',5)')
INSERT #F VALUES (1,9,5,'НЗП_ЗНАЧЕНИЕ(''232'',5)')
INSERT #F VALUES (1,10,5,'НЗП_ЗНАЧЕНИЕ(''233'',5)')
INSERT #F VALUES (1,11,5,'НЗП_ЗНАЧЕНИЕ(''241'',5)')
INSERT #F VALUES (1,12,5,'НЗП_ЗНАЧЕНИЕ(''242'',5)')
INSERT #F VALUES (1,13,5,'НЗП_ЗНАЧЕНИЕ(''243'',5)')
INSERT #F VALUES (1,14,5,'НЗП_ЗНАЧЕНИЕ(''251'',5)')
INSERT #F VALUES (1,15,5,'НЗП_ЗНАЧЕНИЕ(''252'',5)')
INSERT #F VALUES (1,16,5,'НЗП_ЗНАЧЕНИЕ(''253'',5)')
INSERT #F VALUES (1,17,5,'НЗП_ЗНАЧЕНИЕ(''261'',5)')
INSERT #F VALUES (1,18,5,'НЗП_ЗНАЧЕНИЕ(''271'',5)')
INSERT #F VALUES (1,19,5,'НЗП_ЗНАЧЕНИЕ(''3011'',5)')
INSERT #F VALUES (1,20,5,'НЗП_ЗНАЧЕНИЕ(''3111'',5)')
INSERT #F VALUES (1,21,5,'НЗП_ЗНАЧЕНИЕ(''3012'',5)')
INSERT #F VALUES (1,22,5,'НЗП_ЗНАЧЕНИЕ(''3112'',5)')
INSERT #F VALUES (1,23,5,'НЗП_ЗНАЧЕНИЕ(''401'',5)')
INSERT #F VALUES (1,24,5,'НЗП_ЗНАЧЕНИЕ(''411'',5)')
INSERT #F VALUES (1,25,5,'НЗП_ЗНАЧЕНИЕ(''421'',5)')
INSERT #F VALUES (1,26,5,'НЗП_ЗНАЧЕНИЕ(''631'',5)')
INSERT #F VALUES (1,27,5,'НЗП_ЗНАЧЕНИЕ(''501'',5)')
INSERT #F VALUES (1,28,5,'НЗП_ЗНАЧЕНИЕ(''103'',5)')
INSERT #F VALUES (1,2,6,'НЗП_ЗНАЧЕНИЕ(''101'',6)')
INSERT #F VALUES (1,3,6,'НЗП_ЗНАЧЕНИЕ(''102'',6)')
INSERT #F VALUES (1,4,6,'НЗП_ЗНАЧЕНИЕ(''201'',6)')
INSERT #F VALUES (1,5,6,'НЗП_ЗНАЧЕНИЕ(''211'',6)')
INSERT #F VALUES (1,6,6,'НЗП_ЗНАЧЕНИЕ(''212'',6)')
INSERT #F VALUES (1,7,6,'НЗП_ЗНАЧЕНИЕ(''221'',6)')
INSERT #F VALUES (1,8,6,'НЗП_ЗНАЧЕНИЕ(''231'',6)')
INSERT #F VALUES (1,9,6,'НЗП_ЗНАЧЕНИЕ(''232'',6)')
INSERT #F VALUES (1,10,6,'НЗП_ЗНАЧЕНИЕ(''233'',6)')
INSERT #F VALUES (1,11,6,'НЗП_ЗНАЧЕНИЕ(''241'',6)')
INSERT #F VALUES (1,12,6,'НЗП_ЗНАЧЕНИЕ(''242'',6)')
INSERT #F VALUES (1,13,6,'НЗП_ЗНАЧЕНИЕ(''243'',6)')
INSERT #F VALUES (1,14,6,'НЗП_ЗНАЧЕНИЕ(''251'',6)')
INSERT #F VALUES (1,15,6,'НЗП_ЗНАЧЕНИЕ(''252'',6)')
INSERT #F VALUES (1,16,6,'НЗП_ЗНАЧЕНИЕ(''253'',6)')
INSERT #F VALUES (1,17,6,'НЗП_ЗНАЧЕНИЕ(''261'',6)')
INSERT #F VALUES (1,18,6,'НЗП_ЗНАЧЕНИЕ(''271'',6)')
INSERT #F VALUES (1,19,6,'НЗП_ЗНАЧЕНИЕ(''3011'',6)')
INSERT #F VALUES (1,20,6,'НЗП_ЗНАЧЕНИЕ(''3111'',6)')
INSERT #F VALUES (1,21,6,'НЗП_ЗНАЧЕНИЕ(''3012'',6)')
INSERT #F VALUES (1,22,6,'НЗП_ЗНАЧЕНИЕ(''3112'',6)')
INSERT #F VALUES (1,23,6,'НЗП_ЗНАЧЕНИЕ(''401'',6)')
INSERT #F VALUES (1,24,6,'НЗП_ЗНАЧЕНИЕ(''411'',6)')
INSERT #F VALUES (1,25,6,'НЗП_ЗНАЧЕНИЕ(''421'',6)')
INSERT #F VALUES (1,26,6,'НЗП_ЗНАЧЕНИЕ(''631'',6)')
INSERT #F VALUES (1,27,6,'НЗП_ЗНАЧЕНИЕ(''501'',6)')
INSERT #F VALUES (1,28,6,'НЗП_ЗНАЧЕНИЕ(''103'',6)')
INSERT #F VALUES (1,2,7,'НЗП_ЗНАЧЕНИЕ(''101'',7)')
INSERT #F VALUES (1,3,7,'НЗП_ЗНАЧЕНИЕ(''102'',7)')
INSERT #F VALUES (1,4,7,'НЗП_ЗНАЧЕНИЕ(''201'',7)')
INSERT #F VALUES (1,5,7,'НЗП_ЗНАЧЕНИЕ(''211'',7)')
INSERT #F VALUES (1,6,7,'НЗП_ЗНАЧЕНИЕ(''212'',7)')
INSERT #F VALUES (1,7,7,'НЗП_ЗНАЧЕНИЕ(''221'',7)')
INSERT #F VALUES (1,8,7,'НЗП_ЗНАЧЕНИЕ(''231'',7)')
INSERT #F VALUES (1,9,7,'НЗП_ЗНАЧЕНИЕ(''232'',7)')
INSERT #F VALUES (1,10,7,'НЗП_ЗНАЧЕНИЕ(''233'',7)')
INSERT #F VALUES (1,11,7,'НЗП_ЗНАЧЕНИЕ(''241'',7)')
INSERT #F VALUES (1,12,7,'НЗП_ЗНАЧЕНИЕ(''242'',7)')
INSERT #F VALUES (1,13,7,'НЗП_ЗНАЧЕНИЕ(''243'',7)')
INSERT #F VALUES (1,14,7,'НЗП_ЗНАЧЕНИЕ(''251'',7)')
INSERT #F VALUES (1,15,7,'НЗП_ЗНАЧЕНИЕ(''252'',7)')
INSERT #F VALUES (1,16,7,'НЗП_ЗНАЧЕНИЕ(''253'',7)')
INSERT #F VALUES (1,17,7,'НЗП_ЗНАЧЕНИЕ(''261'',7)')
INSERT #F VALUES (1,18,7,'НЗП_ЗНАЧЕНИЕ(''271'',7)')
INSERT #F VALUES (1,19,7,'НЗП_ЗНАЧЕНИЕ(''3011'',7)')
INSERT #F VALUES (1,20,7,'НЗП_ЗНАЧЕНИЕ(''3111'',7)')
INSERT #F VALUES (1,21,7,'НЗП_ЗНАЧЕНИЕ(''3012'',7)')
INSERT #F VALUES (1,22,7,'НЗП_ЗНАЧЕНИЕ(''3112'',7)')
INSERT #F VALUES (1,23,7,'НЗП_ЗНАЧЕНИЕ(''401'',7)')
INSERT #F VALUES (1,24,7,'НЗП_ЗНАЧЕНИЕ(''411'',7)')
INSERT #F VALUES (1,25,7,'НЗП_ЗНАЧЕНИЕ(''421'',7)')
INSERT #F VALUES (1,26,7,'НЗП_ЗНАЧЕНИЕ(''631'',7)')
INSERT #F VALUES (1,27,7,'НЗП_ЗНАЧЕНИЕ(''501'',7)')
INSERT #F VALUES (1,28,7,'НЗП_ЗНАЧЕНИЕ(''103'',7)')
INSERT #F VALUES (1,2,8,'НЗП_ЗНАЧЕНИЕ(''101'',8)')
INSERT #F VALUES (1,3,8,'НЗП_ЗНАЧЕНИЕ(''102'',8)')
INSERT #F VALUES (1,4,8,'НЗП_ЗНАЧЕНИЕ(''201'',8)')
INSERT #F VALUES (1,5,8,'НЗП_ЗНАЧЕНИЕ(''211'',8)')
INSERT #F VALUES (1,6,8,'НЗП_ЗНАЧЕНИЕ(''212'',8)')
INSERT #F VALUES (1,7,8,'НЗП_ЗНАЧЕНИЕ(''221'',8)')
INSERT #F VALUES (1,8,8,'НЗП_ЗНАЧЕНИЕ(''231'',8)')
INSERT #F VALUES (1,9,8,'НЗП_ЗНАЧЕНИЕ(''232'',8)')
INSERT #F VALUES (1,10,8,'НЗП_ЗНАЧЕНИЕ(''233'',8)')
INSERT #F VALUES (1,11,8,'НЗП_ЗНАЧЕНИЕ(''241'',8)')
INSERT #F VALUES (1,12,8,'НЗП_ЗНАЧЕНИЕ(''242'',8)')
INSERT #F VALUES (1,13,8,'НЗП_ЗНАЧЕНИЕ(''243'',8)')
INSERT #F VALUES (1,14,8,'НЗП_ЗНАЧЕНИЕ(''251'',8)')
INSERT #F VALUES (1,15,8,'НЗП_ЗНАЧЕНИЕ(''252'',8)')
INSERT #F VALUES (1,16,8,'НЗП_ЗНАЧЕНИЕ(''253'',8)')
INSERT #F VALUES (1,17,8,'НЗП_ЗНАЧЕНИЕ(''261'',8)')
INSERT #F VALUES (1,18,8,'НЗП_ЗНАЧЕНИЕ(''271'',8)')
INSERT #F VALUES (1,19,8,'НЗП_ЗНАЧЕНИЕ(''3011'',8)')
INSERT #F VALUES (1,20,8,'НЗП_ЗНАЧЕНИЕ(''3111'',8)')
INSERT #F VALUES (1,21,8,'НЗП_ЗНАЧЕНИЕ(''3012'',8)')
INSERT #F VALUES (1,22,8,'НЗП_ЗНАЧЕНИЕ(''3112'',8)')
INSERT #F VALUES (1,23,8,'НЗП_ЗНАЧЕНИЕ(''401'',8)')
INSERT #F VALUES (1,24,8,'НЗП_ЗНАЧЕНИЕ(''411'',8)')
INSERT #F VALUES (1,25,8,'НЗП_ЗНАЧЕНИЕ(''421'',8)')
INSERT #F VALUES (1,26,8,'НЗП_ЗНАЧЕНИЕ(''631'',8)')
INSERT #F VALUES (1,27,8,'НЗП_ЗНАЧЕНИЕ(''501'',8)')
INSERT #F VALUES (1,28,8,'НЗП_ЗНАЧЕНИЕ(''103'',8)')
INSERT #F VALUES (1,2,9,'НЗП_ЗНАЧЕНИЕ(''101'',9)')
INSERT #F VALUES (1,3,9,'НЗП_ЗНАЧЕНИЕ(''102'',9)')
INSERT #F VALUES (1,4,9,'НЗП_ЗНАЧЕНИЕ(''201'',9)')
INSERT #F VALUES (1,5,9,'НЗП_ЗНАЧЕНИЕ(''211'',9)')
INSERT #F VALUES (1,6,9,'НЗП_ЗНАЧЕНИЕ(''212'',9)')
INSERT #F VALUES (1,7,9,'НЗП_ЗНАЧЕНИЕ(''221'',9)')
INSERT #F VALUES (1,8,9,'НЗП_ЗНАЧЕНИЕ(''231'',9)')
INSERT #F VALUES (1,9,9,'НЗП_ЗНАЧЕНИЕ(''232'',9)')
INSERT #F VALUES (1,10,9,'НЗП_ЗНАЧЕНИЕ(''233'',9)')
INSERT #F VALUES (1,11,9,'НЗП_ЗНАЧЕНИЕ(''241'',9)')
INSERT #F VALUES (1,12,9,'НЗП_ЗНАЧЕНИЕ(''242'',9)')
INSERT #F VALUES (1,13,9,'НЗП_ЗНАЧЕНИЕ(''243'',9)')
INSERT #F VALUES (1,14,9,'НЗП_ЗНАЧЕНИЕ(''251'',9)')
INSERT #F VALUES (1,15,9,'НЗП_ЗНАЧЕНИЕ(''252'',9)')
INSERT #F VALUES (1,16,9,'НЗП_ЗНАЧЕНИЕ(''253'',9)')
INSERT #F VALUES (1,17,9,'НЗП_ЗНАЧЕНИЕ(''261'',9)')
INSERT #F VALUES (1,18,9,'НЗП_ЗНАЧЕНИЕ(''271'',9)')
INSERT #F VALUES (1,19,9,'НЗП_ЗНАЧЕНИЕ(''3011'',9)')
INSERT #F VALUES (1,20,9,'НЗП_ЗНАЧЕНИЕ(''3111'',9)')
INSERT #F VALUES (1,21,9,'НЗП_ЗНАЧЕНИЕ(''3012'',9)')
INSERT #F VALUES (1,22,9,'НЗП_ЗНАЧЕНИЕ(''3112'',9)')
INSERT #F VALUES (1,23,9,'НЗП_ЗНАЧЕНИЕ(''401'',9)')
INSERT #F VALUES (1,24,9,'НЗП_ЗНАЧЕНИЕ(''411'',9)')
INSERT #F VALUES (1,25,9,'НЗП_ЗНАЧЕНИЕ(''421'',9)')
INSERT #F VALUES (1,26,9,'НЗП_ЗНАЧЕНИЕ(''631'',9)')
INSERT #F VALUES (1,27,9,'НЗП_ЗНАЧЕНИЕ(''501'',9)')
INSERT #F VALUES (1,28,9,'НЗП_ЗНАЧЕНИЕ(''103'',9)')
INSERT #F VALUES (1,2,10,'НЗП_ЗНАЧЕНИЕ(''101'',10)')
INSERT #F VALUES (1,3,10,'НЗП_ЗНАЧЕНИЕ(''102'',10)')
INSERT #F VALUES (1,4,10,'НЗП_ЗНАЧЕНИЕ(''201'',10)')
INSERT #F VALUES (1,5,10,'НЗП_ЗНАЧЕНИЕ(''211'',10)')
INSERT #F VALUES (1,6,10,'НЗП_ЗНАЧЕНИЕ(''212'',10)')
INSERT #F VALUES (1,7,10,'НЗП_ЗНАЧЕНИЕ(''221'',10)')
INSERT #F VALUES (1,8,10,'НЗП_ЗНАЧЕНИЕ(''231'',10)')
INSERT #F VALUES (1,9,10,'НЗП_ЗНАЧЕНИЕ(''232'',10)')
INSERT #F VALUES (1,10,10,'НЗП_ЗНАЧЕНИЕ(''233'',10)')
INSERT #F VALUES (1,11,10,'НЗП_ЗНАЧЕНИЕ(''241'',10)')
INSERT #F VALUES (1,12,10,'НЗП_ЗНАЧЕНИЕ(''242'',10)')
INSERT #F VALUES (1,13,10,'НЗП_ЗНАЧЕНИЕ(''243'',10)')
INSERT #F VALUES (1,14,10,'НЗП_ЗНАЧЕНИЕ(''251'',10)')
INSERT #F VALUES (1,15,10,'НЗП_ЗНАЧЕНИЕ(''252'',10)')
INSERT #F VALUES (1,16,10,'НЗП_ЗНАЧЕНИЕ(''253'',10)')
INSERT #F VALUES (1,17,10,'НЗП_ЗНАЧЕНИЕ(''261'',10)')
INSERT #F VALUES (1,18,10,'НЗП_ЗНАЧЕНИЕ(''271'',10)')
INSERT #F VALUES (1,19,10,'НЗП_ЗНАЧЕНИЕ(''3011'',10)')
INSERT #F VALUES (1,20,10,'НЗП_ЗНАЧЕНИЕ(''3111'',10)')
INSERT #F VALUES (1,21,10,'НЗП_ЗНАЧЕНИЕ(''3012'',10)')
INSERT #F VALUES (1,22,10,'НЗП_ЗНАЧЕНИЕ(''3112'',10)')
INSERT #F VALUES (1,23,10,'НЗП_ЗНАЧЕНИЕ(''401'',10)')
INSERT #F VALUES (1,24,10,'НЗП_ЗНАЧЕНИЕ(''411'',10)')
INSERT #F VALUES (1,25,10,'НЗП_ЗНАЧЕНИЕ(''421'',10)')
INSERT #F VALUES (1,26,10,'НЗП_ЗНАЧЕНИЕ(''631'',10)')
INSERT #F VALUES (1,27,10,'НЗП_ЗНАЧЕНИЕ(''501'',10)')
INSERT #F VALUES (1,28,10,'НЗП_ЗНАЧЕНИЕ(''103'',10)')
INSERT #F VALUES (1,2,11,'НЗП_ЗНАЧЕНИЕ(''101'',11)')
INSERT #F VALUES (1,3,11,'НЗП_ЗНАЧЕНИЕ(''102'',11)')
INSERT #F VALUES (1,4,11,'НЗП_ЗНАЧЕНИЕ(''201'',11)')
INSERT #F VALUES (1,5,11,'НЗП_ЗНАЧЕНИЕ(''211'',11)')
INSERT #F VALUES (1,6,11,'НЗП_ЗНАЧЕНИЕ(''212'',11)')
INSERT #F VALUES (1,7,11,'НЗП_ЗНАЧЕНИЕ(''221'',11)')
INSERT #F VALUES (1,8,11,'НЗП_ЗНАЧЕНИЕ(''231'',11)')
INSERT #F VALUES (1,9,11,'НЗП_ЗНАЧЕНИЕ(''232'',11)')
INSERT #F VALUES (1,10,11,'НЗП_ЗНАЧЕНИЕ(''233'',11)')
INSERT #F VALUES (1,11,11,'НЗП_ЗНАЧЕНИЕ(''241'',11)')
INSERT #F VALUES (1,12,11,'НЗП_ЗНАЧЕНИЕ(''242'',11)')
INSERT #F VALUES (1,13,11,'НЗП_ЗНАЧЕНИЕ(''243'',11)')
INSERT #F VALUES (1,14,11,'НЗП_ЗНАЧЕНИЕ(''251'',11)')
INSERT #F VALUES (1,15,11,'НЗП_ЗНАЧЕНИЕ(''252'',11)')
INSERT #F VALUES (1,16,11,'НЗП_ЗНАЧЕНИЕ(''253'',11)')
INSERT #F VALUES (1,17,11,'НЗП_ЗНАЧЕНИЕ(''261'',11)')
INSERT #F VALUES (1,18,11,'НЗП_ЗНАЧЕНИЕ(''271'',11)')
INSERT #F VALUES (1,19,11,'НЗП_ЗНАЧЕНИЕ(''3011'',11)')
INSERT #F VALUES (1,20,11,'НЗП_ЗНАЧЕНИЕ(''3111'',11)')
INSERT #F VALUES (1,21,11,'НЗП_ЗНАЧЕНИЕ(''3012'',11)')
INSERT #F VALUES (1,22,11,'НЗП_ЗНАЧЕНИЕ(''3112'',11)')
INSERT #F VALUES (1,23,11,'НЗП_ЗНАЧЕНИЕ(''401'',11)')
INSERT #F VALUES (1,24,11,'НЗП_ЗНАЧЕНИЕ(''411'',11)')
INSERT #F VALUES (1,25,11,'НЗП_ЗНАЧЕНИЕ(''421'',11)')
INSERT #F VALUES (1,26,11,'НЗП_ЗНАЧЕНИЕ(''631'',11)')
INSERT #F VALUES (1,27,11,'НЗП_ЗНАЧЕНИЕ(''501'',11)')
INSERT #F VALUES (1,28,11,'НЗП_ЗНАЧЕНИЕ(''103'',11)')
INSERT #F VALUES (1,2,12,'НЗП_ЗНАЧЕНИЕ(''101'',12)')
INSERT #F VALUES (1,3,12,'НЗП_ЗНАЧЕНИЕ(''102'',12)')
INSERT #F VALUES (1,4,12,'НЗП_ЗНАЧЕНИЕ(''201'',12)')
INSERT #F VALUES (1,5,12,'НЗП_ЗНАЧЕНИЕ(''211'',12)')
INSERT #F VALUES (1,6,12,'НЗП_ЗНАЧЕНИЕ(''212'',12)')
INSERT #F VALUES (1,7,12,'НЗП_ЗНАЧЕНИЕ(''221'',12)')
INSERT #F VALUES (1,8,12,'НЗП_ЗНАЧЕНИЕ(''231'',12)')
INSERT #F VALUES (1,9,12,'НЗП_ЗНАЧЕНИЕ(''232'',12)')
INSERT #F VALUES (1,10,12,'НЗП_ЗНАЧЕНИЕ(''233'',12)')
INSERT #F VALUES (1,11,12,'НЗП_ЗНАЧЕНИЕ(''241'',12)')
INSERT #F VALUES (1,12,12,'НЗП_ЗНАЧЕНИЕ(''242'',12)')
INSERT #F VALUES (1,13,12,'НЗП_ЗНАЧЕНИЕ(''243'',12)')
INSERT #F VALUES (1,14,12,'НЗП_ЗНАЧЕНИЕ(''251'',12)')
INSERT #F VALUES (1,15,12,'НЗП_ЗНАЧЕНИЕ(''252'',12)')
INSERT #F VALUES (1,16,12,'НЗП_ЗНАЧЕНИЕ(''253'',12)')
INSERT #F VALUES (1,17,12,'НЗП_ЗНАЧЕНИЕ(''261'',12)')
INSERT #F VALUES (1,18,12,'НЗП_ЗНАЧЕНИЕ(''271'',12)')
INSERT #F VALUES (1,19,12,'НЗП_ЗНАЧЕНИЕ(''3011'',12)')
INSERT #F VALUES (1,20,12,'НЗП_ЗНАЧЕНИЕ(''3111'',12)')
INSERT #F VALUES (1,21,12,'НЗП_ЗНАЧЕНИЕ(''3012'',12)')
INSERT #F VALUES (1,22,12,'НЗП_ЗНАЧЕНИЕ(''3112,12)')
INSERT #F VALUES (1,23,12,'НЗП_ЗНАЧЕНИЕ(''401'',12)')
INSERT #F VALUES (1,24,12,'НЗП_ЗНАЧЕНИЕ(''411'',12)')
INSERT #F VALUES (1,25,12,'НЗП_ЗНАЧЕНИЕ(''421'',12)')
INSERT #F VALUES (1,26,12,'НЗП_ЗНАЧЕНИЕ(''631'',12)')
INSERT #F VALUES (1,27,12,'НЗП_ЗНАЧЕНИЕ(''501'',12)')
INSERT #F VALUES (1,28,12,'НЗП_ЗНАЧЕНИЕ(''103'',12)')
INSERT #F VALUES (1,2,13,'НЗП_ЗНАЧЕНИЕ(''101'',13)')
INSERT #F VALUES (1,3,13,'НЗП_ЗНАЧЕНИЕ(''102'',13)')
INSERT #F VALUES (1,4,13,'НЗП_ЗНАЧЕНИЕ(''201'',13)')
INSERT #F VALUES (1,5,13,'НЗП_ЗНАЧЕНИЕ(''211'',13)')
INSERT #F VALUES (1,6,13,'НЗП_ЗНАЧЕНИЕ(''212'',13)')
INSERT #F VALUES (1,7,13,'НЗП_ЗНАЧЕНИЕ(''221'',13)')
INSERT #F VALUES (1,8,13,'НЗП_ЗНАЧЕНИЕ(''231'',13)')
INSERT #F VALUES (1,9,13,'НЗП_ЗНАЧЕНИЕ(''232'',13)')
INSERT #F VALUES (1,10,13,'НЗП_ЗНАЧЕНИЕ(''233'',13)')
INSERT #F VALUES (1,11,13,'НЗП_ЗНАЧЕНИЕ(''241'',13)')
INSERT #F VALUES (1,12,13,'НЗП_ЗНАЧЕНИЕ(''242'',13)')
INSERT #F VALUES (1,13,13,'НЗП_ЗНАЧЕНИЕ(''243'',13)')
INSERT #F VALUES (1,14,13,'НЗП_ЗНАЧЕНИЕ(''251'',13)')
INSERT #F VALUES (1,15,13,'НЗП_ЗНАЧЕНИЕ(''252'',13)')
INSERT #F VALUES (1,16,13,'НЗП_ЗНАЧЕНИЕ(''253'',13)')
INSERT #F VALUES (1,17,13,'НЗП_ЗНАЧЕНИЕ(''261'',13)')
INSERT #F VALUES (1,18,13,'НЗП_ЗНАЧЕНИЕ(''271'',13)')
INSERT #F VALUES (1,19,13,'НЗП_ЗНАЧЕНИЕ(''3011'',13)')
INSERT #F VALUES (1,20,13,'НЗП_ЗНАЧЕНИЕ(''3111'',13)')
INSERT #F VALUES (1,21,13,'НЗП_ЗНАЧЕНИЕ(''3012'',13)')
INSERT #F VALUES (1,22,13,'НЗП_ЗНАЧЕНИЕ(''3112'',3)')
INSERT #F VALUES (1,23,13,'НЗП_ЗНАЧЕНИЕ(''401'',13)')
INSERT #F VALUES (1,24,13,'НЗП_ЗНАЧЕНИЕ(''411'',13)')
INSERT #F VALUES (1,25,13,'НЗП_ЗНАЧЕНИЕ(''421'',13)')
INSERT #F VALUES (1,26,13,'НЗП_ЗНАЧЕНИЕ(''631'',13)')
INSERT #F VALUES (1,27,13,'НЗП_ЗНАЧЕНИЕ(''501'',13)')
INSERT #F VALUES (1,28,13,'НЗП_ЗНАЧЕНИЕ(''103'',13)')
INSERT #F VALUES (1,2,14,'НЗП_ЗНАЧЕНИЕ(''101'',14)')
INSERT #F VALUES (1,3,14,'НЗП_ЗНАЧЕНИЕ(''102'',14)')
INSERT #F VALUES (1,4,14,'НЗП_ЗНАЧЕНИЕ(''201'',14)')
INSERT #F VALUES (1,5,14,'НЗП_ЗНАЧЕНИЕ(''211'',14)')
INSERT #F VALUES (1,6,14,'НЗП_ЗНАЧЕНИЕ(''212'',14)')
INSERT #F VALUES (1,7,14,'НЗП_ЗНАЧЕНИЕ(''221'',14)')
INSERT #F VALUES (1,8,14,'НЗП_ЗНАЧЕНИЕ(''231'',14)')
INSERT #F VALUES (1,9,14,'НЗП_ЗНАЧЕНИЕ(''232'',14)')
INSERT #F VALUES (1,10,14,'НЗП_ЗНАЧЕНИЕ(''233'',14)')
INSERT #F VALUES (1,11,14,'НЗП_ЗНАЧЕНИЕ(''241'',14)')
INSERT #F VALUES (1,12,14,'НЗП_ЗНАЧЕНИЕ(''242'',14)')
INSERT #F VALUES (1,13,14,'НЗП_ЗНАЧЕНИЕ(''243'',14)')
INSERT #F VALUES (1,14,14,'НЗП_ЗНАЧЕНИЕ(''251'',14)')
INSERT #F VALUES (1,15,14,'НЗП_ЗНАЧЕНИЕ(''252'',14)')
INSERT #F VALUES (1,16,14,'НЗП_ЗНАЧЕНИЕ(''253'',14)')
INSERT #F VALUES (1,17,14,'НЗП_ЗНАЧЕНИЕ(''261'',14)')
INSERT #F VALUES (1,18,14,'НЗП_ЗНАЧЕНИЕ(''271'',14)')
INSERT #F VALUES (1,19,14,'НЗП_ЗНАЧЕНИЕ(''3011'',14)')
INSERT #F VALUES (1,20,14,'НЗП_ЗНАЧЕНИЕ(''3111'',14)')
INSERT #F VALUES (1,21,14,'НЗП_ЗНАЧЕНИЕ(''3012'',14)')
INSERT #F VALUES (1,22,14,'НЗП_ЗНАЧЕНИЕ(''3112'',14)')
INSERT #F VALUES (1,23,14,'НЗП_ЗНАЧЕНИЕ(''401'',14)')
INSERT #F VALUES (1,24,14,'НЗП_ЗНАЧЕНИЕ(''411'',14)')
INSERT #F VALUES (1,25,14,'НЗП_ЗНАЧЕНИЕ(''421'',14)')
INSERT #F VALUES (1,26,14,'НЗП_ЗНАЧЕНИЕ(''631'',14)')
INSERT #F VALUES (1,27,14,'НЗП_ЗНАЧЕНИЕ(''501'',14)')
INSERT #F VALUES (1,28,14,'НЗП_ЗНАЧЕНИЕ(''103'',14)')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 382
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,'т.1стр.01 =  т.1стр.02 +  т.1стр.03 +  т.1стр.05 +  т.1стр.07 +  т.1стр.08 +  т.1стр.11 +  т.1стр.14 +  т.1стр.18 +  т.1стр.19 +  т.1стр.17 +  т.1стр.04 +  т.1стр.21 +  т.1стр.23 +  т.1стр.24 +  т.1стр.25 +  т.1стр.26 +  т.1стр.27 +  т.1стр.28',1,3,1,'20130912','','','','0606048','20130601','','=',2,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 1
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,'','','','','','','','','','01','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','02','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','03','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','05','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','07','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','08','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','11','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','14','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,9,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','18','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,10,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','19','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,11,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','17','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,12,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','04','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,13,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','21','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,14,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','23','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,15,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','24','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,16,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','25','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,17,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','26','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,18,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','27','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,19,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','28','1',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) <> 19
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] = '451       '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'451','Республика Коми',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] = '606       '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'606','Заработная плата',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-02-27 10:52:11.940',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-02-27 10:52:11.940'
	BEGIN
		SELECT @vcMessage = 'Форма 0606048 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0606048 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-02-27 10:52:11.940. Обновление отклонено.'
	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. (фев 27 2014 10:52:20:380AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0606049 (Сведения о численности и оплате труда работников сферы социального обслуживания по категориям персонала)
-- Дата ввода : 20130601
-- Дата окончания действия :
-- Версия : 2014-02-27 10:52:20.363
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

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] = '0606049' AND [START_DATE] = '20130601'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-02-27 10:52:20.363',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_' + '0606049',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 = '0606049'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20130601')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. 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,6,1,1,1,2291,'RA_EXPORT_FORM',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, '','sv_0606049_20130101.bas','','KirRepMakerMultiSheet.xls','sv_0606049_20130101.xlt','',NULL,'RA_EXPORT_FORM',0,NULL,NULL,NULL,'          ','REPORTS_ATR_TYPE_ORG,REPORTS_FILTER_SUBDIV,REPORTS_ATR_INCR_ITOG',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,1,0,2000,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,3,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, 3,'№ строки',@iLINK_TABLE,1,1,3,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, 4,'Средняя численность работников, человек: списочного состава',@iLINK_TABLE,1,0,4,0,1,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,0,1,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,1,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,0,7,0,1,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,1,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,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр. 3) ОМС',@iLINK_TABLE,1,0,10,0,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр.3) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,11,0,1,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, 12,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) за счет средств бюджетов всех уровней',@iLINK_TABLE,1,0,12,0,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ОМС',@iLINK_TABLE,1,0,13,0,1,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,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,14,0,1,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

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,4,1)
INSERT #R VALUES (3,1,5,1)
INSERT #R VALUES (4,1,6,1)
INSERT #R VALUES (5,1,7,1)
INSERT #R VALUES (6,1,8,1)
INSERT #R VALUES (7,1,9,1)
INSERT #R VALUES (8,1,10,1)
INSERT #R VALUES (9,1,11,1)
INSERT #R VALUES (10,1,12,1)
INSERT #R VALUES (11,1,13,1)
INSERT #R VALUES (12,1,14,1)
INSERT #R VALUES (13,1,14,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 13
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,'Всего работников (сумма строк 02 - 04, 06 - 08, 10 - 13)')
INSERT #F VALUES (1,2,1,'в том числе: руководитель организации')
INSERT #F VALUES (1,3,1,'заместители руководителя и руководители структурных подразделений (кроме врачей - руководителей структурных подразделений), иные руководители')
INSERT #F VALUES (1,4,1,'педагогические работники')
INSERT #F VALUES (1,5,1,'из них преподаватели')
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,'младший медицинский (фармацевтический) персонал (персонал, обеспечивающий предоставление медицинских услуг)')
INSERT #F VALUES (1,12,1,'работники, имеющие высшее фармацевтическое или иное высшее образование, предоставляющие медицинские услуги (обеспечивающие предоставление медицинских услуг)')
INSERT #F VALUES (1,13,1,'прочий персонал')
INSERT #F VALUES (1,1,2,'100                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,2,2,'101                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,3,2,'102                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,4,2,'281                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,5,2,'282                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,6,2,'401                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,7,2,'501                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,8,2,'301                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,9,2,'311                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,10,2,'411                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,11,2,'421                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,12,2,'431                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,13,2,'103                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,1,3,'01                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,2,3,'02                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,3,3,'03                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,4,3,'04                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,5,3,'05                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,6,3,'06                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,7,3,'07                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,8,3,'08                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,9,3,'09                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,10,3,'10                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,11,3,'11                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,12,3,'12                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,13,3,'13                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,1,4,'НЗП_УСТАНОВКА() + НЗП_ЗНАЧЕНИЕ(''100'',4)')
INSERT #F VALUES (1,2,4,'НЗП_ЗНАЧЕНИЕ(''101'',4)')
INSERT #F VALUES (1,3,4,'НЗП_ЗНАЧЕНИЕ(''102'',4)')
INSERT #F VALUES (1,4,4,'НЗП_ЗНАЧЕНИЕ(''281'',4)')
INSERT #F VALUES (1,5,4,'НЗП_ЗНАЧЕНИЕ(''282'',4)')
INSERT #F VALUES (1,6,4,'НЗП_ЗНАЧЕНИЕ(''401'',4)')
INSERT #F VALUES (1,7,4,'НЗП_ЗНАЧЕНИЕ(''501'',4)')
INSERT #F VALUES (1,8,4,'НЗП_ЗНАЧЕНИЕ(''3013'',4)')
INSERT #F VALUES (1,9,4,'НЗП_ЗНАЧЕНИЕ(''3113'',4)')
INSERT #F VALUES (1,10,4,'НЗП_ЗНАЧЕНИЕ(''411'',4)')
INSERT #F VALUES (1,11,4,'НЗП_ЗНАЧЕНИЕ(''421'',4)')
INSERT #F VALUES (1,12,4,'НЗП_ЗНАЧЕНИЕ(''431'',4)')
INSERT #F VALUES (1,13,4,'НЗП_ЗНАЧЕНИЕ(''103'',4)')
INSERT #F VALUES (1,2,5,'НЗП_ЗНАЧЕНИЕ(''101'',5)')
INSERT #F VALUES (1,3,5,'НЗП_ЗНАЧЕНИЕ(''102'',5)')
INSERT #F VALUES (1,4,5,'НЗП_ЗНАЧЕНИЕ(''281'',5)')
INSERT #F VALUES (1,5,5,'НЗП_ЗНАЧЕНИЕ(''282'',5)')
INSERT #F VALUES (1,6,5,'НЗП_ЗНАЧЕНИЕ(''401'',5)')
INSERT #F VALUES (1,7,5,'НЗП_ЗНАЧЕНИЕ(''501'',5)')
INSERT #F VALUES (1,8,5,'НЗП_ЗНАЧЕНИЕ(''3013'',5)')
INSERT #F VALUES (1,9,5,'НЗП_ЗНАЧЕНИЕ(''3113'',5)')
INSERT #F VALUES (1,10,5,'НЗП_ЗНАЧЕНИЕ(''411'',5)')
INSERT #F VALUES (1,11,5,'НЗП_ЗНАЧЕНИЕ(''421'',5)')
INSERT #F VALUES (1,12,5,'НЗП_ЗНАЧЕНИЕ(''431'',5)')
INSERT #F VALUES (1,13,5,'НЗП_ЗНАЧЕНИЕ(''103'',5)')
INSERT #F VALUES (1,2,6,'НЗП_ЗНАЧЕНИЕ(''101'',6)')
INSERT #F VALUES (1,3,6,'НЗП_ЗНАЧЕНИЕ(''102'',6)')
INSERT #F VALUES (1,4,6,'НЗП_ЗНАЧЕНИЕ(''281'',6)')
INSERT #F VALUES (1,5,6,'НЗП_ЗНАЧЕНИЕ(''282'',6)')
INSERT #F VALUES (1,6,6,'НЗП_ЗНАЧЕНИЕ(''401'',6)')
INSERT #F VALUES (1,7,6,'НЗП_ЗНАЧЕНИЕ(''501'',6)')
INSERT #F VALUES (1,8,6,'НЗП_ЗНАЧЕНИЕ(''3013'',6)')
INSERT #F VALUES (1,9,6,'НЗП_ЗНАЧЕНИЕ(''3113'',6)')
INSERT #F VALUES (1,10,6,'НЗП_ЗНАЧЕНИЕ(''411'',6)')
INSERT #F VALUES (1,11,6,'НЗП_ЗНАЧЕНИЕ(''421'',6)')
INSERT #F VALUES (1,12,6,'НЗП_ЗНАЧЕНИЕ(''431'',6)')
INSERT #F VALUES (1,13,6,'НЗП_ЗНАЧЕНИЕ(''103'',6)')
INSERT #F VALUES (1,2,7,'НЗП_ЗНАЧЕНИЕ(''101'',7)')
INSERT #F VALUES (1,3,7,'НЗП_ЗНАЧЕНИЕ(''102'',7)')
INSERT #F VALUES (1,4,7,'НЗП_ЗНАЧЕНИЕ(''281'',7)')
INSERT #F VALUES (1,5,7,'НЗП_ЗНАЧЕНИЕ(''282'',7)')
INSERT #F VALUES (1,6,7,'НЗП_ЗНАЧЕНИЕ(''401'',7)')
INSERT #F VALUES (1,7,7,'НЗП_ЗНАЧЕНИЕ(''501'',7)')
INSERT #F VALUES (1,8,7,'НЗП_ЗНАЧЕНИЕ(''3013'',7)')
INSERT #F VALUES (1,9,7,'НЗП_ЗНАЧЕНИЕ(''3113'',7)')
INSERT #F VALUES (1,10,7,'НЗП_ЗНАЧЕНИЕ(''411'',7)')
INSERT #F VALUES (1,11,7,'НЗП_ЗНАЧЕНИЕ(''421'',7)')
INSERT #F VALUES (1,12,7,'НЗП_ЗНАЧЕНИЕ(''431'',7)')
INSERT #F VALUES (1,13,7,'НЗП_ЗНАЧЕНИЕ(''103'',7)')
INSERT #F VALUES (1,2,8,'НЗП_ЗНАЧЕНИЕ(''101'',8)')
INSERT #F VALUES (1,3,8,'НЗП_ЗНАЧЕНИЕ(''102'',8)')
INSERT #F VALUES (1,4,8,'НЗП_ЗНАЧЕНИЕ(''281'',8)')
INSERT #F VALUES (1,5,8,'НЗП_ЗНАЧЕНИЕ(''282'',8)')
INSERT #F VALUES (1,6,8,'НЗП_ЗНАЧЕНИЕ(''401'',8)')
INSERT #F VALUES (1,7,8,'НЗП_ЗНАЧЕНИЕ(''501'',8)')
INSERT #F VALUES (1,8,8,'НЗП_ЗНАЧЕНИЕ(''3013'',8)')
INSERT #F VALUES (1,9,8,'НЗП_ЗНАЧЕНИЕ(''3113'',8)')
INSERT #F VALUES (1,10,8,'НЗП_ЗНАЧЕНИЕ(''411'',8)')
INSERT #F VALUES (1,11,8,'НЗП_ЗНАЧЕНИЕ(''421'',8)')
INSERT #F VALUES (1,12,8,'НЗП_ЗНАЧЕНИЕ(''431'',8)')
INSERT #F VALUES (1,13,8,'НЗП_ЗНАЧЕНИЕ(''103'',8)')
INSERT #F VALUES (1,2,9,'НЗП_ЗНАЧЕНИЕ(''101'',9)')
INSERT #F VALUES (1,3,9,'НЗП_ЗНАЧЕНИЕ(''102'',9)')
INSERT #F VALUES (1,4,9,'НЗП_ЗНАЧЕНИЕ(''281'',9)')
INSERT #F VALUES (1,5,9,'НЗП_ЗНАЧЕНИЕ(''282'',9)')
INSERT #F VALUES (1,6,9,'НЗП_ЗНАЧЕНИЕ(''401'',9)')
INSERT #F VALUES (1,7,9,'НЗП_ЗНАЧЕНИЕ(''501'',9)')
INSERT #F VALUES (1,8,9,'НЗП_ЗНАЧЕНИЕ(''3013'',9)')
INSERT #F VALUES (1,9,9,'НЗП_ЗНАЧЕНИЕ(''3113'',9)')
INSERT #F VALUES (1,10,9,'НЗП_ЗНАЧЕНИЕ(''411'',9)')
INSERT #F VALUES (1,11,9,'НЗП_ЗНАЧЕНИЕ(''421'',9)')
INSERT #F VALUES (1,12,9,'НЗП_ЗНАЧЕНИЕ(''431'',9)')
INSERT #F VALUES (1,13,9,'НЗП_ЗНАЧЕНИЕ(''103'',9)')
INSERT #F VALUES (1,2,10,'НЗП_ЗНАЧЕНИЕ(''101'',10)')
INSERT #F VALUES (1,3,10,'НЗП_ЗНАЧЕНИЕ(''102'',10)')
INSERT #F VALUES (1,4,10,'НЗП_ЗНАЧЕНИЕ(''281'',10)')
INSERT #F VALUES (1,5,10,'НЗП_ЗНАЧЕНИЕ(''282'',10)')
INSERT #F VALUES (1,6,10,'НЗП_ЗНАЧЕНИЕ(''401'',10)')
INSERT #F VALUES (1,7,10,'НЗП_ЗНАЧЕНИЕ(''501'',10)')
INSERT #F VALUES (1,8,10,'НЗП_ЗНАЧЕНИЕ(''3013'',10)')
INSERT #F VALUES (1,9,10,'НЗП_ЗНАЧЕНИЕ(''3113'',10)')
INSERT #F VALUES (1,10,10,'НЗП_ЗНАЧЕНИЕ(''411'',10)')
INSERT #F VALUES (1,11,10,'НЗП_ЗНАЧЕНИЕ(''421'',10)')
INSERT #F VALUES (1,12,10,'НЗП_ЗНАЧЕНИЕ(''431'',10)')
INSERT #F VALUES (1,13,10,'НЗП_ЗНАЧЕНИЕ(''103'',10)')
INSERT #F VALUES (1,2,11,'НЗП_ЗНАЧЕНИЕ(''101'',11)')
INSERT #F VALUES (1,3,11,'НЗП_ЗНАЧЕНИЕ(''102'',11)')
INSERT #F VALUES (1,4,11,'НЗП_ЗНАЧЕНИЕ(''281'',11)')
INSERT #F VALUES (1,5,11,'НЗП_ЗНАЧЕНИЕ(''282'',11)')
INSERT #F VALUES (1,6,11,'НЗП_ЗНАЧЕНИЕ(''401'',11)')
INSERT #F VALUES (1,7,11,'НЗП_ЗНАЧЕНИЕ(''501'',11)')
INSERT #F VALUES (1,8,11,'НЗП_ЗНАЧЕНИЕ(''3013'',11)')
INSERT #F VALUES (1,9,11,'НЗП_ЗНАЧЕНИЕ(''3113'',11)')
INSERT #F VALUES (1,10,11,'НЗП_ЗНАЧЕНИЕ(''411'',11)')
INSERT #F VALUES (1,11,11,'НЗП_ЗНАЧЕНИЕ(''421'',11)')
INSERT #F VALUES (1,12,11,'НЗП_ЗНАЧЕНИЕ(''431'',11)')
INSERT #F VALUES (1,13,11,'НЗП_ЗНАЧЕНИЕ(''103'',11)')
INSERT #F VALUES (1,2,12,'НЗП_ЗНАЧЕНИЕ(''101'',12)')
INSERT #F VALUES (1,3,12,'НЗП_ЗНАЧЕНИЕ(''102'',12)')
INSERT #F VALUES (1,4,12,'НЗП_ЗНАЧЕНИЕ(''281'',12)')
INSERT #F VALUES (1,5,12,'НЗП_ЗНАЧЕНИЕ(''282'',12)')
INSERT #F VALUES (1,6,12,'НЗП_ЗНАЧЕНИЕ(''401'',12)')
INSERT #F VALUES (1,7,12,'НЗП_ЗНАЧЕНИЕ(''501'',12)')
INSERT #F VALUES (1,8,12,'НЗП_ЗНАЧЕНИЕ(''3013'',12)')
INSERT #F VALUES (1,9,12,'НЗП_ЗНАЧЕНИЕ(''3113'',12)')
INSERT #F VALUES (1,10,12,'НЗП_ЗНАЧЕНИЕ(''411'',12)')
INSERT #F VALUES (1,11,12,'НЗП_ЗНАЧЕНИЕ(''421'',12)')
INSERT #F VALUES (1,12,12,'НЗП_ЗНАЧЕНИЕ(''431'',12)')
INSERT #F VALUES (1,13,12,'НЗП_ЗНАЧЕНИЕ(''103'',12)')
INSERT #F VALUES (1,2,13,'НЗП_ЗНАЧЕНИЕ(''101'',13)')
INSERT #F VALUES (1,3,13,'НЗП_ЗНАЧЕНИЕ(''102'',13)')
INSERT #F VALUES (1,4,13,'НЗП_ЗНАЧЕНИЕ(''281'',13)')
INSERT #F VALUES (1,5,13,'НЗП_ЗНАЧЕНИЕ(''282'',13)')
INSERT #F VALUES (1,6,13,'НЗП_ЗНАЧЕНИЕ(''401'',13)')
INSERT #F VALUES (1,7,13,'НЗП_ЗНАЧЕНИЕ(''501'',13)')
INSERT #F VALUES (1,8,13,'НЗП_ЗНАЧЕНИЕ(''3013'',13)')
INSERT #F VALUES (1,9,13,'НЗП_ЗНАЧЕНИЕ(''3113'',13)')
INSERT #F VALUES (1,10,13,'НЗП_ЗНАЧЕНИЕ(''411'',13)')
INSERT #F VALUES (1,11,13,'НЗП_ЗНАЧЕНИЕ(''421'',13)')
INSERT #F VALUES (1,12,13,'НЗП_ЗНАЧЕНИЕ(''431'',13)')
INSERT #F VALUES (1,13,13,'НЗП_ЗНАЧЕНИЕ(''103'',13)')
INSERT #F VALUES (1,2,14,'НЗП_ЗНАЧЕНИЕ(''101'',14)')
INSERT #F VALUES (1,3,14,'НЗП_ЗНАЧЕНИЕ(''102'',14)')
INSERT #F VALUES (1,4,14,'НЗП_ЗНАЧЕНИЕ(''281'',14)')
INSERT #F VALUES (1,5,14,'НЗП_ЗНАЧЕНИЕ(''282'',14)')
INSERT #F VALUES (1,6,14,'НЗП_ЗНАЧЕНИЕ(''401'',14)')
INSERT #F VALUES (1,7,14,'НЗП_ЗНАЧЕНИЕ(''501'',14)')
INSERT #F VALUES (1,8,14,'НЗП_ЗНАЧЕНИЕ(''3013'',14)')
INSERT #F VALUES (1,9,14,'НЗП_ЗНАЧЕНИЕ(''3113'',14)')
INSERT #F VALUES (1,10,14,'НЗП_ЗНАЧЕНИЕ(''411'',14)')
INSERT #F VALUES (1,11,14,'НЗП_ЗНАЧЕНИЕ(''421'',14)')
INSERT #F VALUES (1,12,14,'НЗП_ЗНАЧЕНИЕ(''431'',14)')
INSERT #F VALUES (1,13,14,'НЗП_ЗНАЧЕНИЕ(''103'',14)')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 172
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,'т.1стр.01 =  т.1стр.02 +  т.1стр.03 +  т.1стр.04 +  т.1стр.06 +  т.1стр.07 +  т.1стр.08 +  т.1стр.10 +  т.1стр.11 +  т.1стр.12 +  т.1стр.13',1,3,1,'20130912','','','','0606049','20130601','','=',2,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 1
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,'','','','','','','','','','01','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','02','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','03','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','04','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','06','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','07','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','08','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','10','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,9,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','11','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,10,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','12','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,11,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','13','1',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) <> 11
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] = '451       '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'451','Республика Коми',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] = '606       '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'606','Заработная плата',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-02-27 10:52:20.363',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-02-27 10:52:20.363'
	BEGIN
		SELECT @vcMessage = 'Форма 0606049 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0606049 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-02-27 10:52:20.363. Обновление отклонено.'
	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. (апр  1 2014 12:07:49:577PM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 4fss (Расчетная ведомость по средствам ФСС РФ)
-- Дата ввода : 20130401
-- Дата окончания действия : 20131231
-- Версия : 2014-04-01 12:07:49.577
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

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] = '20130401'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-04-01 12:07:49.577',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,'20130401')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. 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','20131231',''
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_190313()','4FSS_090212.bas','','KirRepMakerMultiSheet.XLS','4FSS_190313.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.Табл.5. Выпл. за счёт средств Федерал. бюджета', @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,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,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, 'Р2.Табл.6. Несчастные случаи - база', @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,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,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.Табл.7. Несчастные случаи - расчёт', @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,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,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.Табл.8. Расходы по страхованию от несч. случ.', @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,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,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.Табл.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,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,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.Табл.10. Свед. по аттест. раб. мест и медосмотр', @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,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,16, @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 (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,11,1,1)
INSERT #R VALUES (2,11,3,1)
INSERT #R VALUES (3,11,4,1)
INSERT #R VALUES (4,11,5,1)
INSERT #R VALUES (5,11,6,1)
INSERT #R VALUES (6,11,7,1)
INSERT #R VALUES (7,11,8,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 (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 (6,13,7,1)
INSERT #R VALUES (7,13,8,1)
INSERT #R VALUES (8,13,9,1)
INSERT #R VALUES (9,13,10,1)
INSERT #R VALUES (10,13,11,1)
INSERT #R VALUES (11,13,12,1)
INSERT #R VALUES (12,13,13,1)
INSERT #R VALUES (13,13,14,1)
INSERT #R VALUES (14,13,15,1)
INSERT #R VALUES (15,13,16,1)
INSERT #R VALUES (16,13,17,1)
INSERT #R VALUES (17,13,18,1)
INSERT #R VALUES (18,13,19,1)
INSERT #R VALUES (19,13,20,1)
INSERT #R VALUES (20,13,21,1)
INSERT #R VALUES (21,13,22,1)
INSERT #R VALUES (22,13,23,1)
INSERT #R VALUES (23,13,24,1)
INSERT #R VALUES (24,13,25,1)
INSERT #R VALUES (25,13,26,1)
INSERT #R VALUES (26,13,27,1)
INSERT #R VALUES (27,13,28,1)
INSERT #R VALUES (28,13,29,1)
INSERT #R VALUES (29,13,30,1)
INSERT #R VALUES (30,13,31,1)
INSERT #R VALUES (31,13,32,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 (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 (1,16,1,1)
INSERT #R VALUES (2,16,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) <> 155
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,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,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,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,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,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 (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 (11,1,1,'Пособие по временной нетрудоспособности                                                                                                                                                                                                                   ')
INSERT #F VALUES (11,2,1,'Пособие по беременности и родам                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,3,1,'Ежемесячное пособие по уходу за ребенком, всего (стр. 4, 5)                                                                                                                                                                                               ')
INSERT #F VALUES (11,4,1,'в том числе: по уходу за первым ребенком                                                                                                                                                                                                                      ')
INSERT #F VALUES (11,5,1,'по уходу за вторым и 
последующими детьми                                                                                                                                                                                                                ')
INSERT #F VALUES (11,6,1,'Социальное пособие на погребение или возмещение стоимости гарантированного перечня услуг по погребению                                                                                                                                                    ')
INSERT #F VALUES (11,7,1,'ВСЕГО (строки 1 - 3, 6)                                                                                                                                                                                                                                   ')
INSERT #F VALUES (11,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (11,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (11,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (11,4,2,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (11,5,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (11,6,2,'6                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (11,7,2,'7                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (11,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (11,7,7,'ЗАПРЕТ()')
INSERT #F VALUES (11,7,10,'ЗАПРЕТ()')
INSERT #F VALUES (11,2,12,'ЗАПРЕТ()')
INSERT #F VALUES (11,3,12,'ЗАПРЕТ()')
INSERT #F VALUES (11,4,12,'ЗАПРЕТ()')
INSERT #F VALUES (11,5,12,'ЗАПРЕТ()')
INSERT #F VALUES (11,6,12,'ЗАПРЕТ()')
INSERT #F VALUES (11,2,13,'ЗАПРЕТ()')
INSERT #F VALUES (11,3,13,'ЗАПРЕТ()')
INSERT #F VALUES (11,4,13,'ЗАПРЕТ()')
INSERT #F VALUES (11,5,13,'ЗАПРЕТ()')
INSERT #F VALUES (11,6,13,'ЗАПРЕТ()')
INSERT #F VALUES (11,7,13,'ЗАПРЕТ()')
INSERT #F VALUES (11,2,14,'ЗАПРЕТ()')
INSERT #F VALUES (11,3,14,'ЗАПРЕТ()')
INSERT #F VALUES (11,4,14,'ЗАПРЕТ()')
INSERT #F VALUES (11,5,14,'ЗАПРЕТ()')
INSERT #F VALUES (11,6,14,'ЗАПРЕТ()')
INSERT #F VALUES (11,7,16,'ЗАПРЕТ()')
INSERT #F VALUES (11,3,18,'ЗАПРЕТ()')
INSERT #F VALUES (11,4,18,'ЗАПРЕТ()')
INSERT #F VALUES (11,5,18,'ЗАПРЕТ()')
INSERT #F VALUES (11,6,18,'ЗАПРЕТ()')
INSERT #F VALUES (11,3,19,'ЗАПРЕТ()')
INSERT #F VALUES (11,4,19,'ЗАПРЕТ()')
INSERT #F VALUES (11,5,19,'ЗАПРЕТ()')
INSERT #F VALUES (11,6,19,'ЗАПРЕТ()')
INSERT #F VALUES (11,7,19,'ЗАПРЕТ()')
INSERT #F VALUES (11,3,20,'ЗАПРЕТ()')
INSERT #F VALUES (11,4,20,'ЗАПРЕТ()')
INSERT #F VALUES (11,5,20,'ЗАПРЕТ()')
INSERT #F VALUES (11,6,20,'ЗАПРЕТ()')
INSERT #F VALUES (12,1,1,'Всего с начала расчетного  периода                                                                                                                                                                                                                        ')
INSERT #F VALUES (12,2,1,'    В том числе за последние три месяца отчетного периода                                                                                                                                                                                                 ')
INSERT #F VALUES (12,3,1,'       В том числе за 1 месяц                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,4,1,'       В том числе за 2 месяц                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,5,1,'       В том числе за 3 месяц                                                                                                                                                                                                                             ')
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,1,3,'4ФСС_РАЗДЕЛ1(''060103'',3)')
INSERT #F VALUES (12,3,3,'4ФСС_РАЗДЕЛ1(''060303'',3)')
INSERT #F VALUES (12,4,3,'4ФСС_РАЗДЕЛ1(''060403'',3)')
INSERT #F VALUES (12,5,3,'4ФСС_РАЗДЕЛ1(''060503'',3)')
INSERT #F VALUES (12,1,4,'4ФСС_РАЗДЕЛ1(''060104'',3)')
INSERT #F VALUES (12,3,4,'4ФСС_РАЗДЕЛ1(''060304'',3)')
INSERT #F VALUES (12,4,4,'4ФСС_РАЗДЕЛ1(''060404'',3)')
INSERT #F VALUES (12,5,4,'4ФСС_РАЗДЕЛ1(''060504'',3)')
INSERT #F VALUES (12,1,5,'4ФСС_РАЗДЕЛ1(''060105'',3)')
INSERT #F VALUES (12,3,5,'4ФСС_РАЗДЕЛ1(''060305'',3)')
INSERT #F VALUES (12,4,5,'4ФСС_РАЗДЕЛ1(''060405'',3)')
INSERT #F VALUES (12,5,5,'4ФСС_РАЗДЕЛ1(''060505'',3)')
INSERT #F VALUES (12,1,6,'4ФСС_СПРАВОЧНИК(''tax_rate'')')
INSERT #F VALUES (12,2,6,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,6,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,6,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,6,'ЗАПРЕТ()')
INSERT #F VALUES (12,1,7,'4ФСС_СПРАВОЧНИК(''discount'')')
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,1,8,'4ФСС_СПРАВОЧНИК(''raise_date'')')
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,1,9,'4ФСС_СПРАВОЧНИК(''raise_val'')')
INSERT #F VALUES (12,2,9,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,9,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,9,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,9,'ЗАПРЕТ()')
INSERT #F VALUES (12,1,10,'4ФСС_СПРАВОЧНИК(''tax_total'')')
INSERT #F VALUES (12,2,10,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,10,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,10,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,10,'ЗАПРЕТ()')
INSERT #F VALUES (13,1,1,'Задолженность за страхователем на начало расчетного периода                                                                                                                                                                                               ')
INSERT #F VALUES (13,2,1,'Начислено страховых взносов                                                                                                                                                                                                                               ')
INSERT #F VALUES (13,3,1,'на начало отчетного периода                                                                                                                                                                                                                               ')
INSERT #F VALUES (13,4,1,'за последние три месяца отчетного периода                                                                                                                                                                                                                 ')
INSERT #F VALUES (13,5,1,'          1 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,6,1,'          2 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,7,1,'          3 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,8,1,'Начислено взносов по результатам проверок                                                                                                                                                                                                                 ')
INSERT #F VALUES (13,9,1,'Не принято к зачету расходов территориальным органом Фонда за прошлые расчетные периоды                                                                                                                                                                   ')
INSERT #F VALUES (13,10,1,'Начислено взносов страхователем за прошлые расчетные периоды                                                                                                                                                                                              ')
INSERT #F VALUES (13,11,1,'Получено от территориального органа Фонда на банковский счет                                                                                                                                                                                              ')
INSERT #F VALUES (13,12,1,'Возврат сумм излишне уплаченных (взысканных) страховых взносов                                                                                                                                                                                            ')
INSERT #F VALUES (13,13,1,'Всего  (сумма строк 1+2+3+4+5+6+7)                                                                                                                                                                                                                        ')
INSERT #F VALUES (13,14,1,'Задолженность за территориальным органом Фонда на конец отчетного периода                                                                                                                                                                                 ')
INSERT #F VALUES (13,15,1,'Задолженность за территориальным органом Фонда на начало расчетного периода                                                                                                                                                                               ')
INSERT #F VALUES (13,16,1,'Расходы по обязательному социальному страхованию                                                                                                                                                                                                          ')
INSERT #F VALUES (13,17,1,'на начало отчетного периода                                                                                                                                                                                                                               ')
INSERT #F VALUES (13,18,1,'за последние три месяца отчетного периода                                                                                                                                                                                                                 ')
INSERT #F VALUES (13,19,1,'          1 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,20,1,'          2 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,21,1,'          3 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,22,1,'Уплачено страховых взносов                                                                                                                                                                                                                                ')
INSERT #F VALUES (13,23,1,'на начало отчетного периода                                                                                                                                                                                                                               ')
INSERT #F VALUES (13,24,1,'за последние три месяца отчетного периода дата, № платежного  поручения                                                                                                                                                                                   ')
INSERT #F VALUES (13,25,1,'          1 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,26,1,'          2 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,27,1,'          3 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,28,1,'Списанная сумма задолженности страхователя                                                                                                                                                                                                                ')
INSERT #F VALUES (13,29,1,'Всего (сумма строк 10+11+12+13                                                                                                                                                                                                                            ')
INSERT #F VALUES (13,30,1,'Задолженность за страхователем на конец отчетного периода                                                                                                                                                                                                 ')
INSERT #F VALUES (13,31,1,'           в том числе недоимка                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,3,2,'2_1                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (13,4,2,'2_2                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (13,5,2,'2_3                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (13,6,2,'2_4                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (13,7,2,'2_5                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (13,8,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,9,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,10,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,11,2,'6                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,12,2,'7                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,13,2,'8                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,14,2,'9                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,15,2,'10                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (13,16,2,'11                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (13,17,2,'11_1                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,18,2,'11_2                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,19,2,'11_3                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,20,2,'11_4                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,21,2,'11_5                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,22,2,'12                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (13,23,2,'12_1                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,24,2,'12_2                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,25,2,'12_3                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,26,2,'12_4                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,27,2,'12_5                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,28,2,'13                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (13,29,2,'14                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (13,30,2,'15                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (13,31,2,'16                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (13,1,3,'КТСН("_.303.06","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (13,3,3,'4ФСС_РАЗДЕЛ1(''1021'',3)')
INSERT #F VALUES (13,5,3,'4ФСС_РАЗДЕЛ1(''1023'',3)')
INSERT #F VALUES (13,6,3,'4ФСС_РАЗДЕЛ1(''1024'',3)')
INSERT #F VALUES (13,7,3,'4ФСС_РАЗДЕЛ1(''1025'',3)')
INSERT #F VALUES (13,11,3,'АДТКТ("_.304.05:_.201.11:_.201.21:_.201.27","_.303.06")')
INSERT #F VALUES (13,17,3,'АДТКТ("_.303.06","_.302.13,"ДЛЯ ДАТА>=''01.01'' И ДАТА<КВАРТАЛ")')
INSERT #F VALUES (13,19,3,'АДТКТ("_.303.06","_.302.13,"ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (13,20,3,'АДТКТ("_.303.06","_.302.13","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (13,21,3,'АДТКТ("_.303.06","_.302.13","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (13,23,3,'АДТКТ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА>=''01.01'' И ДАТА<КВАРТАЛ")')
INSERT #F VALUES (13,25,3,'АДТКТ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (13,26,3,'АДТКТ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (13,27,3,'АДТКТ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (13,30,3,'КТСК("_.303.06")')
INSERT #F VALUES (13,1,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,2,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,3,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,4,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,6,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,8,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,9,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,10,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,11,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,12,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,13,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,14,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,15,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,16,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,17,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,18,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,19,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,20,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,21,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,22,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,23,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,24,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,25,4,'НОМ_ПЛАТЕЖ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (13,26,4,'НОМ_ПЛАТЕЖ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (13,27,4,'НОМ_ПЛАТЕЖ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (13,28,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,29,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,30,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,31,4,'ЗАПРЕТ()')
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,'      из них: по внешнему совместительству                                                                                                                                                                                                                ')
INSERT #F VALUES (14,6,1,'      пострадавшим в другой организации                                                                                                                                                                                                                       ')
INSERT #F VALUES (14,7,1,'Оплата отпуска для санаторно-курортного лечения застрахованным (сверх ежегодного оплачиваемого отпуска, установленного законодательством Российской Федерации)                                                                                            ')
INSERT #F VALUES (14,8,1,'      из них: пострадавшим в другой организации                                                                                                                                                                                                               ')
INSERT #F VALUES (14,9,1,'Финансирование предупредительных мер по сокращению производственного травматизма и профзаболеваний                                                                                                                                                        ')
INSERT #F VALUES (14,10,1,'Всего расходов (сумма строк 1, 4, 7, 9)                                                                                                                                                                                                                   ')
INSERT #F VALUES (14,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,3,2,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (14,4,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,5,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,6,2,'6                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (14,7,2,'7                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,8,2,'8                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (14,9,2,'9                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,10,2,'10                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (14,1,3,'4ФСС_РАЗДЕЛ1(''1101'',6)')
INSERT #F VALUES (14,2,3,'4ФСС_РАЗДЕЛ1(''1102'',6)')
INSERT #F VALUES (14,4,3,'4ФСС_РАЗДЕЛ1(''1104'',6)')
INSERT #F VALUES (14,5,3,'4ФСС_РАЗДЕЛ1(''1105'',6)')
INSERT #F VALUES (14,7,3,'4ФСС_РАЗДЕЛ1(''1107'',6)')
INSERT #F VALUES (14,9,3,'ЗАПРЕТ()')
INSERT #F VALUES (14,10,3,'ЗАПРЕТ()')
INSERT #F VALUES (14,1,4,'4ФСС_РАЗДЕЛ1(''1101'',3)')
INSERT #F VALUES (14,2,4,'4ФСС_РАЗДЕЛ1(''1102'',3)')
INSERT #F VALUES (14,4,4,'4ФСС_РАЗДЕЛ1(''1104'',3)')
INSERT #F VALUES (14,5,4,'4ФСС_РАЗДЕЛ1(''1105'',3)')
INSERT #F VALUES (14,7,4,'4ФСС_РАЗДЕЛ1(''1107'',3)')
INSERT #F VALUES (15,1,1,'По несчастным случаям                                                                                                                                                                                                                                     ')
INSERT #F VALUES (15,2,1,'      из них: со смертельным исходом                                                                                                                                                                                                                      ')
INSERT #F VALUES (15,3,1,'По профессиональным заболеваниям                                                                                                                                                                                                                          ')
INSERT #F VALUES (15,4,1,'ВСЕГО пострадавших (сумма строк 1, 3)                                                                                                                                                                                                                     ')
INSERT #F VALUES (15,5,1,'в том числе пострадавших (застрахованных) по случаям, закончившимся только временной нетрудоспособностью                                                                                                                                                  ')
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 (16,1,1,'Аттестация рабочих мест по условиям труда                                                                                                                                                                                                                     ')
INSERT #F VALUES (16,2,1,'Проведение обязательных предварительных и периодических медицинских осмотров (обследований) работников                                                                                                                                                        ')
INSERT #F VALUES (16,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (16,2,2,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (16,2,3,'ЗАПРЕТ()')
INSERT #F VALUES (16,2,4,'ЗАПРЕТ()')
INSERT #F VALUES (16,2,6,'ЗАПРЕТ()')
INSERT #F VALUES (16,2,7,'ЗАПРЕТ()')
INSERT #F VALUES (16,1,8,'ЗАПРЕТ()')
INSERT #F VALUES (16,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) <> 589
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,'20130621','','','','4fss','20130401','','=',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,'20130621','','','','4fss','20130401','','=',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,'20130621','','','','4fss','20130401','','=',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,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(5,NULL,0,NULL,5,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,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(6,NULL,0,NULL,6,7,0,0,0,'т.2стр.15_2гр.3 =  т.2стр.15_3гр.3 +  т.2стр.15_4гр.3 +  т.2стр.15_5гр.3',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(7,NULL,0,NULL,7,7,0,0,0,'т.2стр.16_2гр.3 =  т.2стр.16_3гр.3 +  т.2стр.16_4гр.3 +  т.2стр.16_5гр.3',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(8,NULL,0,NULL,8,7,0,0,0,'т.2стр.18гр.3 =  т.2стр.12гр.3 +  т.2стр.15гр.3 +  т.2стр.16гр.3 +  т.2стр.17гр.3',1,2,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(9,NULL,0,NULL,9,7,0,0,0,'т.2стр.15гр.3 =  т.3стр.12гр.4',0,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(10,NULL,0,NULL,10,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,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(11,NULL,0,NULL,11,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,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(12,NULL,0,NULL,12,7,0,0,0,'т.4стр.4гр.3 =  т.4стр.1гр.3 -  т.4стр.2гр.3 -  т.4стр.3гр.3',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(13,NULL,0,NULL,13,7,0,0,0,'т.4стр.4гр.4 =  т.4стр.1гр.4 -  т.4стр.2гр.4 -  т.4стр.3гр.4',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(14,NULL,0,NULL,14,7,0,0,0,'т.4стр.4гр.5 =  т.4стр.1гр.5 -  т.4стр.2гр.5 -  т.4стр.3гр.5',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(15,NULL,0,NULL,15,7,0,0,0,'т.4стр.4гр.6 =  т.4стр.1гр.6 -  т.4стр.2гр.6 -  т.4стр.3гр.6',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(16,NULL,0,NULL,16,7,0,0,0,'т.6стр.1гр.3 =  т.6стр.1гр.6',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(17,NULL,0,NULL,17,7,0,0,0,'т.6стр.2гр.3 =  т.6стр.2гр.6',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(18,NULL,0,NULL,18,7,0,0,0,'т.6стр.3гр.3 =  т.6стр.2гр.3 /  т.6стр.1гр.3 *  100',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(19,NULL,0,NULL,19,7,0,0,0,'т.6стр.3гр.4 =  т.6стр.2гр.4 /  т.6стр.1гр.4 *  100',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(20,NULL,0,NULL,20,7,0,0,0,'т.6стр.3гр.5 =  т.6стр.2гр.5 /  т.6стр.1гр.5 *  100',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(21,NULL,0,NULL,21,7,0,0,0,'т.6стр.3гр.6 =  т.6стр.2гр.6 /  т.6стр.1гр.6 *  100',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(22,NULL,0,NULL,22,7,0,0,0,'т.7стр.1гр.3 =  т.7стр.1гр.6',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(23,NULL,0,NULL,23,7,0,0,0,'т.7стр.2гр.3 =  т.7стр.2гр.6',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(24,NULL,0,NULL,24,7,0,0,0,'т.7стр.3гр.3 =  т.7стр.2гр.3 /  т.7стр.1гр.3 *  100',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(25,NULL,0,NULL,25,7,0,0,0,'т.7стр.3гр.4 =  т.7стр.2гр.4 /  т.7стр.1гр.4 *  100',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(26,NULL,0,NULL,26,7,0,0,0,'т.7стр.3гр.5 =  т.7стр.2гр.5 /  т.7стр.1гр.5 *  100',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(27,NULL,0,NULL,27,7,0,0,0,'т.7стр.3гр.6 =  т.7стр.2гр.6 /  т.7стр.1гр.6 *  100',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(28,NULL,0,NULL,28,7,0,0,0,'т.7стр.6гр.3 =  т.7стр.5гр.3 /  т.7стр.4гр.3 *  100',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(29,NULL,0,NULL,29,7,0,0,0,'т.7стр.6гр.4 =  т.7стр.5гр.4 /  т.7стр.4гр.4 *  100',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(30,NULL,0,NULL,30,7,0,0,0,'т.7стр.6гр.5 =  т.7стр.5гр.5 /  т.7стр.4гр.5 *  100',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(31,NULL,0,NULL,31,7,0,0,0,'т.7стр.6гр.6 =  т.7стр.5гр.6 /  т.7стр.4гр.6 *  100',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(32,NULL,0,NULL,32,7,0,0,0,'т.8стр.4гр.3 =  т.8стр.3гр.3 /  т.8стр.2гр.3 *  100',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(33,NULL,0,NULL,33,7,0,0,0,'т.11стр.1гр.5 =  т.3стр.1гр.5',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(34,NULL,0,NULL,34,7,0,0,0,'т.11стр.2гр.5 =  т.3стр.3гр.5',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(35,NULL,0,NULL,35,7,0,0,0,'т.11стр.4гр.5 =  т.3стр.8гр.5',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(36,NULL,0,NULL,36,7,0,0,0,'т.11стр.5гр.5 =  т.3стр.9гр.5',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(37,NULL,0,NULL,37,7,0,0,0,'т.11стр.3гр.5 =  т.11стр.4гр.5 +  т.11стр.5гр.5',1,1,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(38,NULL,0,NULL,38,7,0,0,0,'т.11стр.6гр.5 =  т.3стр.11гр.5',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(39,NULL,0,NULL,39,7,0,0,0,'т.11стр.7гр.3 =  т.11стр.1гр.3 +  т.11стр.2гр.3 +  т.11стр.3гр.3 +  т.11стр.6гр.3',1,2,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(40,NULL,0,NULL,40,7,0,0,0,'т.11стр.7гр.5 =  т.11стр.1гр.5 +  т.11стр.2гр.5 +  т.11стр.3гр.5 +  т.11стр.6гр.5',1,2,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(41,NULL,0,NULL,41,7,0,0,0,'т.11стр.7гр.6 =  т.11стр.1гр.6 +  т.11стр.2гр.6 +  т.11стр.3гр.6 +  т.11стр.6гр.6',1,2,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(42,NULL,0,NULL,42,7,0,0,0,'т.11стр.7гр.8 =  т.11стр.1гр.8 +  т.11стр.2гр.8 +  т.11стр.3гр.8 +  т.11стр.6гр.8',1,2,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(43,NULL,0,NULL,43,7,0,0,0,'т.11стр.7гр.9 =  т.11стр.1гр.9 +  т.11стр.2гр.9 +  т.11стр.3гр.9 +  т.11стр.6гр.9',1,2,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(44,NULL,0,NULL,44,7,0,0,0,'т.11стр.7гр.11 =  т.11стр.1гр.11 +  т.11стр.2гр.11 +  т.11стр.3гр.11 +  т.11стр.6гр.11',1,2,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(45,NULL,0,NULL,45,7,0,0,0,'т.11стр.7гр.12 =  т.11стр.1гр.12 +  т.11стр.2гр.12 +  т.11стр.3гр.12 +  т.11стр.6гр.12',1,2,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(46,NULL,0,NULL,46,7,0,0,0,'т.11стр.7гр.14 =  т.11стр.1гр.14 +  т.11стр.2гр.14 +  т.11стр.3гр.14 +  т.11стр.6гр.14',1,2,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(47,NULL,0,NULL,47,7,0,0,0,'т.11стр.7гр.15 =  т.11стр.1гр.15 +  т.11стр.2гр.15 +  т.11стр.3гр.15 +  т.11стр.6гр.15',1,2,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(48,NULL,0,NULL,48,7,0,0,0,'т.11стр.7гр.17 =  т.11стр.1гр.17 +  т.11стр.2гр.17 +  т.11стр.3гр.17 +  т.11стр.6гр.17',1,2,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(49,NULL,0,NULL,49,7,0,0,0,'т.11стр.7гр.18 =  т.11стр.1гр.18 +  т.11стр.2гр.18 +  т.11стр.3гр.18 +  т.11стр.6гр.18',1,2,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(50,NULL,0,NULL,50,7,0,0,0,'т.11стр.7гр.20 =  т.11стр.1гр.20 +  т.11стр.2гр.20 +  т.11стр.3гр.20 +  т.11стр.6гр.20',1,2,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(51,NULL,0,NULL,51,7,0,0,0,'т.12стр.2гр.3 =  т.12стр.3гр.3 +  т.12стр.4гр.3 +  т.12стр.5гр.3',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(52,NULL,0,NULL,52,7,0,0,0,'т.12стр.2гр.4 =  т.12стр.3гр.4 +  т.12стр.4гр.4 +  т.12стр.5гр.4',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(53,NULL,0,NULL,53,7,0,0,0,'т.12стр.2гр.5 =  т.12стр.3гр.5 +  т.12стр.4гр.5 +  т.12стр.5гр.5',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(54,NULL,0,NULL,54,7,0,0,0,'т.13стр.2_2гр.3 =  т.13стр.2_3гр.3 +  т.13стр.2_4гр.3 +  т.13стр.2_5гр.3',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(55,NULL,0,NULL,55,7,0,0,0,'т.13стр.8гр.3 =  т.13стр.1гр.3 +  т.13стр.2гр.3 +  т.13стр.3гр.3 +  т.13стр.4гр.3 +  т.13стр.5гр.3 +  т.13стр.6гр.3 +  т.13стр.7гр.3',1,2,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(56,NULL,0,NULL,56,7,0,0,0,'т.13стр.11_2гр.3 =  т.13стр.11_3гр.3 +  т.13стр.11_4гр.3 +  т.13стр.11_5гр.3',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(57,NULL,0,NULL,57,7,0,0,0,'т.13стр.12_2гр.3 =  т.13стр.12_3гр.3 +  т.13стр.12_4гр.3 +  т.13стр.12_5гр.3',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(58,NULL,0,NULL,58,7,0,0,0,'т.13стр.14гр.3 =  т.13стр.10гр.3 +  т.13стр.11гр.3 +  т.13стр.12гр.3 +  т.13стр.13гр.3',1,2,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(59,NULL,0,NULL,59,7,0,0,0,'т.14стр.10гр.4 =  т.14стр.1гр.4 +  т.14стр.4гр.4 +  т.14стр.7гр.4 +  т.14стр.9гр.4',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(60,NULL,0,NULL,60,7,0,0,0,'т.15стр.4гр.3 =  т.15стр.1гр.3 +  т.15стр.3гр.3',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(61,NULL,0,NULL,61,7,0,0,0,'т.13стр.2гр.3 =  т.13стр.2_1гр.3 +  т.13стр.2_2гр.3',1,1,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(62,NULL,0,NULL,62,7,0,0,0,'т.13стр.11гр.3 =  т.13стр.11_1гр.3 +  т.13стр.11_2гр.3',1,1,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(63,NULL,0,NULL,63,7,0,0,0,'т.13стр.12гр.3 =  т.13стр.12_1гр.3 +  т.13стр.12_2гр.3',1,1,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(64,NULL,0,NULL,64,7,0,0,0,'т.13гр.3 =  -  т.13гр.3',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(65,NULL,0,NULL,65,7,0,0,0,'т.13гр.3 =  -  т.13гр.3',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(66,NULL,0,NULL,66,7,0,0,0,'т.13гр.3 =  т.13гр.3 -  т.13гр.3',1,1,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(67,NULL,0,NULL,67,7,0,0,0,'т.13гр.3 =  т.13гр.3 -  т.13гр.3',1,1,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(68,NULL,0,NULL,73,7,0,0,0,'т.2стр.2гр.3 =  т.2стр.2_1гр.3 +  т.2стр.2_2гр.3',1,1,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(69,NULL,0,NULL,74,7,0,0,0,'т.2стр.3гр.3 =  т.2стр.3_1гр.3 +  т.2стр.3_2гр.3',1,1,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(70,NULL,0,NULL,75,7,0,0,0,'т.2стр.5гр.3 =  т.2стр.5_1гр.3 +  т.2стр.5_2гр.3',1,1,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(71,NULL,0,NULL,76,7,0,0,0,'т.2стр.6гр.3 =  т.2стр.6_1гр.3 +  т.2стр.6_2гр.3',1,1,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(72,NULL,0,NULL,77,7,0,0,0,'т.2стр.15гр.3 =  т.2стр.15_1гр.3 +  т.2стр.15_2гр.3',1,1,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(73,NULL,0,NULL,78,7,0,0,0,'т.2стр.16гр.3 =  т.2стр.16_1гр.3 +  т.2стр.16_2гр.3',1,1,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(74,NULL,0,NULL,79,7,0,0,0,'Проверки =  0',0,100,1,'20130621','','','','4fss','20130401','','=',9,'','')
INSERT #A VALUES(75,NULL,0,NULL,80,7,0,0,0,'т.3стр.7гр.2 =  т.3стр.8гр.2 +  т.3стр.9гр.2',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(76,NULL,0,NULL,81,7,0,0,0,'т.3стр.7гр.3 =  т.3стр.8гр.3 +  т.3стр.9гр.3',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(77,NULL,0,NULL,82,7,0,0,0,'т.3стр.7гр.4 =  т.3стр.8гр.4 +  т.3стр.9гр.4',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(78,NULL,0,NULL,83,7,0,0,0,'т.3стр.7гр.5 =  т.3стр.8гр.5 +  т.3стр.9гр.5',1,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(79,NULL,0,NULL,84,7,0,0,0,'т.1стр.2гр.3 <=  т.1стр.1гр.3',0,0,1,'20130621','','','','4fss','20130401','','<=',1,'','')
INSERT #A VALUES(80,NULL,0,NULL,85,7,0,0,0,'т.1стр.3гр.3 <=  т.1стр.1гр.3',0,0,1,'20130621','','','','4fss','20130401','','<=',1,'','')
INSERT #A VALUES(81,NULL,0,NULL,86,7,0,0,0,'т.1стр.4гр.3 <=  т.1стр.1гр.3',0,0,1,'20130621','','','','4fss','20130401','','<=',1,'','')
INSERT #A VALUES(82,NULL,0,NULL,87,7,0,0,0,'т.3стр.2гр.2 <=  т.3стр.1гр.2',0,0,1,'20130621','','','','4fss','20130401','','<=',1,'','')
INSERT #A VALUES(83,NULL,0,NULL,88,7,0,0,0,'т.3стр.2гр.3 <=  т.3стр.1гр.3',0,0,1,'20130621','','','','4fss','20130401','','<=',1,'','')
INSERT #A VALUES(84,NULL,0,NULL,89,7,0,0,0,'т.3стр.2гр.4 <=  т.3стр.1гр.4',0,0,1,'20130621','','','','4fss','20130401','','<=',1,'','')
INSERT #A VALUES(85,NULL,0,NULL,90,7,0,0,0,'т.3стр.2гр.5 <=  т.3стр.1гр.5',0,0,1,'20130621','','','','4fss','20130401','','<=',1,'','')
INSERT #A VALUES(86,NULL,0,NULL,91,7,0,0,0,'т.3стр.4гр.3 <=  т.3стр.3гр.3',0,0,1,'20130621','','','','4fss','20130401','','<=',1,'','')
INSERT #A VALUES(87,NULL,0,NULL,92,7,0,0,0,'т.3стр.4гр.4 <=  т.3стр.3гр.4',0,0,1,'20130621','','','','4fss','20130401','','<=',1,'','')
INSERT #A VALUES(88,NULL,0,NULL,93,7,0,0,0,'т.3стр.4гр.5 <=  т.3стр.3гр.5',0,0,1,'20130621','','','','4fss','20130401','','<=',1,'','')
INSERT #A VALUES(89,NULL,0,NULL,94,7,0,0,0,'т.4стр.1гр.3 >=  т.4стр.1гр.4 +  т.4стр.1гр.5 +  т.4стр.1гр.6',0,0,1,'20130621','','','','4fss','20130401','','>=',1,'','')
INSERT #A VALUES(90,NULL,0,NULL,95,7,0,0,0,'т.4стр.2гр.3 >=  т.4стр.2гр.4 +  т.4стр.2гр.5 +  т.4стр.2гр.6',0,0,1,'20130621','','','','4fss','20130401','','>=',1,'','')
INSERT #A VALUES(91,NULL,0,NULL,96,7,0,0,0,'т.4стр.3гр.3 >=  т.4стр.3гр.4 +  т.4стр.3гр.5 +  т.4стр.3гр.6',0,0,1,'20130621','','','','4fss','20130401','','>=',1,'','')
INSERT #A VALUES(92,NULL,0,NULL,97,7,0,0,0,'т.4стр.4гр.3 >=  т.4стр.4гр.4 +  т.4стр.4гр.5 +  т.4стр.4гр.6',0,0,1,'20130621','','','','4fss','20130401','','>=',1,'','')
INSERT #A VALUES(93,NULL,0,NULL,98,7,0,0,0,'т.4стр.5гр.3 >=  т.4стр.5гр.4 +  т.4стр.5гр.5 +  т.4стр.5гр.6',0,0,1,'20130621','','','','4fss','20130401','','>=',1,'','')
INSERT #A VALUES(94,NULL,0,NULL,99,7,0,0,0,'т.4стр.5гр.3 <=  т.4стр.4гр.3',0,0,1,'20130621','','','','4fss','20130401','','<=',1,'','')
INSERT #A VALUES(95,NULL,0,NULL,100,7,0,0,0,'т.4стр.5гр.4 <=  т.4стр.4гр.4',0,0,1,'20130621','','','','4fss','20130401','','<=',1,'','')
INSERT #A VALUES(96,NULL,0,NULL,101,7,0,0,0,'т.4стр.5гр.5 <=  т.4стр.4гр.5',0,0,1,'20130621','','','','4fss','20130401','','<=',1,'','')
INSERT #A VALUES(97,NULL,0,NULL,102,7,0,0,0,'т.4стр.5гр.6 <=  т.4стр.4гр.6',0,0,1,'20130621','','','','4fss','20130401','','<=',1,'','')
INSERT #A VALUES(98,NULL,0,NULL,103,7,0,0,0,'т.12стр.1гр.4 <=  т.12стр.1гр.3',0,0,1,'20130621','','','','4fss','20130401','','<=',1,'','')
INSERT #A VALUES(99,NULL,0,NULL,104,7,0,0,0,'т.13стр.16гр.3 <=  т.13стр.15гр.3',0,0,1,'20130621','','','','4fss','20130401','','<=',1,'','')
INSERT #A VALUES(100,NULL,0,NULL,105,7,0,0,0,'т.13стр.11гр.3 =  т.14стр.10гр.4',0,0,1,'20130621','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(101,NULL,0,NULL,106,7,0,0,0,'т.14стр.1гр.3 >=  т.14стр.2гр.3 +  т.14стр.3гр.3',0,0,1,'20130621','','','','4fss','20130401','','>=',1,'','')
INSERT #A VALUES(102,NULL,0,NULL,107,7,0,0,0,'т.14стр.1гр.4 >=  т.14стр.2гр.4 +  т.14стр.3гр.4',0,0,1,'20130621','','','','4fss','20130401','','>=',1,'','')
INSERT #A VALUES(103,NULL,0,NULL,108,7,0,0,0,'т.14стр.4гр.3 >=  т.14стр.5гр.3 +  т.14стр.6гр.3',0,0,1,'20130621','','','','4fss','20130401','','>=',1,'','')
INSERT #A VALUES(104,NULL,0,NULL,109,7,0,0,0,'т.14стр.4гр.4 >=  т.14стр.5гр.4 +  т.14стр.6гр.4',0,0,1,'20130621','','','','4fss','20130401','','>=',1,'','')
INSERT #A VALUES(105,NULL,0,NULL,110,7,0,0,0,'т.14стр.7гр.3 >=  т.14стр.8гр.3',0,0,1,'20130621','','','','4fss','20130401','','>=',1,'','')
INSERT #A VALUES(106,NULL,0,NULL,111,7,0,0,0,'т.14стр.7гр.4 >=  т.14стр.8гр.4',0,0,1,'20130621','','','','4fss','20130401','','>=',1,'','')
INSERT #A VALUES(107,NULL,0,NULL,112,7,0,0,0,'т.8стр.4гр.4 =  т.8стр.3гр.4 /  т.8стр.2гр.4 *  100',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(108,NULL,0,NULL,113,7,0,0,0,'т.9стр.3гр.3 =  т.9стр.2гр.3 /  т.9стр.1гр.3 *  100',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(109,NULL,0,NULL,114,7,0,0,0,'т.10стр.5гр.3 =  т.10стр.4гр.3 +  т.10стр.3гр.3 +  т.10стр.2гр.3 /  т.10стр.1гр.3 *  100',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(110,NULL,0,NULL,115,7,0,0,0,'т.10стр.5гр.4 =  т.10стр.4гр.4 +  т.10стр.3гр.4 +  т.10стр.2гр.4 /  т.10стр.1гр.4 *  100',1,0,1,'20130621','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(111,NULL,0,NULL,125,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,'20140325','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(112,NULL,0,NULL,126,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,'20140325','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(113,NULL,0,NULL,152,7,0,0,0,'т.11стр.3гр.5 =  т.11стр.4гр.5 +  т.11стр.5гр.5',1,1,1,'20140325','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(114,NULL,0,NULL,176,7,0,0,0,'т.13стр.2гр.3 =  т.13стр.2_1гр.3 +  т.13стр.2_2гр.3',1,1,1,'20140325','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(115,NULL,0,NULL,177,7,0,0,0,'т.13стр.11гр.3 =  т.13стр.11_1гр.3 +  т.13стр.11_2гр.3',1,1,1,'20140325','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(116,NULL,0,NULL,178,7,0,0,0,'т.13стр.12гр.3 =  т.13стр.12_1гр.3 +  т.13стр.12_2гр.3',1,1,1,'20140325','','','','4fss','20130401','','=',1,'','')
INSERT #A VALUES(117,NULL,0,NULL,181,7,0,0,0,'т.13гр.3 =  т.13гр.3 -  т.13гр.3',1,1,1,'20140325','','','','4fss','20130401','','=',0,'','')
INSERT #A VALUES(118,NULL,0,NULL,182,7,0,0,0,'т.13гр.3 =  т.13гр.3 -  т.13гр.3',1,1,1,'20140325','','','','4fss','20130401','','=',0,'','')
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','8','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(5,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','18','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(8,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','17','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(9,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','12','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','12','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(10,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','7','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','10','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','12','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(11,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','6','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','7','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','10','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(12,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(13,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(14,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(15,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(16,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','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(18,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(18,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(19,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(20,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','6',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,'','','','','','','','','6','3','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(21,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','6',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,'','','','','','','','','3','1','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(22,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','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(24,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(24,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','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','3','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(25,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','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','3','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(26,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','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','3','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(27,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','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','6','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(28,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','7',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,'','','','','','','','','4','6','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(29,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(30,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','6','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(31,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(32,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(33,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(34,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(35,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(36,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(37,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(38,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(39,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(40,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(41,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(42,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(43,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(44,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(45,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(46,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(47,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(48,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(49,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(50,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(51,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(52,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(53,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(54,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_3','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_4','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_5','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','8','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(55,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_2','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(56,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_3','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_4','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_5','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_2','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(57,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_3','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_4','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_5','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','14','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(58,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','10','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','13','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','10','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(59,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','7','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','9','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','15',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(60,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(61,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_1','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(62,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_1','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_2','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(63,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_1','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_2','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(64,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(65,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(65,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(66,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''1'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(66,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,3,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''15'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(67,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,3,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(68,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(68,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(68,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(69,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(69,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(69,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(70,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(70,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(70,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(71,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(71,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(71,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(72,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(73,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(74,1,2,'+',NULL,NULL,NULL,NULL,0,0,'SA_4FSS_EXPORT_TEST(0)','Проверки','','','','','','','','','',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,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(75,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(75,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','7','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(76,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','7','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(77,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','7','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(78,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(79,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(80,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(81,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(82,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(82,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(83,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(83,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(84,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(84,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(85,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(85,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(86,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(86,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(87,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(87,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(88,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(88,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(89,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(90,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(91,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(92,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(92,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(92,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(92,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(93,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(93,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(93,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(93,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(94,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(95,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(96,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(97,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(97,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(98,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(98,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(99,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(99,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(100,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(100,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','10','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(101,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(101,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(101,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(102,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(103,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(104,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','6','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(105,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','8','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','7','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(106,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','8','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(107,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','8',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','3','9',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(108,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','9',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,'','','','','','','','','3','5','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(109,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,5,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,6,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,'','','','','','','','','4','5','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(110,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,5,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,6,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,'','','','','','','','','5','12','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(111,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','7','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','10','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','12','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(112,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','6','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','7','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','10','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(113,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(114,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_1','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(115,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_1','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_2','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(116,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_1','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_2','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''1'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(117,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,3,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(118,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''15'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(118,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(118,3,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','13',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-04-01 12:07:49.577',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-01 12:07:49.577'
	BEGIN
		SELECT @vcMessage = 'Форма 4fss с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 4fss с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-04-01 12:07:49.577. Обновление отклонено.'
	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. (апр  5 2014  8:15:05:560PM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 4fss (Расчетная ведомость по средствам ФСС РФ)
-- Дата ввода : 20140101
-- Дата окончания действия :
-- Версия : 2014-04-05 20:15:05.560
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

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-04-05 20:15:05.560',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,'20140401','','','','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гр.3',0,0,1,'20140401','','','','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,'20140401','','','','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,94,7,0,0,0,'т.2стр.12гр.4 =  т.2стр.16_1гр.3 +  т.2стр.16_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(95,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(96,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(97,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(98,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(99,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(100,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(101,NULL,0,NULL,101,7,0,0,0,'т.14гр.3 =  т.14гр.3 -  т.14гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(102,NULL,0,NULL,102,7,0,0,0,'т.14гр.3 =  т.14гр.3 -  т.14гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(103,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(104,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(105,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(106,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(107,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(108,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(109,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(110,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(111,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(112,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(113,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(114,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(115,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(116,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(117,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(118,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(119,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) <> 119
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,'','','','','','','','','4','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,'','','','','','','','','4','12','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(94,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','12','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(95,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','7','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','10','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','12','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(96,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','6','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','7','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','10','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(97,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(97,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(97,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(98,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(98,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(98,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(99,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(99,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(99,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(100,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(100,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(100,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(101,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(101,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(101,3,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,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(102,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,3,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','8','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(103,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','18','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(104,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','17','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(105,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(106,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(107,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(108,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(109,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(110,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(111,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(112,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(113,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(114,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(115,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(116,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','8','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(117,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(118,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','14','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(118,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','10','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(118,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(118,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(118,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','13','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(119,1,2,'+',NULL,NULL,NULL,NULL,0,0,'SA_4FSS_EXPORT_TEST(0)','Проверки','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(119,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) <> 427
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-04-05 20:15:05.560',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-05 20:15:05.560'
	BEGIN
		SELECT @vcMessage = 'Форма 4fss с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 4fss с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-04-05 20:15:05.560. Обновление отклонено.'
	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. (мар  5 2014  5:12:37:633PM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : AV_ASS (Налоговая декларация по налогу на имущество организаций)
-- Дата ввода : 20080101
-- Дата окончания действия : 20111230
-- Версия : 2014-03-05 17:12:37.633
-- Параметры выгрузки :
-- только обновить  REPORT_FORMS              : да

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] = 'AV_ASS' AND [START_DATE] = '20080101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-03-05 17:12:37.633',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)
END -- проверка признака остановки в #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


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Обновление только REPORT_FORMS.
UPDATE dbo.[REPORT_FORMS]
SET [NAME]                = 'Налоговая декларация по налогу на имущество организаций',
    [ExportCode]          = '          ',
    [START_DATE]          = '20080101',
    [END_DATE]            = '20111230',
    [PERIODIC]            = 1,
    [ISSVOD]              = 1,
    [ISEXPORTED]          = 1,
    [ISUSERFORM]          = 0,
    [IsKonsolid]          = 0,
    [IS_AUTOFILL]         = 0,
    [PRINT_OBJECT_METHOD] = 'SvodPrint_ass_bal()',
    [QUERY_ADD_MODULE]    = 'KirRepF_AV_ASS_K.bas#KirRepF_AV_ASS_F.bas',
    [QUERY_BEFORE]        = '',
    [QUERY_REPMAKER]      = 'KirRepMakerMultiSheet.xls',
    [QUERY_REPORT]        = 'F1152001_K.XLT#F1152001_F.XLT',
    [QUERY_REPORT_PATH]   = '',
    [DECRIPT_PROC]        = '',
    [EXPORT_PROC]         = 'i_report_export_nalog',
    [IsRemoteAccess]      = 0,
    [PARAM_EXPORT]        = NULL,
    [PARAM_IMPORT]        = NULL,
    [OBJECT]              = NULL,
    [ATRIBUTS]            = '',
    [SvodProc]            = NULL,
    [COMMENT]             = NULL,
    [PRINT_OBJECT_METHOD_NEW] = NULL,
    [QUERY_BEFORE_PRINT_NEW]  = '',
    [QUERY_REPORT_NEW]        = '',
    [IS_CALC]        = 1
WHERE [LINK_FORM] = @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2014-03-05 17:12:37.633',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-03-05 17:12:37.633'
	BEGIN
		SELECT @vcMessage = 'Форма AV_ASS с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма AV_ASS с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-03-05 17:12:37.633. Обновление отклонено.'
	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  3:14:15:657PM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : AV_IMU (Налоговый расчет по авансовому платежу по налогу на имущество организаций)
-- Дата ввода : 20140101
-- Дата окончания действия :
-- Версия : 2014-03-03 15:14:15.653
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

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] = 'AV_IMU' AND [START_DATE] = '20140101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-03-03 15:14:15.653',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_' + 'AV_IMU',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 = 'AV_IMU'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20140101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. 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,0,1,1,18186,'i_report_export_nalog',0,0,'19000101',NULL,'Приказ ФНС РФ от 24 ноября 2011 г. N ММВ-7-11/895  (изм. 05.11.2013 N ММВ-7-11/478@)'
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, '','nd_imu_f1152026_2013.BAS','print_nd_imu_2013 (.T.)','KirRepMakerMultiSheet.xls','AV_IMU_F1152028_2014.XLT','',NULL,'i_report_export_nalog',0,NULL,NULL,NULL,'          ','',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, 'Раздел 1', @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,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_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,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, 3,'Код по ОКТМО',@iLINK_TABLE,1,1,3,0,11,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,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, 5,'К уменьшению',@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,'Код по месту нахождения (учета)',@iLINK_TABLE,1,1,6,0,3,1,'DICTIONARY_PLACE_ND_IMU','COL6','CODE',NULL,4,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #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,1,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,1,8,0,2,1,'DICTIONARY_TAX_PERIOD','COL8','CODE',NULL,4,NULL,'CODE LIKE ''%[1-3]'''
IF @iERROR <> 0
BEGIN
   INSERT #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,0,1,9,0,1,1,'DICTIONARY_REORG_DEP','COL9','CODE',NULL,NULL,NULL,'CODE <> ''0'''
IF @iERROR <> 0
BEGIN
   INSERT #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,0,1,10,0,12,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,1,11,0,11,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, 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


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Раздел 1', @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, 'Раздел 2.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,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,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,'в т.ч. стоимость льготируемого имущества',@iLINK_TABLE,1,0,4,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, 'Раздел 2.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.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,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,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_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,'Налоговая ставка(%)',@iLINK_TABLE,1,0,4,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, 5,'Код льготы/Доля',@iLINK_TABLE,0,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,'Код льготы (2-я часть)',@iLINK_TABLE,0,1,6,0,15,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.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, 'Раздел 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,0,1,0,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,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_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,'Налоговая ставка(%)',@iLINK_TABLE,1,0,4,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, 5,'Код льготы/Доля',@iLINK_TABLE,0,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,'Код льготы (2-я часть)',@iLINK_TABLE,0,1,6,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, 7,'Кадастровый номер',@iLINK_TABLE,0,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


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Раздел 3', @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 (1,1,1,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,4,1)
INSERT #R VALUES (5,2,5,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,9,1)
INSERT #R VALUES (10,2,10,1)
INSERT #R VALUES (1,3,1,1)
INSERT #R VALUES (2,3,2,1)
INSERT #R VALUES (3,3,3,1)
INSERT #R VALUES (4,3,4,1)
INSERT #R VALUES (5,3,5,1)
INSERT #R VALUES (6,3,6,1)
INSERT #R VALUES (7,3,7,1)
INSERT #R VALUES (8,3,8,1)
INSERT #R VALUES (9,3,9,1)
INSERT #R VALUES (10,3,10,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 (9,4,9,1)
INSERT #R VALUES (10,4,10,1)
INSERT #R VALUES (11,4,11,1)
INSERT #R VALUES (12,4,12,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 33
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,'Блок1                                                                                                                                                                                                                                                     ')
INSERT #F VALUES (1,1,2,'АВПЛАТ3_НАСТРОЙКА(К.СТР.)')
INSERT #F VALUES (1,1,3,'АВПЛАТ3_НАСТРОЙКА("О_К_Т_М_О")')
INSERT #F VALUES (1,1,6,'214')
INSERT #F VALUES (1,1,7,'3')
INSERT #F VALUES (1,1,8,'АВПЛАТ3_НАСТРОЙКА("КОД_НАЛ_ПЕР")')
INSERT #F VALUES (2,1,1,'01.01                                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,2,1,'01.02                                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,3,1,'01.03                                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,4,1,'01.04                                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,5,1,'01.05                                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,6,1,'01.06                                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,7,1,'01.07                                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,8,1,'01.08                                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,9,1,'01.09                                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,10,1,'01.10                                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,1,2,'020')
INSERT #F VALUES (2,2,2,'030')
INSERT #F VALUES (2,3,2,'040')
INSERT #F VALUES (2,4,2,'050')
INSERT #F VALUES (2,5,2,'060')
INSERT #F VALUES (2,6,2,'070')
INSERT #F VALUES (2,7,2,'080')
INSERT #F VALUES (2,8,2,'090')
INSERT #F VALUES (2,9,2,'100')
INSERT #F VALUES (2,10,2,'110')
INSERT #F VALUES (2,1,3,'АВПЛАТ3_УСТАНОВКА() + АВПЛАТ3_ИМУЩ(К.СТР.,"ВСЕГО")                                                                                                                                                                                                        ')
INSERT #F VALUES (2,2,3,'АВПЛАТ3_ИМУЩ(К.СТР.,"ВСЕГО")                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,3,3,'АВПЛАТ3_ИМУЩ(К.СТР.,"ВСЕГО")                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,4,3,'АВПЛАТ3_ИМУЩ(К.СТР.,"ВСЕГО")                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,5,3,'АВПЛАТ3_ИМУЩ(К.СТР.,"ВСЕГО")                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,6,3,'АВПЛАТ3_ИМУЩ(К.СТР.,"ВСЕГО")                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,7,3,'АВПЛАТ3_ИМУЩ(К.СТР.,"ВСЕГО")                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,8,3,'АВПЛАТ3_ИМУЩ(К.СТР.,"ВСЕГО")                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,9,3,'АВПЛАТ3_ИМУЩ(К.СТР.,"ВСЕГО")                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,10,3,'АВПЛАТ3_ИМУЩ(К.СТР.,"ВСЕГО")                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,1,4,'АВПЛАТ3_ИМУЩ(К.СТР.,"НЕОБЛ")                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,2,4,'АВПЛАТ3_ИМУЩ(К.СТР.,"НЕОБЛ")                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,3,4,'АВПЛАТ3_ИМУЩ(К.СТР.,"НЕОБЛ")                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,4,4,'АВПЛАТ3_ИМУЩ(К.СТР.,"НЕОБЛ")                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,5,4,'АВПЛАТ3_ИМУЩ(К.СТР.,"НЕОБЛ")                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,6,4,'АВПЛАТ3_ИМУЩ(К.СТР.,"НЕОБЛ")                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,7,4,'АВПЛАТ3_ИМУЩ(К.СТР.,"НЕОБЛ")                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,8,4,'АВПЛАТ3_ИМУЩ(К.СТР.,"НЕОБЛ")                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,9,4,'АВПЛАТ3_ИМУЩ(К.СТР.,"НЕОБЛ")                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,10,4,'АВПЛАТ3_ИМУЩ(К.СТР.,"НЕОБЛ")                                                                                                                                                                                                                              ')
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,'Остаточная стоимость основных средств по состоянию на 01.04, 01.07, 01.10                                                                                                                                                                                 ')
INSERT #F VALUES (3,1,2,'120                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,2,2,'130                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,3,2,'140                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,4,2,'150                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,5,2,'160                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,6,2,'170                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,7,2,'180                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,8,2,'190                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,9,2,'200                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,10,2,'210                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,1,3,'АВПЛАТ3_СРЕДНЯЯ("ВСЕГО")')
INSERT #F VALUES (3,2,3,'ЗАПРЕТ ()')
INSERT #F VALUES (3,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,'АВПЛАТ3_СУМАВАНС()')
INSERT #F VALUES (3,8,3,'ЗАПРЕТ ()')
INSERT #F VALUES (3,9,3,'АВПЛАТ3_ЛЬГОТА()')
INSERT #F VALUES (3,1,4,'ЗАПРЕТ ()')
INSERT #F VALUES (3,2,4,'ЗАПРЕТ ()')
INSERT #F VALUES (3,3,4,'ЗАПРЕТ ()')
INSERT #F VALUES (3,4,4,'ЗАПРЕТ ()')
INSERT #F VALUES (3,5,4,'ЗАПРЕТ ()')
INSERT #F VALUES (3,6,4,'АВПЛАТ3_НАСТРОЙКА("210")')
INSERT #F VALUES (3,7,4,'ЗАПРЕТ ()')
INSERT #F VALUES (3,8,4,'ЗАПРЕТ ()')
INSERT #F VALUES (3,9,4,'ЗАПРЕТ ()')
INSERT #F VALUES (3,10,4,'ЗАПРЕТ ()')
INSERT #F VALUES (3,1,5,'ЗАПРЕТ ()')
INSERT #F VALUES (3,2,5,'АВПЛАТ3_НАСТРОЙКА("160")')
INSERT #F VALUES (3,3,5,'ЗАПРЕТ ()')
INSERT #F VALUES (3,5,5,'АВПЛАТ3_НАСТРОЙКА("200")')
INSERT #F VALUES (3,6,5,'ЗАПРЕТ ()')
INSERT #F VALUES (3,7,5,'ЗАПРЕТ ()')
INSERT #F VALUES (3,8,5,'АВПЛАТ3_НАСТРОЙКА("240")')
INSERT #F VALUES (3,9,5,'ЗАПРЕТ ()')
INSERT #F VALUES (3,10,5,'ЗАПРЕТ ()')
INSERT #F VALUES (3,1,6,'ЗАПРЕТ ()')
INSERT #F VALUES (3,3,6,'ЗАПРЕТ ()')
INSERT #F VALUES (3,4,6,'ЗАПРЕТ ()')
INSERT #F VALUES (3,6,6,'ЗАПРЕТ ()')
INSERT #F VALUES (3,7,6,'ЗАПРЕТ ()')
INSERT #F VALUES (3,9,6,'ЗАПРЕТ ()')
INSERT #F VALUES (3,10,6,'ЗАПРЕТ ()')
INSERT #F VALUES (4,1,1,'Кадастровый номер здания (строения, сооружения)                                                                                                                                                                                                           ')
INSERT #F VALUES (4,2,1,'Кадастровый номер помещения                                                                                                                                                                                                                               ')
INSERT #F VALUES (4,7,1,'Код налоговой льготы (установленной в виде понижения налоговой ставки)                                                                                                                                                                                    ')
INSERT #F VALUES (4,3,1,'Кадастровая стоимость на 1 января налогового периода                                                                                                                                                                                                      ')
INSERT #F VALUES (4,4,1,'в том числе необлагаемая налогом кадастровая стоимость                                                                                                                                                                                                    ')
INSERT #F VALUES (4,5,1,'Код налоговой льготы                                                                                                                                                                                                                                      ')
INSERT #F VALUES (4,6,1,'Доля балансовой стоимости объекта недвижимого имущества на территории соответствующего субъекта Российской Федерации                                                                                                                                      ')
INSERT #F VALUES (4,8,1,'Налоговая ставка                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,9,1,'Коэффициент К                                                                                                                                                                                                                                             ')
INSERT #F VALUES (4,10,1,'Сумма авансового платежа по налогу                                                                                                                                                                                                                        ')
INSERT #F VALUES (4,11,1,'Код налоговой льготы (в виде уменьшения суммы налога, подлежащей уплате в бюджет)                                                                                                                                                                         ')
INSERT #F VALUES (4,12,1,'Сумма льготы по авансовому платежу, уменьшающей сумму авансового платежа по налогу, подлежащую уплате в бюджет                                                                                                                                            ')
INSERT #F VALUES (4,1,2,'014                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,2,2,'015                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,7,2,'060                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,3,2,'020                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,4,2,'030                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,5,2,'040                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,6,2,'050                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,8,2,'070                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,9,2,'080                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,10,2,'090                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,11,2,'100                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,12,2,'110                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,1,3,'ЗАПРЕТ ()')
INSERT #F VALUES (4,2,3,'ЗАПРЕТ ()')
INSERT #F VALUES (4,7,3,'ЗАПРЕТ ()')
INSERT #F VALUES (4,5,3,'ЗАПРЕТ ()')
INSERT #F VALUES (4,6,3,'ЗАПРЕТ ()')
INSERT #F VALUES (4,8,3,'ЗАПРЕТ ()')
INSERT #F VALUES (4,9,3,'ЗАПРЕТ ()')
INSERT #F VALUES (4,11,3,'ЗАПРЕТ ()')
INSERT #F VALUES (4,1,4,'ЗАПРЕТ ()')
INSERT #F VALUES (4,2,4,'ЗАПРЕТ ()')
INSERT #F VALUES (4,7,4,'ЗАПРЕТ ()')
INSERT #F VALUES (4,3,4,'ЗАПРЕТ ()')
INSERT #F VALUES (4,4,4,'ЗАПРЕТ ()')
INSERT #F VALUES (4,5,4,'ЗАПРЕТ ()')
INSERT #F VALUES (4,6,4,'ЗАПРЕТ ()')
INSERT #F VALUES (4,9,4,'ЗАПРЕТ ()')
INSERT #F VALUES (4,10,4,'ЗАПРЕТ ()')
INSERT #F VALUES (4,11,4,'ЗАПРЕТ ()')
INSERT #F VALUES (4,12,4,'ЗАПРЕТ ()')
INSERT #F VALUES (4,1,5,'ЗАПРЕТ ()')
INSERT #F VALUES (4,2,5,'ЗАПРЕТ ()')
INSERT #F VALUES (4,3,5,'ЗАПРЕТ ()')
INSERT #F VALUES (4,4,5,'ЗАПРЕТ ()')
INSERT #F VALUES (4,8,5,'ЗАПРЕТ ()')
INSERT #F VALUES (4,10,5,'ЗАПРЕТ ()')
INSERT #F VALUES (4,12,5,'ЗАПРЕТ ()')
INSERT #F VALUES (4,1,6,'ЗАПРЕТ ()')
INSERT #F VALUES (4,2,6,'ЗАПРЕТ ()')
INSERT #F VALUES (4,3,6,'ЗАПРЕТ ()')
INSERT #F VALUES (4,4,6,'ЗАПРЕТ ()')
INSERT #F VALUES (4,6,6,'ЗАПРЕТ ()')
INSERT #F VALUES (4,8,6,'ЗАПРЕТ ()')
INSERT #F VALUES (4,10,6,'ЗАПРЕТ ()')
INSERT #F VALUES (4,12,6,'ЗАПРЕТ ()')
INSERT #F VALUES (4,7,7,'ЗАПРЕТ ()')
INSERT #F VALUES (4,3,7,'ЗАПРЕТ ()')
INSERT #F VALUES (4,4,7,'ЗАПРЕТ ()')
INSERT #F VALUES (4,5,7,'ЗАПРЕТ ()')
INSERT #F VALUES (4,6,7,'ЗАПРЕТ ()')
INSERT #F VALUES (4,8,7,'ЗАПРЕТ ()')
INSERT #F VALUES (4,9,7,'ЗАПРЕТ ()')
INSERT #F VALUES (4,10,7,'ЗАПРЕТ ()')
INSERT #F VALUES (4,11,7,'ЗАПРЕТ ()')
INSERT #F VALUES (4,12,7,'ЗАПРЕТ ()')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 169
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,'т.1стр.Блок1гр.4 =  т.3стр.180гр.3 -  т.3стр.200гр.3',1,0,1,'20140201','','','','AV_IMU','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) <> 1
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,'','','','','','','','','4','Блок1','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','180','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','200','3',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) <> 3
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] = '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] = '7         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'7','Тест',1,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-03-03 15:14:15.653',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-03-03 15:14:15.653'
	BEGIN
		SELECT @vcMessage = 'Форма AV_IMU с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма AV_IMU с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-03-03 15:14:15.653. Обновление отклонено.'
	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. (апр  6 2014  2:41:34:770PM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : РСВ-1 (Расчет по начисленным и уплаченным страховым взносам на ОПС и в ФСС (ФЗ от 24 июля 2009 г. № 212-ФЗ))
-- Дата ввода : 20140101
-- Дата окончания действия :
-- Версия : 2014-04-06 14:41:34.770
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

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-06 14:41:34.770',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',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,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,1,3,'КТСН("_.303.10","ДЛЯ ДАТА<НАЧ.ГОДА")')
INSERT #F VALUES (2,11,3,'АДТКТ("_.303.10","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА<НАЧ.ГОДА") + АДТКТ("_.303.10","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА<НАЧ.ГОДА")')
INSERT #F VALUES (2,12,3,'АДТКТ("_.303.10","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(1)") + АДТКТ("_.303.10","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,13,3,'АДТКТ("_.303.10","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(2)") + АДТКТ("_.303.10","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,14,3,'АДТКТ("_.303.10","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(3)") + АДТКТ("_.303.10","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(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,'АДТКТ("_.303.10","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=НАЧ.ГОДА") + АДТКТ("_.303.10","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,12,4,'АДТКТ("_.303.10","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(1)") + АДТКТ("_.303.10","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,13,4,'АДТКТ("_.303.10","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(2)") + АДТКТ("_.303.10","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,14,4,'АДТКТ("_.303.10","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(3)") + АДТКТ("_.303.10","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
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,'АДТКТ("_.303.11","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=НАЧ.ГОДА") + АДТКТ("_.303.11","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,12,5,'АДТКТ("_.303.11","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(1)") + АДТКТ("_.303.11","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,13,5,'АДТКТ("_.303.11","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(2)") + АДТКТ("_.303.11","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,14,5,'АДТКТ("_.303.11","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(3)") + АДТКТ("_.303.11","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
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) <> 678
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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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,'20140401','','','','РСВ-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-06 14:41:34.770',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-06 14:41:34.770'
	BEGIN
		SELECT @vcMessage = 'Форма РСВ-1 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма РСВ-1 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-04-06 14:41:34.770. Обновление отклонено.'
	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
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'SPO_USL_TRUDA' AND ltrim(rtrim(code)) = 'О4')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'SPO_USL_TRUDA',
			'О4', 
			'Класс условий труда - опасный; Подкласс условий труда - 4',
			'20140101'
END 	
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'SPO_USL_TRUDA' AND ltrim(rtrim(code)) = 'В3.4')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'SPO_USL_TRUDA',
			'В3.4', 
			'Класс условий труда - вредный; Подкласс условий труда - 3.4 (вредные условия труда 4-й степени)',
			'20140101'
END
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'SPO_USL_TRUDA' AND ltrim(rtrim(code)) = 'В3.3')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'SPO_USL_TRUDA',
			'В3.3', 
			'Класс условий труда – вредный; Подкласс условий труда – 3.3 (вредные условия труда 3-й степени)',
			'20140101'
END 
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'SPO_USL_TRUDA' AND ltrim(rtrim(code)) = 'В3.2')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'SPO_USL_TRUDA',
			'В3.2', 
			'Класс условий труда – вредный; Подкласс условий труда – 3.2 (вредные условия труда 2-й степени)',
			'20140101'
END 	
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'SPO_USL_TRUDA' AND ltrim(rtrim(code)) = 'В3.1')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'SPO_USL_TRUDA',
			'В3.1', 
			'Класс условий труда – вредный; Подкласс условий труда – 3.1 (вредные условия труда 1-й степени)',
			'20140101'
END 


GO
/****** Объект: Дополнение к основанию******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'VAC_REASON_DOP')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'VAC_REASON_DOP')
	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 = 'VAC_REASON_DOP')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'VAC_REASON_DOP')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'VAC_REASON_DOP'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'VAC_REASON_DOP')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='VAC_REASON_DOP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'VAC_REASON_DOP', 'Дополнение к основанию', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='VACATION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'VAC_REASON_DOP', NAME = 'Дополнение к основанию', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='VACATION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='VAC_REASON_DOP'
GO
EXEC X_SET_PROP 'VAC_REASON_DOP', 'TITLE', 'Дополнение к основанию'
GO
EXEC X_SET_PROP 'VAC_REASON_DOP', 'VISIBLE', '27'
GO
EXEC X_SET_PROP 'VAC_REASON_DOP', 'CONTROLSOURCE', 'm.cAlias+".REASON_DOP"'
GO
EXEC X_SET_PROP 'VAC_REASON_DOP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'VAC_REASON_DOP', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'VAC_REASON_DOP', 'TYPE_FIELD_DICT', 'VARCHAR(500)'
GO
EXEC X_SET_PROP 'VAC_REASON_DOP', 'SHORT_CODE_OBJ', 'REASON_DOP'
GO
EXEC X_SET_PROP 'VAC_REASON_DOP', 'CONTROLSOURCE_EDIT', 'm.cAlias+".REASON_DOP"'
GO
EXEC X_SET_PROP 'VAC_REASON_DOP', 'CONTROL_NAME_EDIT', 'Edit15'
GO
EXEC X_SET_PROP 'VAC_REASON_DOP', 'REFERENCE_TO_FIELD', 'REASON_DOP'
GO
EXEC X_SET_PROP 'VAC_REASON_DOP', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'VAC_REASON_DOP', 'ATTRIBUTES', 'style="Z-INDEX: 133; LEFT: 200px; POSITION: absolute; TOP: 392px""
Width="424px"'
GO
EXEC X_SET_PROP 'VAC_REASON_DOP', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 132; LEFT: 24px; POSITION: absolute; TOP: 392px"'
GO
EXEC X_SET_PROP 'VAC_REASON_DOP', 'FIELD_DATA', 'reason_dop'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
